Programs & Examples On #Windows phone 7

Windows Phone is Microsoft's mobile operating system and software development platform. Use this tag for questions specific to Version 7.x

Add custom header in HttpWebRequest

You can add values to the HttpWebRequest.Headers collection.

According to MSDN, it should be supported in windows phone: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.95%29.aspx

How to hash a password

Based on csharptest.net's great answer, I have written a Class for this:

public static class SecurePasswordHasher
{
    /// <summary>
    /// Size of salt.
    /// </summary>
    private const int SaltSize = 16;

    /// <summary>
    /// Size of hash.
    /// </summary>
    private const int HashSize = 20;

    /// <summary>
    /// Creates a hash from a password.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="iterations">Number of iterations.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password, int iterations)
    {
        // Create salt
        byte[] salt;
        new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);

        // Create hash
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        var hash = pbkdf2.GetBytes(HashSize);

        // Combine salt and hash
        var hashBytes = new byte[SaltSize + HashSize];
        Array.Copy(salt, 0, hashBytes, 0, SaltSize);
        Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);

        // Convert to base64
        var base64Hash = Convert.ToBase64String(hashBytes);

        // Format hash with extra information
        return string.Format("$MYHASH$V1${0}${1}", iterations, base64Hash);
    }

    /// <summary>
    /// Creates a hash from a password with 10000 iterations
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password)
    {
        return Hash(password, 10000);
    }

    /// <summary>
    /// Checks if hash is supported.
    /// </summary>
    /// <param name="hashString">The hash.</param>
    /// <returns>Is supported?</returns>
    public static bool IsHashSupported(string hashString)
    {
        return hashString.Contains("$MYHASH$V1$");
    }

    /// <summary>
    /// Verifies a password against a hash.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="hashedPassword">The hash.</param>
    /// <returns>Could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        // Check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        // Extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$MYHASH$V1$", "").Split('$');
        var iterations = int.Parse(splittedHashString[0]);
        var base64Hash = splittedHashString[1];

        // Get hash bytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        // Get salt
        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        // Create hash with given salt
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        byte[] hash = pbkdf2.GetBytes(HashSize);

        // Get result
        for (var i = 0; i < HashSize; i++)
        {
            if (hashBytes[i + SaltSize] != hash[i])
            {
                return false;
            }
        }
        return true;
    }
}

Usage:

// Hash
var hash = SecurePasswordHasher.Hash("mypassword");

// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);

A sample hash could be this:

$MYHASH$V1$10000$Qhxzi6GNu/Lpy3iUqkeqR/J1hh8y/h5KPDjrv89KzfCVrubn

As you can see, I also have included the iterations in the hash for easy usage and the possibility to upgrade this, if we need to upgrade.


If you are interested in .net core, I also have a .net core version on Code Review.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Setting the User-Agent header for a WebClient request

I found that the WebClient kept removing my User-Agent header after one request and I was tired of setting it each time. I used a hack to set the User-Agent permanently by making my own custom WebClient and overriding the GetWebRequest method. Hope this helps.

public class CustomWebClient : WebClient
{
    public CustomWebClient(){}

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        request.UserAgent="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0;)";

        //... your other custom code...

        return request;
    }
}

Calculating Distance between two Latitude and Longitude GeoCoordinates

For those who are using Xamarin and don't have access to the GeoCoordinate class, you can use the Android Location class instead:

public static double GetDistanceBetweenCoordinates (double lat1, double lng1, double lat2, double lng2) {
            var coords1 = new Location ("");
            coords1.Latitude = lat1;
            coords1.Longitude = lng1;
            var coords2 = new Location ("");
            coords2.Latitude = lat2;
            coords2.Longitude = lng2;
            return coords1.DistanceTo (coords2);
        }

How to POST request using RestSharp

As of 2017 I post to a rest service and getting the results from it like that:

        var loginModel = new LoginModel();
        loginModel.DatabaseName = "TestDB";
        loginModel.UserGroupCode = "G1";
        loginModel.UserName = "test1";
        loginModel.Password = "123";

        var client = new RestClient(BaseUrl);

        var request = new RestRequest("/Connect?", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(loginModel);

        var response = client.Execute(request);

        var obj = JObject.Parse(response.Content);

        LoginResult result = new LoginResult
        {
            Status = obj["Status"].ToString(),
            Authority = response.ResponseUri.Authority,
            SessionID = obj["SessionID"].ToString()
        };

Programmatically set TextBlock Foreground Color

 textBlock.Foreground = new SolidColorBrush(Colors.White);

How to trigger event when a variable's value is changed?

you can use generic class:

class Wrapped<T>  {
    private T _value;

    public Action ValueChanged;

    public T Value
    {
        get => _value;

        set
        {
            _value = value;
            OnValueChanged();
        }
    }

    protected virtual void OnValueChanged() => ValueChanged?.Invoke() ;
}

and will be able to do the following:

var i = new Wrapped<int>();

i.ValueChanged += () => { Console.WriteLine("changed!"); };

i.Value = 10;
i.Value = 10;
i.Value = 10;
i.Value = 10;

Console.ReadKey();

result:

changed!
changed!
changed!
changed!
changed!
changed!
changed!

Converting a JToken (or string) to a given Type

var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);

Convert List<T> to ObservableCollection<T> in WP7

Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T> or List<T> are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.

I guess your only option is to take your list and add the items into a new instance of an ObservableCollection individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.

var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
    oc.Add(item);

But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.

Deserializing JSON array into strongly typed .NET object

I suspect the problem is because the json represents an object with the list of users as a property. Try deserializing to something like:

public class UsersResponse
{
    public List<User> Data { get; set; }
}

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

Because it's not.

Indexing is covered by IList. IEnumerable means "I have some of the powers of IList, but not all of them."

Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.

How to get status code from webclient?

Tried it out. ResponseHeaders do not include status code.

If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

The status code unfortunately isn't present in the ResponseHeaders dictionary.

Consistency of hashCode() on a Java string

I can see that documentation as far back as Java 1.2.

While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String, so changing it would count as breaking existing contracts.

Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

Web Reference vs. Service Reference

If I understand your question right:

To add a .net 2.0 Web Service Reference instead of a WCF Service Reference, right-click on your project and click 'Add Service Reference.'

Then click "Advanced.." at the bottom left of the dialog.

Then click "Add Web Reference.." on the bottom left of the next dialog.

Now you can add a regular SOAP web reference like you are looking for.

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

Converting Date and Time To Unix Timestamp

You can use Date.getTime() function, or the Date object itself which when divided returns the time in milliseconds.

var d = new Date();

d/1000
> 1510329641.84

d.getTime()/1000
> 1510329641.84

How do I set headers using python's urllib?

Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html

I dont really use the "old" urllib anymore.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

untested....

Simple way to understand Encapsulation and Abstraction

data abstraction: accessing data members and member functions of any class is simply called data abstraction.....

encapsulation: binding variables and functions or 1 can say data members or member functions all together in a single unit is called as data encapsulation....

Error to run Android Studio

On ubuntu I have tried all the methods that are described here but none worked.

What I did in the end was to:

  • download JDK from oracle, extract the archive

  • edit android-studio/bin/studio.sh and add at the top

    export JAVA_HOME=/path/to/jdk

  • save the file and cd android-studio/bin and launch Android Studio: ./studio.sh

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

Making a button invisible by clicking another button in HTML

  1. getElementById returns a single object for which you can specify the style.So, the above explanation is correct.

  2. getElementsByTagName returns multiple objects(array of objects and properties) for which we cannot apply the style directly.

How do I catch an Ajax query post error?

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

Loop through a comma-separated shell variable

Another solution not using IFS and still preserving the spaces:

$ var="a bc,def,ghij"
$ while read line; do echo line="$line"; done < <(echo "$var" | tr ',' '\n')
line=a bc
line=def
line=ghij

How to perform a for-each loop over all the files under a specified path?

The for-loop will iterate over each (space separated) entry on the provided string.

You do not actually execute the find command, but provide it is as string (which gets iterated by the for-loop). Instead of the double quotes use either backticks or $():

for line in $(find . -iname '*.txt'); do 
     echo "$line"
     ls -l "$line"
done

Furthermore, if your file paths/names contains spaces this method fails (since the for-loop iterates over space separated entries). Instead it is better to use the method described in dogbanes answer.


To clarify your error:

As said, for line in "find . -iname '*.txt'"; iterates over all space separated entries, which are:

  • find
  • .
  • -iname
  • '*.txt' (I think...)

The first two do not result in an error (besides the undesired behavior), but the third is problematic as it executes:

ls -l -iname

A lot of (bash) commands can combine single character options, so -iname is the same as -i -n -a -m -e. And voila: your invalid option -- 'e' error!

Inherit CSS class

You could also use the !important feature of css to make qualities you do not want to override in the original class. I am using this on my site to keep some of the essential characteristics of the original class while overriding others:

<div class="foo bar">
.foo {
color: blue;
width: 200px  !important;
}

.bar {
color: red;
width: 400px;
}

This will generate a class "foo bar" element that is red and 200px. This is great if you are using the other two classes individually and just want a piece from each class.

Explaining Python's '__enter__' and '__exit__'

If you know what context managers are then you need nothing more to understand __enter__ and __exit__ magic methods. Lets see a very simple example.

In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.

fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
    for line in fp:
        print(line)
finally:
    fp.close()

Now I am opening same file with with statement:

with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
    for line in fp:
        print(line) 

If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed) attribute -- which returns True.

This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__ and __exit__. It is also known as context manager. __enter__ method is called at the start of with block and __exit__ method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__ and __exit__ methods. A class which implement both methods is known as context manager class.

Now lets define our own context manager class.

 class Log:
    def __init__(self,filename):
        self.filename=filename
        self.fp=None    
    def logging(self,text):
        self.fp.write(text+'\n')
    def __enter__(self):
        print("__enter__")
        self.fp=open(self.filename,"a+")
        return self    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.fp.close()

with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
    print("Main")
    logfile.logging("Test1")
    logfile.logging("Test2")

I hope now you have basic understanding of both __enter__ and __exit__ magic methods.

"Correct" way to specifiy optional arguments in R functions

I would tend to prefer using NULL for the clarity of what is required and what is optional. One word of warning about using default values that depend on other arguments, as suggested by Jthorpe. The value is not set when the function is called, but when the argument is first referenced! For instance:

foo <- function(x,y=length(x)){
    x <- x[1:10]
    print(y)
}
foo(1:20) 
#[1] 10

On the other hand, if you reference y before changing x:

foo <- function(x,y=length(x)){
    print(y)
    x <- x[1:10]
}
foo(1:20) 
#[1] 20

This is a bit dangerous, because it makes it hard to keep track of what "y" is being initialized as if it's not called early on in the function.

Find all elements with a certain attribute value in jquery

Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:

$("*[attr-name]")

Hope that helps somebody who happens to land on this page looking for the same thing that I was :).

Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):

$("[attr-name]")

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

How to get the difference between two arrays of objects in JavaScript

I think the @Cerbrus solution is spot on. I have implemented the same solution but extracted the repeated code into it's own function (DRY).

 function filterByDifference(array1, array2, compareField) {
  var onlyInA = differenceInFirstArray(array1, array2, compareField);
  var onlyInb = differenceInFirstArray(array2, array1, compareField);
  return onlyInA.concat(onlyInb);
}

function differenceInFirstArray(array1, array2, compareField) {
  return array1.filter(function (current) {
    return array2.filter(function (current_b) {
        return current_b[compareField] === current[compareField];
      }).length == 0;
  });
}

How to implement class constructor in Visual Basic?

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

Best practice to run Linux service as a different user

On Debian we use the start-stop-daemon utility, which handles pid-files, changing the user, putting the daemon into background and much more.

I'm not familiar with RedHat, but the daemon utility that you are already using (which is defined in /etc/init.d/functions, btw.) is mentioned everywhere as the equivalent to start-stop-daemon, so either it can also change the uid of your program, or the way you do it is already the correct one.

If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize, for example.

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How to convert an entire MySQL database characterset and collation to UTF-8?

You can also DB tool Navicat, which does it more easier.

  • Siva.

Right Click Your Database & select DB Properties & Change as you desired in Drop Down

enter image description here

Checkout one file from Subversion

You can do it in two steps:

  1. Checkout an empty SVN repository with meta information only:

    $ cd /tmp
    
    $ svn co --depth empty http://svn.your.company.ca/training/trunk/sql
    
  2. Run svn up to update specified file:

    $ svn up http://svn.your.company.ca/training/trunk/sql/showSID.sql
    

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

You should now use DbFunctions.TruncateTime

var anyCalls = _db.CallLogs.Where(r => DbFunctions.TruncateTime(r.DateTime) == callDateTime.Date).ToList();

How do I get the width and height of a HTML5 canvas?

It might be worth looking at a tutorial: MDN Canvas Tutorial

You can get the width and height of a canvas element simply by accessing those properties of the element. For example:

var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;

If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:

const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;

Or using the shorter object destructuring syntax:

const { width, height } = canvas.getBoundingClientRect();

The context is an object you get from the canvas to allow you to draw into it. You can think of the context as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.

Spring security CORS Filter

With SpringBoot 2 Spring Security, The code below perfectly resolved Cors issues

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("*")); // <-- you may change "*"
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(Arrays.asList(
            "Accept", "Origin", "Content-Type", "Depth", "User-Agent", "If-Modified-Since,",
            "Cache-Control", "Authorization", "X-Req", "X-File-Size", "X-Requested-With", "X-File-Name"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Bean
public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() {
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource()));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}

Then for the WebSecurity Configuration, I added this

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable()
            .and()
            .authorizeRequests()
            .antMatchers("/oauth/tokeen").permitAll()
            .antMatchers(HttpMethod.GET, "/").permitAll()
            .antMatchers(HttpMethod.POST, "/").permitAll()
            .antMatchers(HttpMethod.PUT, "/").permitAll()
            .antMatchers(HttpMethod.DELETE, "/**").permitAll()
            .antMatchers(HttpMethod.OPTIONS, "*").permitAll()
            .anyRequest().authenticated()
            .and().cors().configurationSource(corsConfigurationSource());
}

jQuery get values of checked checkboxes into array

You need to add .toArray() to the end of your .map() function

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Webpack how to build production code and how to use it

You can add the plugins as suggested by @Vikramaditya. Then to generate the production build. You have to run the the command

NODE_ENV=production webpack --config ./webpack.production.config.js

If using babel, you will also need to prefix BABEL_ENV=node to the above command.

Changing MongoDB data store directory

The following command will work for you, if you want to change default path. Just type this in bin directory of mongodb.

mongod --dbpath=yourdirectory\data\db

In case you want to move existing data too, then just copy all the folders from existing data\db directory to new directory before you execute the command.

And also stop existing mongodb services which are running.

Check if URL has certain string with PHP

Starting with PHP 8 (2020-11-24), you can use str_contains:

if (str_contains('www.domain.com/car/', 'car')) {
   echo 'car is exist';
} else {
   echo 'no cars';
}

How to break/exit from a each() function in JQuery?

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

Centering Bootstrap input fields

Well in my case the following work fine

<div class="card-body p-2">
  <div class="d-flex flex-row justify-content-center">
     <div style="margin: auto;">
        <input type="text" autocomplete="off"
          style="max-width:150px!important; "
          class="form-control form-control-sm font-weight-bold align-self-center w-25" id="dtTechState">
     </div>
  </div>
</div>

How to get the Mongo database specified in connection string in C#

Update:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

var _server = new MongoClient(connectionString).GetServer();

It's easy. You should first take database name from connection string and then get database by name. Complete example:

var connectionString = "mongodb://localhost:27020/mydb";

//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);

//and then get database by database name:
_server.GetDatabase(_databaseName);

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

How to check if a process is in hang state (Linux)

Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

Django Multiple Choice Field / Checkbox Select Multiple

The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).

You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.

There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField.

How can I count the number of matches for a regex?

From Java 9, you can use the stream provided by Matcher.results()

long matches = matcher.results().count();

Why is Java's SimpleDateFormat not thread-safe?

Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.

How to compile without warnings being treated as errors?

Sure, find where -Werror is set and remove that flag. Then warnings will be only warnings.

How to set UITextField height?

swift3

@IBDesignable
class BigTextField: UITextField {
    override func didMoveToWindow() {
        super.didMoveToWindow()
        if window != nil {
            borderStyle = .roundedRect
        }
    }
}

Interface Builder

  • Replace UITextField with BigTextField.
  • Change the Border Style to none.

How to create an empty R vector to add new items

In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2

For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors

How to make the 'cut' command treat same sequental delimiters as one?

As you comment in your question, awk is really the way to go. To use cut is possible together with tr -s to squeeze spaces, as kev's answer shows.

Let me however go through all the possible combinations for future readers. Explanations are at the Test section.

tr | cut

tr -s ' ' < file | cut -d' ' -f4

awk

awk '{print $4}' file

bash

while read -r _ _ _ myfield _
do
   echo "forth field: $myfield"
done < file

sed

sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file

Tests

Given this file, let's test the commands:

$ cat a
this   is    line     1 more text
this      is line    2     more text
this    is line 3     more text
this is   line 4            more    text

tr | cut

$ cut -d' ' -f4 a
is
                        # it does not show what we want!


$ tr -s ' ' < a | cut -d' ' -f4
1
2                       # this makes it!
3
4
$

awk

$ awk '{print $4}' a
1
2
3
4

bash

This reads the fields sequentially. By using _ we indicate that this is a throwaway variable as a "junk variable" to ignore these fields. This way, we store $myfield as the 4th field in the file, no matter the spaces in between them.

$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4

sed

This catches three groups of spaces and no spaces with ([^ ]*[ ]*){3}. Then, it catches whatever coming until a space as the 4th field, that it is finally printed with \1.

$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4

Create a custom callback in JavaScript

Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.

The basics

function doSomething(callback) {
    // ...

    // Call the callback
    callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
    // I'm the callback
    alert(a + " " + b + " " + c);
}

doSomething(foo);

That will call doSomething, which will call foo, which will alert "stuff goes here".

Note that it's very important to pass the function reference (foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it's just worth pointing out because it's a common error.

More advanced stuff

Sometimes you want to call the callback so it sees a specific value for this. You can easily do that with the JavaScript call function:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.call(this);
}

function foo() {
    alert(this.name);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Joe" via `foo`

You can also pass arguments:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
    // Call our callback, but using our own instance as the context
    callback.call(this, salutation);
}

function foo(salutation) {
    alert(salutation + " " + this.name);
}

var t = new Thing('Joe');
t.doSomething(foo, 'Hi');  // Alerts "Hi Joe" via `foo`

Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.apply(this, ['Hi', 3, 2, 1]);
}

function foo(salutation, three, two, one) {
    alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Hi Joe - 3 2 1" via `foo`

mysql_fetch_array() expects parameter 1 to be resource problem

You are using this :

mysql_fetch_array($result)

To get the error you're getting, it means that $result is not a resource.


In your code, $result is obtained this way :

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);

If the SQL query fails, $result will not be a resource, but a boolean -- see mysql_query.

I suppose there's an error in your SQL query -- so it fails, mysql_query returns a boolean, and not a resource, and mysql_fetch_array cannot work on that.


You should check if the SQL query returns a result or not :

$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
    // use $result
} else {
    // an error has occured
    echo mysql_error();
    die;    // note : echoing the error message and dying 
            // is OK while developping, but not in production !
}

With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)


Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !

For example, here, you should make sure that $_GET['id'] contains nothing else than an integer, using something like this :

$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));

Or you should check this before trying to execute the query, to display a nicer error message to the user.

Peak memory usage of a linux/unix process

Perhaps (gnu) time(1) already does what you want. For instance:

$ /usr/bin/time -f "%P %M" command
43% 821248

But other profiling tools may give more accurate results depending on what you are looking for.

Find first element by predicate

In addition to Alexis C's answer, If you are working with an array list, in which you are not sure whether the element you are searching for exists, use this.

Integer a = list.stream()
                .peek(num -> System.out.println("will filter " + num))
                .filter(x -> x > 5)
                .findFirst()
                .orElse(null);

Then you could simply check whether a is null.

Programmatically center TextView text

TextView text = new TextView(this);

text.setGravity(Gravity.CENTER);

and

text.setGravity(Gravity.TOP);

and

text.setGravity(Gravity.BOTTOM);

and

text.setGravity(Gravity.LEFT);

and

text.setGravity(Gravity.RIGHT);

and

text.setGravity(Gravity.CENTER_VERTICAL);

and

text.setGravity(Gravity.CENTER_HORIZONTAL);

And More Also Avaliable

Easiest way to convert month name to month number in JS ? (Jan = 01)

One more way to do the same

month1 = month1.toLowerCase();
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
month1 = months.indexOf(month1);

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

ran into this issue while trying to connect mysql in SSH client, found adding the socket path to the command helpful when switching between sockets is necessary.

> mysql -u user -p --socket=/path/to/mysql5143.sock

Getting All Variables In Scope

How much time do you have?

If you hate your cpu you can bruteforce through every valid variable name, and eval each one to see if it results in a value!

The following snippet tries the first 1000 bruteforce strings, which is enough to find the contrived variable names in scope:

_x000D_
_x000D_
let alpha = 'abcdefghijklmnopqrstuvwxyz';
let everyPossibleString = function*() {
  yield '';
  for (let prefix of everyPossibleString()) for (let char of alpha) yield `${prefix}${char}`;
};
let allVarsInScope = (iterations=1000) => {  
  let results = {};
  let count = 0;
  for (let bruteforceString of everyPossibleString()) {
    if (!bruteforceString) continue; // Skip the first empty string
    try { results[bruteforceString] = eval(bruteforceString); } catch(err) {}
    if (count++ > iterations) break;
  }
  return results;
};

let myScope = (() => {
    
  let dd = 'ddd';
  let ee = 'eee';
  let ff = 'fff';
  
  ((gg, hh) => {
    
    // We can't call a separate function, since that function would be outside our
    // scope and wouldn't be able to see any variables - but we can define the
    // function in place (using `eval(allVarsInScope.toString())`), and then call
    // that defined-in-place function
    console.log(eval(allVarsInScope.toString())());
    
  })('ggg', 'hhh');
  
})();
_x000D_
_x000D_
_x000D_

This script will eventually (after a very long time) find all scoped variable names, as well as abc nifty and swell, some example variables I created. Note it will only find variable names consisting of alpha characters.

_x000D_
_x000D_
let preElem = document.getElementsByClassName('display')[0];
let statusElem = document.getElementsByClassName('status')[0];
let alpha = 'abcdefghijklmnopqrstuvwxyz';
alpha += alpha.toUpperCase();
let everyPossibleString = function*() {
  yield '';
  for (let prefix of everyPossibleString()) for (let char of alpha) yield `${prefix}${char}`;
};

(async () => {
  
  let abc = 'This is the ABC variable :-|';
  let neato = 'This is the NEATO variable :-)';
  let swell = 'This is the SWELL variable :-D';
  
  let results = {};
  let batch = 25000;
  let waitMs = 25;
  let count = 0;
  let startStr = null;

  for (let bruteStr of everyPossibleString()) {
    
    try {

      if (bruteStr === '') continue;
      if (startStr === null) startStr = bruteStr;

      try { results[bruteStr] = eval(bruteStr); } catch(err) {}

      if (count++ >= batch) {
        
        statusElem.innerHTML = `Did batch of ${batch} from ${startStr} -> ${bruteStr}`;
        preElem.innerHTML = JSON.stringify(results, null, 2);
        
        count = 0;
        startStr = null;
        await new Promise(r => setTimeout(r, waitMs));

      }
      
    } catch(err) {
      
      // It turns out some global variables are protected by stackoverflow's snippet
      // system (these include "top", "self", and "this"). If these values are touched
      // they result in a weird iframe error, captured in this `catch` statement. The
      // program can recover by replacing the most recent `result` value (this will be
      // the value which causes the error).
      let lastEntry = Object.entries(results).slice(-1)[0];
      results[lastEntry[0]] = '<a protected value>';
            
    }

  }
  
  console.log('Done...'); // Will literally never happen

})();
_x000D_
html, body { position: fixed; left: 0; top: 0; right: 0; bottom: 0; margin: 0; padding: 0; overflow: hidden }
.display {
  position: fixed;
  box-sizing: border-box;
  left: 0; top: 0;
  bottom: 30px; right: 0;
  overflow-y: scroll;
  white-space: pre;
  font-family: monospace;
  padding: 10px;
  box-shadow: inset 0 0 10px 1px rgba(0, 0, 0, 0.3);
}
.status {
  position: fixed;
  box-sizing: border-box;
  left: 0; bottom: 0px; right: 0; height: 30px; line-height: 30px;
  padding: 0 10px;
  background-color: rgba(0, 0, 0, 1);
  color: rgba(255, 255, 255, 1);
  font-family: monospace;
}
_x000D_
<div class="display"></div>
<div class="status"></div>
_x000D_
_x000D_
_x000D_

I am all too aware there is virtually no situation where this is practical

css3 text-shadow in IE9

The answer of crdunst is pretty neat and the best looking answer I've found but there's no explanation on how to use and the code is bigger than needed.

The only code you need:

#element {
    background-color: #cacbcf;
    text-shadow: 2px 2px 4px rgba(0,0,0, 0.5);
    filter: chroma(color=#cacbcf) progid:DXImageTransform.Microsoft.dropshadow(color=#60000000, offX=2, offY=2);
}

First you MUST specify a background-color - if your element should be transparent just copy the background-color of the parent or let it inherit. The color at the chroma-filter must match the background-color to fix those artifacts around the text (but here you must copy the color, you can't write inherit). Note that I haven't shortened the dropshadow-filter - it works but the shadows are then cut to the element dimensions (noticeable with big shadows; try to set the offsets to atleast 4).

TIP: If you want to use colors with transparency (alpha-channel) write in a #AARRGGBB notation, where AA stands for a hexadezimal value of the opacity - from 01 to FE, because FF and ironically also 00 means no transparency and is therefore useless.. ^^ Just go a little lower than in the rgba notation because the shadows aren't soft and the same alpha value would appear darker then. ;)

A nice snippet to convert the alpha value for IE (JavaScript, just paste into the console):

var number = 0.5; //alpha value from the rgba() notation
("0"+(Math.round(0.75 * number * 255).toString(16))).slice(-2);

ISSUES: The text/font behaves like an image after the shadow is applied; it gets pixelated and blurry after you zoom in... But that's IE's issue, not mine.

Live demo of the shadow here: http://jsfiddle.net/12khvfru/2/

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I had a similar problem:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.

In my case, I know the image works in other places, then was a corrupted local image. I solved the issue removing the image (docker rmi <imagename>) and pulling it again(docker pull <imagename>).

I did a docker system prune too, but I think it's not mandatory.

How to convert color code into media.brush?

What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
        <Rectangle.Fill>
            <SolidColorBrush Color="#FF00AE00" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

req.body empty on posts

I was using restify instead of express and ran into the same problem. The solution was to do:

server.use(restify.bodyParser());

Appending the same string to a list of strings in Python

new_list = [word_in_list + end_string for word_in_list in old_list]

Using names such as "list" for your variable names is bad since it will overwrite/override the builtins.

How to fix curl: (60) SSL certificate: Invalid certificate chain

In some systems like your office system, there is sometimes a firewall/security client that is installed for security purpose. Try uninstalling that and then run the command again, it should start the download.

My system had Netskope Client installed and was blocking the ssl communication.

Search in finder -> uninstall netskope, run it, and try installing homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

PS: consider installing the security client.

Proper way to use **kwargs in Python

@AbhinavGupta and @Steef suggested using update(), which I found very helpful for processing large argument lists:

args.update(kwargs)

What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that pop() can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.

Here's another possible way to do this, which keeps the simple syntax of using update():

# kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments

# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
    raise TypeError('Unknown arguments: {}'.format(unknown_args))

# Update args to contain user-supplied arguments
args.update(kwargs)

unknown_args is a set containing the names of arguments that don't occur in the defaults.

Argparse: Required arguments listed under "optional arguments"?

One more time, building off of @RalphyZ

This one doesn't break the exposed API.

from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')

# Add back help 
optional.add_argument(
    '-h',
    '--help',
    action='help',
    default=SUPPRESS,
    help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')

Which will show the same as above and should survive future versions:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

CSS @media print issues with background-color;

If you don't mind using an image instead of a background color(or possibly an image with your background color) the solution below has worked for me in FireFox,Chrome and even IE without any over-rides. Set the image somewhere on the page and hide it until the user prints.

The html on the page with the background image

<img src="someImage.png" class="background-print-img">

The Css

.background-print-img{
    display: none;
}

@media print{
    .background-print-img{
        background:red;
        display: block;
        width:100%;
        height:100%;
        position:absolute;
        left:0;
        top:0;
        z-index:-10;
    }

}

How can I add a hint text to WPF textbox?

You can accomplish this much more easily with a VisualBrush and some triggers in a Style:

<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <Style.Resources>
                <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
                    <VisualBrush.Visual>
                        <Label Content="Search" Foreground="LightGray" />
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                    <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                </Trigger>
                <Trigger Property="Text" Value="{x:Null}">
                    <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="True">
                    <Setter Property="Background" Value="White" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

To increase the re-usability of this Style, you can also create a set of attached properties to control the actual cue banner text, color, orientation etc.

Play sound on button click android

there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.

Nice!

MediaActionSound

A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs

use like:

fun playBeepSound() {
    val sound = MediaActionSound()
    sound.play(MediaActionSound.START_VIDEO_RECORDING)
}

How to make canvas responsive

<div class="outer">
 <canvas id="canvas"></canvas>
</div>    
.outer {
 position: relative;
 width: 100%;
 padding-bottom: 100%;
}

#canvas {
 position: absolute;
 width: 100%;
 height: 100%;
}

Count number of days between two dates

None of the previous answers (to this date) gives the correct difference in days between two dates.

The one that comes closest is by thatdankent. A full answer would convert to_i and then divide:

(Time.now.to_i - 23.hours.ago.to_i) / 86400
>> 0

(Time.now.to_i - 25.hours.ago.to_i) / 86400
>> 1

(Time.now.to_i - 1.day.ago.to_i) / 86400
>> 1

In the question's specific example, one should not parse to Date if the time passed is relevant. Use Time.parse instead.

How to skip the first n rows in sql query

I know it's quite late now to answer the query. But I have a little different solution than the others which I believe has better performance because no comparisons are performed in the SQL query only sorting is done. You can see its considerable performance improvement basically when value of SKIP is LARGE enough.

  1. Best performance but only for SQL Server 2012 and above. Originally from @Majid Basirati's answer which is worth mentioning again.

    DECLARE @Skip INT = 2, @Take INT = 2
    
    SELECT * FROM TABLE_NAME
    ORDER BY ID ASC
    OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY
    
  2. Not as Good as the first one but compatible with SQL Server 2005 and above.

    DECLARE @Skip INT = 2, @Take INT = 2
    
    SELECT * FROM 
    (
        SELECT TOP (@Take) * FROM 
        (
            SELECT TOP (@Take + @Skip) * FROM TABLE_NAME
            ORDER BY ID ASC
        ) T1
        ORDER BY ID DESC
    ) T2
    ORDER BY ID ASC
    

Is Python strongly typed?

A Python variable stores an untyped reference to the target object that represent the value.

Any assignment operation means assigning the untyped reference to the assigned object -- i.e. the object is shared via the original and the new (counted) references.

The value type is bound to the target object, not to the reference value. The (strong) type checking is done when an operation with the value is performed (run time).

In other words, variables (technically) have no type -- it does not make sense to think in terms of a variable type if one wants to be exact. But references are automatically dereferenced and we actually think in terms of the type of the target object.

Is there an effective tool to convert C# code to Java code?

C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern. Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java. If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.

I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen: http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen

(I've been registered with them for a while and they're good about not spamming)

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

The answer is here: http://sysadminsjourney.com/content/2010/02/01/apache-modproxy-error-13permission-denied-error-rhel/

Which is a link to a blog that explains:

SELinux on RHEL/CentOS by default ships so that httpd processes cannot initiate outbound connections, which is just what mod_proxy attempts to do.

If this is the problem, it can be solved by running:

 /usr/sbin/setsebool -P httpd_can_network_connect 1

And for a more definitive source of information, see https://wiki.apache.org/httpd/13PermissionDenied

Check if int is between two numbers

simplifying:

a = 10; b = 15; c = 20

public static boolean check(int a, int b, int c) {
    return a<=b && b<=c;
}

This checks if b is between a and c

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

CSS Auto hide elements after 5 seconds

based from the answer of @SW4, you could also add a little animation at the end.

_x000D_
_x000D_
body > div{_x000D_
    border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
#container {_x000D_
    overflow:hidden;_x000D_
    position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
    -webkit-animation: cssAnimation 5s forwards; _x000D_
    animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
    <div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.

How can I echo HTML in PHP?

Try it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;

How to avoid Python/Pandas creating an index in a saved csv?

Another solution if you want to keep this column as index.

pd.read_csv('filename.csv', index_col='Unnamed: 0')

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

Can I check if Bootstrap Modal Shown / Hidden?

In offical way:

> ($("element").data('bs.modal') || {})._isShown    // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown     // Bootstrap <= 3

{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.

Input group - two inputs close to each other

Assuming you want them next to each other:

<form action="" class="form-inline">
    <div class="form-group">
        <input type="text" class="form-control" placeholder="MinVal">
    </div>
    <div class="form-group">    
         <input type="text" class="form-control" placeholder="MaxVal">   
    </div>
</form>

JSFiddle

Update Nr.1: Should you want to use .input-group with this example:

<form action="" class="form-inline">
    <div class="form-group">
        <div class="input-group">
          <span class="input-group-addon">@</span>
          <input type="text" class="form-control" placeholder="Username">
        </div>
    </div>
    <div class="form-group">    
        <div class="input-group">
          <input type="text" class="form-control">
          <span class="input-group-addon">.00</span>
        </div>
    </div>
</form>

JSFiddle

The class .input-group is there to extend inputs with buttons and such (directly attached). Checkboxes or radio buttons are possible as well. I don't think it works with two input fields though.

Update Nr. 2: With .form-horizontal the .form-group tag basically becomes a .row tag so you can use the column classes such as .col-sm-8:

<form action="" class="form-horizontal">
    <div class="form-group">
        <div class="col-sm-8">
            <input type="text" class="form-control" placeholder="MinVal">
        </div>
        <div class="col-sm-4">
            <input type="text" class="form-control" placeholder="MaxVal">
        </div>
    </div>
</form>

Updated JSFiddle with all three examples

How can I create a progress bar in Excel VBA?

Hi modified version of another post by Marecki. Has 4 styles

1. dots ....
2  10 to 1 count down
3. progress bar (default)
4. just percentage.

Before you ask why I didn't edit that post is I did and it got rejected was told to post a new answer.

Sub ShowProgress()

  Const x As Long = 150000
  Dim i&, PB$

  For i = 1 To x
  DoEvents
  UpdateProgress i, x
  Next i

  Application.StatusBar = ""
End Sub 'ShowProgress

Sub UpdateProgress(icurr As Long, imax As Long, Optional istyle As Integer = 3)
    Dim PB$
    PB = Format(icurr / imax, "00 %")
    If istyle = 1 Then ' text dots >>....    <<'
        Application.StatusBar = "Progress: " & PB & "  >>" & String(Val(PB), Chr(183)) & String(100 - Val(PB), Chr(32)) & "<<"
    ElseIf istyle = 2 Then ' 10 to 1 count down  (eight balls style)
        Application.StatusBar = "Progress: " & PB & "  " & ChrW$(10111 - Val(PB) / 11)
    ElseIf istyle = 3 Then ' solid progres bar (default)
        Application.StatusBar = "Progress: " & PB & "  " & String(100 - Val(PB), ChrW$(9608))
    Else ' just 00 %
        Application.StatusBar = "Progress: " & PB
    End If
End Sub

MongoDB or CouchDB - fit for production?

We are currently using MongoDB in production as the caching layer as well as storage engine for product importing and manipulating product data. We are an eCommerce company managing over two million products (100+ million attributes), spanning 10+ distributors and without MongoDB, this task would be nearing impossible.

Don't change link color when a link is clicked

you are looking for this:

a:visited{
  color:blue;
}

Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)

Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)

a:link{
  color:blue;
}
a:visited{
  color:purple;
}
a:hover{
  color:orange;
}
a:focus{
  color:green;
}
a:active{
  color:red;
}

If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)

If you have different types of links that you want to all have the same color when clicked, add a class to the links.

a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
  color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
  color:orange;
}

It should be noted that not all browsers respect each of these options ;-)

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

The OS failed to install the required update Windows8.1-KB2999226-x64.msu. However I tried to find the particular update from -

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu.

I couldn't find it there so I installed the kb2999226 update from here (Windows 10 Universal C runtime)

Then I installed the update according to my OS and after that It was working fine.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

How can I set the initial value of Select2 when using AJAX?

What I've done is more clean and needs to make two arrays :

  • one contains a list of Object with id and a text (in my case its id and name, depending of your templateResult) (its what you get from ajax query)
  • the second is only an array of ids (selection value)

I initialize select2 using the first array as data, and the second as the val.

An example function with as parameters a dict of id:name.

function initMyList(values) {
    var selected = [];
    var initials = [];

    for (var s in values) {
        initials.push({id: s, name: values[s].name});
        selected.push(s);
    }

    $('#myselect2').select2({
        data: initials,
        ajax: {
            url: "/path/to/value/",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    term: params.term,
                    page: params.page || 1,
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: true
        },
        minimumInputLength: 1,
        tokenSeparators: [",", " "],
        placeholder: "Select none, one or many values",
        templateResult: function (item) { return item.name; },
        templateSelection: function (item) { return item.name; },
        matcher: function(term, text) { return text.name.toUpperCase().indexOf(term.toUpperCase()) != -1; },
    });

    $('#myselect2').val(selected).trigger('change');
}

You can feed the initials value using ajax calls, and use jquery promises to do the select2 initialization.

Cross-Origin Read Blocking (CORB)

Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page.

First Make sure these resources are served with a correct "Content-Type", i.e, for JSON MIME type - "text/json", "application/json", HTML MIME type - "text/html".

Second: set mode to cors i.e, mode:cors

The fetch would look something like this

 fetch("https://example.com/api/request", {
            method: 'POST',
            body: JSON.stringify(data),
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                "Accept": 'application/json',
            }
        })
    .then((data) => data.json())
    .then((resp) => console.log(resp))
    .catch((err) => console.log(err))

references: https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md

https://www.chromium.org/Home/chromium-security/corb-for-developers

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

How to make node.js require absolute? (instead of relative)

What I like to do is leverage how node loads from the node_module directory for this.

If one tries to load the module "thing", one would do something like

require('thing');

Node will then look for the 'thing' directory in the 'node_module' directory.

Since the node_module is normally at the root of the project, we can leverage this consistency. (If node_module is not at the root, then you have other self induced headaches to deal with.)

If we go into the directory and then back out of it, we can get a consistent path to the root of the node project.

require('thing/../../');

Then if we want to access the /happy directory, we would do this.

require('thing/../../happy');

Though it is quite a bit hacky, however I feel if the functionality of how node_modules load changes, there will be bigger problems to deal with. This behavior should remain consistent.

To make things clear, I do this, because the name of module does not matter.

require('root/../../happy');

I used it recently for angular2. I want to load a service from the root.

import {MyService} from 'root/../../app/services/http/my.service';

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass annotation (optimize later).

Example of optimization using the @BeforeClass setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.

Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.

"Can't find Project or Library" for standard VBA functions

In my case, it was that the function was AMBIGUOUS as it was defined in the VBA library (present in my references), and also in the Microsoft Office Object Library (also present). I removed the Microsoft Office Object Library, and voila! No need to use the VBA. prefix.

Concatenating two std::vectors

I would use the insert function, something like:

vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

Why is "npm install" really slow?

One thing I noticed is, if you are working in new project(folder) you have to reconfigure proxy setting for the particular path

  1. Cd(change terminal window path to the destination folder.

  2. npm config set proxy http://(ip address):(port)

  3. npm config set https-proxy http://(ip address):(port)

  4. npm install -g @angular/cli

HttpClient won't import in Android Studio

Error:(30, 0) Gradle DSL method not found: 'classpath()' Possible causes:

  • The project 'cid' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0). Upgrade plugin to version 2.3.3 and sync project
  • The project 'cid' may be using a version of Gradle that does not contain the method. Open Gradle wrapper file
  • The build file may be missing a Gradle plugin. Apply Gradle plugin
  • How do I check if a number is a palindrome?

    A number is palindromic if its string representation is palindromic:

    def is_palindrome(s):
        return all(s[i] == s[-(i + 1)] for i in range(len(s)//2))
    
    def number_palindrome(n):
        return is_palindrome(str(n))
    

    javac: file not found: first.java Usage: javac <options> <source files>

    Java file execution procedure: After you saved a file MyFirstJavaProgram2.java

    Enter the whole Path of "Javac" followed by java file For executing output Path of followed by comment <-cp> followed by followed by

    Given below is the example of execution

    C:\Program Files\Java\jdk1.8.0_101\bin>javac C:\Sample\MyFirstJavaProgram2.java

    C:\Program Files\Java\jdk1.8.0_101\bin>java -cp C:\Sample MyFirstJavaProgram2

    Hello World

    How do I get HTTP Request body content in Laravel?

    For those who are still getting blank response with $request->getContent(), you can use:

    $request->all()

    e.g:

    public function foo(Request $request){
       $bodyContent = $request->all();
    }
    

    How to return result of a SELECT inside a function in PostgreSQL?

    Hi please check the below link

    https://www.postgresql.org/docs/current/xfunc-sql.html

    EX:

    CREATE FUNCTION sum_n_product_with_tab (x int)
    RETURNS TABLE(sum int, product int) AS $$
        SELECT $1 + tab.y, $1 * tab.y FROM tab;
    $$ LANGUAGE SQL;
    

    Windows task scheduler error 101 launch failure code 2147943785

    I have the same today on Win7.x64, this solve it.

    Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

    How to get the innerHTML of selectable jquery element?

    $(function() {
            $("#select-image").selectable({
                selected: function( event, ui ) { 
                    var $variable = $('.ui-selected').html(); 
                    console.log($variable);
                }
            });
        });
    

    or

    $(function() {
            $("#select-image").selectable({
                selected: function( event, ui ) { 
                    var $variable = $('.ui-selected').text(); 
                    console.log($variable);
                }
            });
        });
    

    or

    $(function() {
            $("#select-image").selectable({
                selected: function( event, ui ) { 
                    var $variable = $('.ui-selected').val(); 
                    console.log($variable);
                }
            });
        });
    

    Simple excel find and replace for formulas

    It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

    =((E9-E8)/E8) 
    

    became

    =((R[-1]C-R[-2]C)/R[-2]C)
    

    and

    (EXP((LN(E9/E8)/14.32))-1)
    

    became

    =(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)
    

    In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

    Show/hide widgets in Flutter programmatically

    For beginner try this too.

    class Visibility extends StatefulWidget {
      @override
      _VisibilityState createState() => _VisibilityState();
    }
    
    class _VisibilityState extends State<Visibility> {
      bool a = true;
      String mText = "Press to hide";
    
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: "Visibility",
          home: new Scaffold(
              body: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  new RaisedButton(
                    onPressed: _visibilitymethod, child: new Text(mText),),
                    a == true ? new Container(
                    width: 300.0,
                    height: 300.0,
                    color: Colors.red,
                  ) : new Container(),
                ],
              )
          ),
        );
      }
    
      void _visibilitymethod() {
        setState(() {
          if (a) {
            a = false;
            mText = "Press to show";
          } else {
            a = true;
            mText = "Press to hide";
          }
        });
      }
    }
    

    lodash: mapping array to object

    Another way with lodash

    creating pairs, and then either construct a object or ES6 Map easily

    _(params).map(v=>[v.name, v.input]).fromPairs().value()

    or

    _.fromPairs(params.map(v=>[v.name, v.input]))

    Here is a working example

    _x000D_
    _x000D_
    var params = [_x000D_
        { name: 'foo', input: 'bar' },_x000D_
        { name: 'baz', input: 'zle' }_x000D_
    ];_x000D_
    _x000D_
    var obj = _(params).map(v=>[v.name, v.input]).fromPairs().value();_x000D_
    _x000D_
    console.log(obj);
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
    _x000D_
    _x000D_
    _x000D_

    FAIL - Application at context path /Hello could not be started

    You need to close the XML with </web-app>, not with <web-app>.

    jQuery count child elements

    pure js

    selected.children[0].children.length;
    

    _x000D_
    _x000D_
    let num = selected.children[0].children.length;_x000D_
    _x000D_
    console.log(num);
    _x000D_
    <div id="selected">_x000D_
      <ul>_x000D_
        <li>29</li>_x000D_
        <li>16</li>_x000D_
        <li>5</li>_x000D_
        <li>8</li>_x000D_
        <li>10</li>_x000D_
        <li>7</li>_x000D_
      </ul>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Why does the program give "illegal start of type" error?

    You have a misplaced closing brace before the return statement.

    Android: How to handle right to left swipe gestures

    I know its a bit late since 2012 but I hope it will help someone since I think it's a shorter and cleaner code than most of the answers:

    view.setOnTouchListener((v, event) -> {
            
    int action = MotionEventCompat.getActionMasked(event);
    
    switch(action) {
        case (MotionEvent.ACTION_DOWN) :
            Log.d(DEBUG_TAG,"Action was DOWN");
            return true;
    
        case (MotionEvent.ACTION_MOVE) :
            Log.d(DEBUG_TAG,"Action was MOVE");
            return true;
    
        case (MotionEvent.ACTION_UP) :
            Log.d(DEBUG_TAG,"Action was UP");
            return true;
    
        case (MotionEvent.ACTION_CANCEL) :
            Log.d(DEBUG_TAG,"Action was CANCEL");
            return true;
    
        case (MotionEvent.ACTION_OUTSIDE) :
            Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
                    "of current screen element");
            return true;
    
        default :
            return super.onTouchEvent(event);
    }
        });
    

    of course you can leave only the relevant gestures to you.

    src: https://developer.android.com/training/gestures/detector

    Can't install Scipy through pip

    For windows(7 in my case):

    1. download scipy-0.19.1-cp36-cp36m-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
    2. create one some.bat file with content

      @echo off C:\Python36\python.exe -m pip -V C:\Python36\python.exe -m pip install scipy-0.19.1-cp36-cp36m-win32.whl C:\Python36\python.exe -m pip list pause

    3. then run this batch file some.bat

    4. call python shell "C:\Python36\pythonw.exe "C:\Python36\Lib\idlelib\idle.pyw" and test if scipy was installed with

    import scipy

    How to put two divs side by side

    http://jsfiddle.net/kkobold/qMQL5/

    _x000D_
    _x000D_
    #header {_x000D_
        width: 100%;_x000D_
        background-color: red;_x000D_
        height: 30px;_x000D_
    }_x000D_
    _x000D_
    #container {_x000D_
        width: 300px;_x000D_
        background-color: #ffcc33;_x000D_
        margin: auto;_x000D_
    }_x000D_
    #first {_x000D_
        width: 100px;_x000D_
        float: left;_x000D_
        height: 300px;_x000D_
            background-color: blue;_x000D_
    }_x000D_
    #second {_x000D_
        width: 200px;_x000D_
        float: left;_x000D_
        height: 300px;_x000D_
        background-color: green;_x000D_
    }_x000D_
    #clear {_x000D_
        clear: both;_x000D_
    }
    _x000D_
    <div id="header"></div>_x000D_
    <div id="container">_x000D_
        <div id="first"></div>_x000D_
        <div id="second"></div>_x000D_
        <div id="clear"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    C# Create New T()

    Take a look at new Constraint

    public class MyClass<T> where T : new()
    {
        protected T GetObject()
        {
            return new T();
        }
    }
    

    T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

    You can apply the same constraint to a generic method:

    public static T GetObject<T>() where T : new()
    {
        return new T();
    }
    

    If you need to pass parameters:

    protected T GetObject(params object[] args)
    {
        return (T)Activator.CreateInstance(typeof(T), args);
    }
    

    What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

    I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

        1 with open("/tmp/train.p", mode='rb') as training_data:
    ----> 2     train = pickle.load(training_data)
    UnpicklingError: invalid load key, '<'.
    

    I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

    Combining multiple condition in single case statement in Sql Server

    You can put the condition after the WHEN clause, like so:

    SELECT
      CASE
        WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
        WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
        WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
        WHEN DS.DES = 'N' THEN 'Early Term'
        WHEN DS.DES = 'Y' THEN 'Complete'
      END
    FROM
      ....
    

    Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

    Create parameterized VIEW in SQL Server 2008

    Try creating an inline table-valued function. Example:

    CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
    RETURNS TABLE
    AS
    RETURN
    (
        SELECT Field1, Field2
        FROM SomeTable
        WHERE Field3 = @Parameter1
    )
    
    -- Then call like this, just as if it's a table/view just with a parameter
    SELECT * FROM dbo.fxnExample(1)
    

    If you view the execution plan for the SELECT you will not see a mention of the function at all and will actually just show you the underlying tables being queried. This is good as it means statistics on the underlying tables will be used when generating an execution plan for the query.

    The thing to avoid would be a multi-statement table valued function as underlying table statistics will not be used and can result in poor performance due to a poor execution plan.
    Example of what to avoid:

    CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
        RETURNS @Results TABLE(Field1 VARCHAR(10), Field2 VARCHAR(10))
    AS
    BEGIN
        INSERT @Results
        SELECT Field1, Field2
        FROM SomeTable
        WHERE Field3 = @Parameter1
    
        RETURN
    END
    

    Subtly different, but with potentially big differences in performance when the function is used in a query.

    Vector of structs initialization

    Create vector, push_back element, then modify it as so:

    struct subject {
        string name;
        int marks;
        int credits;
    };
    
    
    int main() {
        vector<subject> sub;
    
        //Push back new subject created with default constructor.
        sub.push_back(subject());
    
        //Vector now has 1 element @ index 0, so modify it.
        sub[0].name = "english";
    
        //Add a new element if you want another:
        sub.push_back(subject());
    
        //Modify its name and marks.
        sub[1].name = "math";
        sub[1].marks = 90;
    }
    

    You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

    Using grep to help subset a data frame in R

    It's pretty straightforward using [ to extract:

    grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

    grep("^G45", My.Data$x)
    # [1] 2
    

    Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

    My.Data[grep("^G45", My.Data$x), ]
    #      x y
    # 2 G459 2
    

    The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

    subset(My.Data, grepl("^G45", My.Data$x))
    #      x y
    # 2 G459 2
    

    As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

    subset(My.Data, startsWith(as.character(x), "G45"))
    #      x y
    # 2 G459 2
    

    C Program to find day of week given date

    #include<stdio.h>
    static char day_tab[2][13] = {
            {0,31,28,31,30,31,30,31,31,30,31,30,31},
            {0,31,29,31,30,31,30,31,31,30,31,30,31}
            };
    int main()
    {
         int year,month;
         scanf("%d%d%d",&year,&month,&day);
         printf("%d\n",day_of_year(year,month,day));
         return 0;
    }
    int day_of_year(int year ,int month,int day)
    {
            int i,leap;
            leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
            if(month < 1 || month >12)
            return -1;
            if (day <1 || day > day_tab[leap][month])
            return -1;
            for(i= 1;i<month ; i++)
            {
                    day += day_tab[leap][year];
            }
            return day;
    }
    

    Locating child nodes of WebElements in selenium

    For Finding All the ChildNodes you can use the below Snippet

    List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
    
            for (WebElement e  : childs)
            {
                System.out.println(e.getTagName());
            }
    

    Note that this will give all the Child Nodes at same level -> Like if you have structure like this :

    <Html> 
    <body> 
     <div> ---suppose this is current WebElement 
       <a>
       <a>
          <img>
              <a>
          <img>
       <a>
    

    It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));

    Hope That Helps !!

    MySQL Data - Best way to implement paging?

    Query 1: SELECT * FROM yourtable WHERE id > 0 ORDER BY id LIMIT 500

    Query 2: SELECT * FROM tbl LIMIT 0,500;

    Query 1 run faster with small or medium records, if number of records equal 5,000 or higher, the result are similar.

    Result for 500 records:

    Query1 take 9.9999904632568 milliseconds

    Query2 take 19.999980926514 milliseconds

    Result for 8,000 records:

    Query1 take 129.99987602234 milliseconds

    Query2 take 160.00008583069 milliseconds

    How to set scope property with ng-init?

    Try this Code

    var app = angular.module('myapp', []);
      app.controller('testController', function ($scope, $http) {
           $scope.init = function(){           
           alert($scope.testInput);
       };});
    

    _x000D_
    _x000D_
    <body ng-app="myapp">_x000D_
          <div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
          </div>_x000D_
    </body>
    _x000D_
    _x000D_
    _x000D_

    Clearing content of text file using php

    To add button you may use either jQuery libraries or simple Javascript script as shown below:

    HTML link or button:

    <a href="#" onClick="goclear()" id="button">click event</a>
    

    Javascript:

    <script type="text/javascript">
    var btn = document.getElementById('button');
    function goclear() { 
    alert("Handler called. Page will redirect to clear.php");
    document.location.href = "clear.php";
    };
    </script>
    

    Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:

    <?php
    //open file to write
    $fp = fopen("/tmp/file.txt", "r+");
    // clear content to 0 bits
    ftruncate($fp, 0);
    //close file
    fclose($fp);
    ?>
    

    Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )

    <?php
    header('Location: getbacktoindex.html');
    ?>
    

    I hope it's help.

    Can´t run .bat file under windows 10

    There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

    • Add a pause to the batch file so that you can see what is happening before it exits.
      1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
      2. Go to the very end of the file and add a new line by pressing "enter".
      3. type pause.
      4. Save the file.
      5. Run the file again using the same method you did before.

    - OR -

    • Run the batch file from a static command prompt so the window does not close.
      1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
      2. Select "Open Command Window Here".
      3. You will now see a new command prompt. Type in the name of the batch file and press enter.

    Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

    Program does not contain a static 'Main' method suitable for an entry point

    Maybe the "Output type" in properties->Application of the project must be a "Class Library" instead of console or windows application.

    Remove directory which is not empty

    As of 2019...

    As of Node.js 12.10.0, fs.rmdirSync supports a recursive options, so you can finally do:

    fs.rmdirSync(dir, { recursive: true });
    

    Where the recursive option deletes the entire directory recursively.

    Typescript: difference between String and string

    TypeScript: String vs string

    Argument of type 'String' is not assignable to parameter of type 'string'.

    'string' is a primitive, but 'String' is a wrapper object.

    Prefer using 'string' when possible.

    demo

    String Object

    // error
    class SVGStorageUtils {
      store: object;
      constructor(store: object) {
        this.store = store;
      }
      setData(key: String = ``, data: object) {
        sessionStorage.setItem(key, JSON.stringify(data));
      }
      getData(key: String = ``) {
        const obj = JSON.parse(sessionStorage.getItem(key));
      }
    }
    
    

    string primitive

    // ok
    class SVGStorageUtils {
      store: object;
      constructor(store: object) {
        this.store = store;
      }
      setData(key: string = ``, data: object) {
        sessionStorage.setItem(key, JSON.stringify(data));
      }
      getData(key: string = ``) {
        const obj = JSON.parse(sessionStorage.getItem(key));
      }
    }
    
    

    enter image description here

    jQuery: How to get to a particular child of a parent?

    If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

    Disable a Button

    Let's say in Swift 4 you have a button set up for a segue as an IBAction like this @IBAction func nextLevel(_ sender: UIButton) {} and you have other actions occurring within your app (i.e. a timer, gamePlay, etc.). Rather than disabling the segue button, you might want to give your user the option to use that segue while the other actions are still occurring and WITHOUT CRASHING THE APP. Here's how:

    var appMode = 0
    
    @IBAction func mySegue(_ sender: UIButton) {
    
        if appMode == 1 {  // avoid crash if button pressed during other app actions and/or conditions
            let conflictingAction = sender as UIButton
            conflictingAction.isEnabled = false
        }
    }
    

    Please note that you will likely have other conditions within if appMode == 0 and/or if appMode == 1 that will still occur and NOT conflict with the mySegue button. Thus, AVOIDING A CRASH.

    how to get yesterday's date in C#

    You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that

     string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
    

    OR

     string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
    

    BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

    I had the same problem, you have to load first the Moment.js file!

    _x000D_
    _x000D_
    <script src="path/moment.js"></script>_x000D_
    <script src="path/bootstrap-datetimepicker.js"></script>
    _x000D_
    _x000D_
    _x000D_

    How to use Apple's new San Francisco font on a webpage

    None of the current answers including the accepted one will use Apple's San Francisco font on systems that don't have it installed as the system font. Since the question isn't "how do I use the OS X system font on a webpage" the correct solution is to use web fonts:

    @font-face {
      font-family: "San Francisco";
      font-weight: 400;
      src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-regular-webfont.woff");
    }
    

    Source

    How to create cron job using PHP?

    This is the best explanation with code in PHP I have found so far:

    http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

    In short:

    Although the syntax of scheduling a new job may seem daunting at first glance, it's actually relatively simple to understand once you break it down. A cron job will always have five columns each of which represent a chronological 'operator' followed by the full path and command to execute:

    * * * * * home/path/to/command/the_command.sh

    Each of the chronological columns has a specific relevance to the schedule of the task. They are as follows:

    Minutes represents the minutes of a given hour, 0-59 respectively.
    Hours represents the hours of a given day, 0-23 respectively.
    Days represents the days of a given month, 1-31 respectively.
    Months represents the months of a given year, 1-12 respectively.
    Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.
    

    enter image description here

    So, for example, if one wanted to schedule a task for 12am on the first day of every month it would look something like this:

    0 0 1 * * home/path/to/command/the_command.sh

    If we wanted to schedule a task to run every Saturday at 8:30am we'd write it as follows:

    30 8 * * 6 home/path/to/command/the_command.sh

    There are also a number of operators which can be used to customize the schedule even further:

    Commas is used to create a comma separated list of values for any of the cron columns.
    Dashes is used to specify a range of values.
    Asterisksis used to specify 'all' or 'every' value
    

    Visit the link for the full article, it explains:

    1. What is the format of the cronjob if you want to enter/edit it manually.
    2. How to use PHP with SSH2 library to authenticate as the user, which crontab you are going to edit.
    3. Full PHP class with all necessary methods for authentication, editing and deleting crontab entries.

    How to stop/terminate a python script from running?

    Ctrl + Z should do it, if you're caught in the python shell. Keep in mind that instances of the script could continue running in background, so under linux you have to kill the corresponding process.

    How to convert List<string> to List<int>?

    Convert string value into integer list

    var myString = "010"; 
    int myInt;
    List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();
    

    Extract the first word of a string in a SQL Server query

    DECLARE @string NVARCHAR(50)
    
    SET @string = 'CUT STRING'
    
    SELECT LEFT(@string,(PATINDEX('% %',@string)))
    

    C#: Waiting for all threads to complete

    I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do

    if(!thread.Join(End-now))
        throw new NotFinishedInTime();
    

    scrollbars in JTextArea

                txtarea = new JTextArea(); 
        txtarea.setRows(25);
        txtarea.setColumns(25);
        txtarea.setWrapStyleWord(true);
        JScrollPane scroll = new JScrollPane (txtarea);
        panel2.add(scroll); //Object of Jpanel
    

    Above given lines automatically shows you both horizontal & vertical Scrollbars..

    Unfortunately Launcher3 has stopped working error in android studio?

    I didn't found any particular answer to this question but i deleted the emulator and create a new one and increase the Ram size of the new emulator.Then the emulator works fine.

    HQL Hibernate INNER JOIN

    You can do it without having to create a real Hibernate mapping. Try this:

    SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team
    

    convert string into array of integers

    An alternative to Tushar Gupta answer would be :

    '14 2'.split(' ').map(x=>+x);
    
    // [14, 2]`
    

    In code golf you save 1 character. Here the "+" is "unary plus" operator, works like parseInt.

    PowerShell equivalent to grep -f

    PS) new-alias grep findstr
    PS) C:\WINDOWS> ls | grep -I -N exe
    
    105:-a---        2006-11-02     13:34      49680 twunk_16.exe
    106:-a---        2006-11-02     13:34      31232 twunk_32.exe
    109:-a---        2006-09-18     23:43     256192 winhelp.exe
    110:-a---        2006-11-02     10:45       9216 winhlp32.exe
    
    PS) grep /?
    

    How can I calculate divide and modulo for integers in C#?

    There is also Math.DivRem

    quotient = Math.DivRem(dividend, divisor, out remainder);
    

    Can a Byte[] Array be written to a file in C#?

    Try BinaryReader:

    /// <summary>
    /// Convert the Binary AnyFile to Byte[] format
    /// </summary>
    /// <param name="image"></param>
    /// <returns></returns>
    public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
    {
        byte[] imageBytes = null;
        BinaryReader reader = new BinaryReader(image.InputStream);
        imageBytes = reader.ReadBytes((int)image.ContentLength);
        return imageBytes;
    }
    

    Run function in script from command line (Node JS)

    I do a IIFE, something like that:

    (() => init())();
    

    this code will be executed immediately and invoke the init function.

    Import Excel Data into PostgreSQL 9.3

    It is possible using ogr2ogr:

    C:\Program Files\PostgreSQL\12\bin\ogr2ogr.exe -f "PostgreSQL" PG:"host=someip user=someuser dbname=somedb password=somepw" C:/folder/excelfile.xlsx -nln newtablenameinpostgres -oo AUTODETECT_TYPE=YES
    

    (Not sure if ogr2ogr is included in postgres installation or if I got it with postgis extension.)

    how to store Image as blob in Sqlite & how to retrieve it?

    you may also want to encode and decode to/from base64

        function uncompress(str:String):ByteArray {
                import mx.utils.Base64Decoder;
                var dec:Base64Decoder = new Base64Decoder();
                dec.decode(str);
                var newByteArr:ByteArray=dec.toByteArray();        
                return newByteArr;
            }
    
    
        // Compress a ByteArray into a Base64 String.
        function compress(bytes:ByteArray):String { 
            import mx.utils.Base64Decoder; //Transform String in a ByteArray.
            import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
            var enc:Base64Encoder = new Base64Encoder();    
            enc.encodeBytes(bytes);
            return enc.drain().split("\n").join("");
        }
    

    Find Process Name by its Process ID

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET /a pid=1600
    FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
     SET "found=%%a"
     SET /a foundpid=!found:~26,8!
     IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
    )
    
    GOTO :EOF
    

    ...set PID to suit your circumstance.

    Java: How to stop thread?

    We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().

    public class Task1 implements Runnable {
        public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                           ................
                           ................
                           ................
                           ................
               }
        }
    }
    

    in main we will do like this:

    Thread t1 = new Thread(new Task1());
    t1.start();
    t1.interrupt();
    

    Why am I getting tree conflicts in Subversion?

    In my experience, SVN creates a tree conflict WHENEVER I delete a folder. There appears to be no reason.

    I'm the only one working on my code -> delete a directory -> commit -> conflict!

    I can't wait to switch to Git.

    I should clarify - I use Subclipse. That's probably the problem! Again, I can't wait to switch...

    How to get the public IP address of a user in C#

    I have an extension method:

    public static string GetIp(this HttpContextBase context)
    {
        if (context == null || context.Request == null)
            return string.Empty;
    
        return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 
               ?? context.Request.UserHostAddress;
    }
    

    Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".

    But bear in mind it is not necessary the actual IP though.

    Sources:

    IIS Server Variables

    Link

    MySQL Results as comma separated list

    Now only I came across this situation and found some more interesting features around GROUP_CONCAT. I hope these details will make you feel interesting.

    simple GROUP_CONCAT

    SELECT GROUP_CONCAT(TaskName) 
    FROM Tasks;
    

    Result:

    +------------------------------------------------------------------+
    | GROUP_CONCAT(TaskName)                                           |
    +------------------------------------------------------------------+
    | Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
    +------------------------------------------------------------------+
    

    GROUP_CONCAT with DISTINCT

    SELECT GROUP_CONCAT(TaskName) 
    FROM Tasks;
    

    Result:

    +------------------------------------------------------------------+
    | GROUP_CONCAT(TaskName)                                           |
    +------------------------------------------------------------------+
    | Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
    +------------------------------------------------------------------+
    

    GROUP_CONCAT with DISTINCT and ORDER BY

    SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) 
    FROM Tasks;
    

    Result:

    +--------------------------------------------------------+
    | GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
    +--------------------------------------------------------+
    | Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
    +--------------------------------------------------------+
    

    GROUP_CONCAT with DISTINCT and SEPARATOR

    SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') 
    FROM Tasks;
    

    Result:

    +----------------------------------------------------------------+
    | GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')                |
    +----------------------------------------------------------------+
    | Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
    +----------------------------------------------------------------+
    

    GROUP_CONCAT and Combining Columns

    SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') 
    FROM Tasks;
    

    Result:

    +------------------------------------------------------------------------------------+
    | GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')                                 |
    +------------------------------------------------------------------------------------+
    | 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
    +------------------------------------------------------------------------------------+
    

    GROUP_CONCAT and Grouped Results Assume that the following are the results before using GROUP_CONCAT

    +------------------------+--------------------------+
    | ArtistName             | AlbumName                |
    +------------------------+--------------------------+
    | Iron Maiden            | Powerslave               |
    | AC/DC                  | Powerage                 |
    | Jim Reeves             | Singing Down the Lane    |
    | Devin Townsend         | Ziltoid the Omniscient   |
    | Devin Townsend         | Casualties of Cool       |
    | Devin Townsend         | Epicloud                 |
    | Iron Maiden            | Somewhere in Time        |
    | Iron Maiden            | Piece of Mind            |
    | Iron Maiden            | Killers                  |
    | Iron Maiden            | No Prayer for the Dying  |
    | The Script             | No Sound Without Silence |
    | Buddy Rich             | Big Swing Face           |
    | Michael Learns to Rock | Blue Night               |
    | Michael Learns to Rock | Eternity                 |
    | Michael Learns to Rock | Scandinavia              |
    | Tom Jones              | Long Lost Suitcase       |
    | Tom Jones              | Praise and Blame         |
    | Tom Jones              | Along Came Jones         |
    | Allan Holdsworth       | All Night Wrong          |
    | Allan Holdsworth       | The Sixteen Men of Tain  |
    +------------------------+--------------------------+
    
    USE Music;
    SELECT ar.ArtistName,
        GROUP_CONCAT(al.AlbumName)
    FROM Artists ar
    INNER JOIN Albums al
    ON ar.ArtistId = al.ArtistId
    GROUP BY ArtistName;
    

    Result:

    +------------------------+----------------------------------------------------------------------------+
    | ArtistName             | GROUP_CONCAT(al.AlbumName)                                                 |
    +------------------------+----------------------------------------------------------------------------+
    | AC/DC                  | Powerage                                                                   |
    | Allan Holdsworth       | All Night Wrong,The Sixteen Men of Tain                                    |
    | Buddy Rich             | Big Swing Face                                                             |
    | Devin Townsend         | Epicloud,Ziltoid the Omniscient,Casualties of Cool                         |
    | Iron Maiden            | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
    | Jim Reeves             | Singing Down the Lane                                                      |
    | Michael Learns to Rock | Eternity,Scandinavia,Blue Night                                            |
    | The Script             | No Sound Without Silence                                                   |
    | Tom Jones              | Long Lost Suitcase,Praise and Blame,Along Came Jones                       |
    +------------------------+----------------------------------------------------------------------------+
    

    How to convert string to date to string in Swift iOS?

    First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

    Swift 3

    let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
    dateFormatter.locale = Locale.init(identifier: "en_GB")
    
    let dateObj = dateFormatter.date(from: dateString)
    
    dateFormatter.dateFormat = "MM-dd-yyyy"
    print("Dateobj: \(dateFormatter.string(from: dateObj!))")
    

    The printed result is: Dateobj: 10-22-2015

    test attribute in JSTL <c:if> tag

    All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

    <c:if test="true">Hello world!</c:if>
    

    The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

    How to simplify a null-safe compareTo() implementation?

    You could design your class to be immutable (Effective Java 2nd Ed. has a great section on this, Item 15: Minimize mutability) and make sure upon construction that no nulls are possible (and use the null object pattern if needed). Then you can skip all those checks and safely assume the values are not null.

    Adding a column after another column within SQL

    Assuming MySQL (EDIT: posted before the SQL variant was supplied):

    ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
    

    The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

    How to declare a constant map in Golang?

    As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

    The Initialization would look like this:

    var romanNumeralDict = struct {
        m map[int]string
    }{m: map[int]string {
        1000: "M",
        900: "CM",
        //YOUR VALUES HERE
    }}
    
    func main() {
        d := 1000
        fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
    }
    

    Does JSON syntax allow duplicate keys in an object?

    There are 2 documents specifying the JSON format:

    1. http://json.org/
    2. https://tools.ietf.org/html/rfc7159

    The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

    The 2nd document says:

    1. Objects

      An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

    So it is not forbidden to have a duplicate name, but it is discouraged.

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

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

    lblExample.ForeColor = DefaultForeColor;
    

    How to find indices of all occurrences of one string in another in JavaScript?

    Here is regex free version:

    function indexes(source, find) {
      if (!source) {
        return [];
      }
      // if find is empty string return all indexes.
      if (!find) {
        // or shorter arrow function:
        // return source.split('').map((_,i) => i);
        return source.split('').map(function(_, i) { return i; });
      }
      var result = [];
      for (i = 0; i < source.length; ++i) {
        // If you want to search case insensitive use 
        // if (source.substring(i, i + find.length).toLowerCase() == find) {
        if (source.substring(i, i + find.length) == find) {
          result.push(i);
        }
      }
      return result;
    }
    
    indexes("I learned to play the Ukulele in Lebanon.", "le")
    

    EDIT: and if you want to match strings like 'aaaa' and 'aa' to find [0, 2] use this version:

    function indexes(source, find) {
      if (!source) {
        return [];
      }
      if (!find) {
          return source.split('').map(function(_, i) { return i; });
      }
      var result = [];
      var i = 0;
      while(i < source.length) {
        if (source.substring(i, i + find.length) == find) {
          result.push(i);
          i += find.length;
        } else {
          i++;
        }
      }
      return result;
    }
    

    Python: can't assign to literal

    This is taken from the Python docs:

    Identifiers (also referred to as names) are described by the following lexical definitions:
    
    identifier ::=  (letter|"_") (letter | digit | "_")*
    
    letter     ::=  lowercase | uppercase
    
    lowercase  ::=  "a"..."z"
    
    uppercase  ::=  "A"..."Z"
    
    digit      ::=  "0"..."9"
    
    Identifiers are unlimited in length. Case is significant.
    

    That should explain how to name your variables.

    How to create a list of objects?

    I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

    a way:

    class myClass():
        myInstances = []
        def __init__(self, myStr01, myStr02):
            self.myStr01 = myStr01
            self.myStr02 = myStr02
            self.__class__.myInstances.append(self)
    
    myObj01 = myClass("Foo", "Bar")
    myObj02 = myClass("FooBar",  "Baz")
    
    for thisObj in myClass.myInstances:
        print(thisObj.myStr01)
        print(thisObj.myStr02)
    

    A hack way to get this done:

    import sys
    class myClass():
        def __init__(self, myStr01, myStr02):
            self.myStr01 = myStr01
            self.myStr02 = myStr02
    
    myObj01 = myClass("Foo", "Bar")
    myObj02 = myClass("FooBar",  "Baz")
    
    myInstances = []
    myLocals = str(locals()).split("'")
    thisStep = 0
    for thisLocalsLine in myLocals:
        thisStep += 1
        if "myClass object at" in thisLocalsLine:
            print(thisLocalsLine)
            print(myLocals[(thisStep - 2)])
            #myInstances.append(myLocals[(thisStep - 2)])
            print(myInstances)
            myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
    
    for thisObj in myInstances:
        print(thisObj.myStr01)
        print(thisObj.myStr02)
    

    Another more 'clever' hack:

    import sys
    class myClass():
        def __init__(self, myStr01, myStr02):
            self.myStr01 = myStr01
            self.myStr02 = myStr02
    
    myInstances = []
    myClasses = {
        "myObj01": ["Foo", "Bar"],
        "myObj02": ["FooBar",  "Baz"]
        }
    
    for thisClass in myClasses.keys():
        exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
        myInstances.append(getattr(sys.modules[__name__], thisClass))
    
    for thisObj in myInstances:
        print(thisObj.myStr01)
        print(thisObj.myStr02)
    

    How to check which version of Keras is installed?

    Python library authors put the version number in <module>.__version__. You can print it by running this on the command line:

    python -c 'import keras; print(keras.__version__)'
    

    If it's Windows terminal, enclose snippet with double-quotes like below

    python -c "import keras; print(keras.__version__)"
    

    How to specify an element after which to wrap in css flexbox?

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

    Here's an article with your full list of options: https://tobiasahlin.com/blog/flexbox-break-to-new-row/

    EDIT: This is really easy to do with Grid now: https://codepen.io/anon/pen/mGONxv?editors=1100

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

    I don't think you can break after a specific item. The best you can probably do is change the flex-basis at your breakpoints. So:

    ul {
      flex-flow: row wrap;
      display: flex;
    }
    
    li {
      flex-grow: 1;
      flex-shrink: 0;
      flex-basis: 50%;
    }
    
    @media (min-width: 40em;){
    li {
      flex-basis: 30%;
    }
    

    Here's a sample: http://cdpn.io/ndCzD

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

    EDIT: You CAN break after a specific element! Heydon Pickering unleashed some css wizardry in an A List Apart article: http://alistapart.com/article/quantity-queries-for-css

    EDIT 2: Please have a look at this answer: Line break in multi-line flexbox

    @luksak also provides a great answer

    Convert DataFrame column type from string to datetime, dd/mm/yyyy format

    If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

    df['date'] = df['date'].astype('datetime64[ns]')

    or use datetime64[D] if you want Day precision and not nanoseconds

    print(type(df_launath['date'].iloc[0]))

    yields

    <class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

    You can try it with other formats then '%Y-%m-%d' but at least this works.

    Is it possible to compile a program written in Python?

    If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.

    Python Web Crawlers and "getting" html source code

    Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

    I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

    import urllib2
    
    response = urllib2.urlopen("http://google.de")
    page_source = response.read()
    

    For parsing the code, have a look at BeautifulSoup.

    BTW: what exactly do you want to do:

    Just for background, I need to download a page and replace any img with ones I have

    Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

    Mockito: Trying to spy on method is calling the original method

    I've found yet another reason for spy to call the original method.

    Someone had the idea to mock a final class, and found about MockMaker:

    As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line: mock-maker-inline

    Source: https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods

    After I merged and brought that file to my machine, my tests failed.

    I just had to remove the line (or the file), and spy() worked.

    curl: (6) Could not resolve host: application

    I was getting this error too. I resolved it by installing: https://git-scm.com/

    and running the command from the Git Bash window.

    Init method in Spring Controller (annotation version)

    public class InitHelloWorld implements BeanPostProcessor {
    
       public Object postProcessBeforeInitialization(Object bean,
                 String beanName) throws BeansException {
           System.out.println("BeforeInitialization : " + beanName);
           return bean;  // you can return any other object as well
       }
    
       public Object postProcessAfterInitialization(Object bean,
                 String beanName) throws BeansException {
           System.out.println("AfterInitialization : " + beanName);
           return bean;  // you can return any other object as well
       }
    
    }
    

    Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

    You could use a new annotation to solve this:

    @XXXToXXX(targetEntity = XXXX.class, fetch = FetchType.LAZY)
    

    In fact, fetch's default value is FetchType.LAZY too.

    Convert String to System.IO.Stream

    System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
    

    Remove plot axis values

    you can also put labels inside plot:

    plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)
    

    you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.

    How to add spacing between UITableViewCell

    Check out my solution on GitHub with subclassing of UITableView and using runtime features of Objective-C.
    It basically uses Apple's private data structure UITableViewRowData that I got searching private runtime header of UITableView:

    https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UITableView.h,

    and here's desired private class that contains everything you need to layout your cells' spacings however you want without setting it in cells' classes:

    https://github.com/JaviSoto/iOS10-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UITableViewRowData.h

    How do I add an "Add to Favorites" button or link on my website?

    I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

    jQuery('.bookmarkMeLink').click(function() {
        if (window.sidebar && window.sidebar.addPanel) { 
            // Mozilla Firefox Bookmark
            window.sidebar.addPanel(document.title,window.location.href,'');
        }
        else if(window.sidebar && jQuery.browser.mozilla){
            //for other version of FF add rel="sidebar" to link like this:
            //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
            jQuery(this).attr('rel', 'sidebar');
        }
        else if(window.external && ('AddFavorite' in window.external)) { 
            // IE Favorite
            window.external.AddFavorite(location.href,document.title); 
        } else if(window.opera && window.print) { 
            // Opera Hotlist
            this.title=document.title;
            return true;
        } else { 
            // webkit - safari/chrome
            alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
    
        }
    });
    

    Change an image with onclick()

    How about this? It doesn't require so much coding.

    _x000D_
    _x000D_
    $(".plus").click(function(){
     $(this).toggleClass("minus")  ; 
    })
    _x000D_
    .plus{
        background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
        width:130px;
        height:130px;
        background-repeat:no-repeat;
    }
    
    .plus.minus{
        background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
        width:130px;
        height:130px;
        background-repeat:no-repeat;
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#"><div class="plus">CHANGE</div></a>
    _x000D_
    _x000D_
    _x000D_

    How to set a:link height/width with css?

    Thanks to RandomUs 1r for this observation:

    changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59

    I tried it myself for a top navigation menu bar, as follows:

    First style the "li" element as follows:

    display: inline-block;
    width: 7em;
    text-align: center;

    Then style the "a"> element as follows:

    width: 100%;

    Now the navigation links are all equal width with text centered in each link.

    How do I force files to open in the browser instead of downloading (PDF)?

    You can do this in the following way:

    <a href="path to PDF file">Open PDF</a>
    

    If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:

    <FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
        Order Allow,Deny
        Allow from all
    </FilesMatch>
    

    But now allow just certain necessary files.

    I have used this code and it worked perfectly.

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

    An other cause of this problem is corruption of maven repository jars so you can use the following command to solve the problem :

    mvn dependency:purge-local-repository
    

    jQuery/JavaScript to replace broken images

    In case someone like me, tries to attach the error event to a dynamic HTML img tag, I'd like to point out that, there is a catch:

    Apparently img error events don't bubble in most browsers, contrary to what the standard says.

    So, something like the following will not work:

    $(document).on('error', 'img', function () { ... })
    

    Hope this will be helpful to someone else. I wish I had seen this here in this thread. But, I didn't. So, I am adding it

    jQuery remove all list items from an unordered list

    $("ul").empty() works fine. Is there some other error?

    _x000D_
    _x000D_
    $('input').click(function() {_x000D_
      $('ul').empty()_x000D_
    });
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <ul>_x000D_
      <li>test</li>_x000D_
      <li>test</li>_x000D_
    </ul>_x000D_
    _x000D_
    <input type="button" value="click me" />
    _x000D_
    _x000D_
    _x000D_

    http://jsfiddle.net/infernalbadger/D5ss8/

    Reloading submodules in IPython

    http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

    To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

    from IPython import get_ipython
    ipython = get_ipython()
    
    ipython.magic("pylab")
    ipython.magic("load_ext autoreload")
    ipython.magic("autoreload 2")
    

    PHP: Inserting Values from the Form into MySQL

    <!DOCTYPE html>
    <?php
    $con = new mysqli("localhost","root","","form");
    
    ?>
    
    
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script type="text/javascript">
    $(document).ready(function(){
     //$("form").submit(function(e){
    
         $("#btn1").click(function(e){
         e.preventDefault();
        // alert('here');
            $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');
    
        });
        //}
    });
    </script>
    
    </head>
    
    <body>
    <h2><b>Register Form<b></h2>
    <form method="post" enctype="multipart/form-data">
    <table>
    <tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
    <div class="apnew"></div><button id="btn1">Add</button></td></tr>
    <tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>
    
    <tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
    <tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
    <tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
    <tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
    </table>
    <?php
    //echo '<pre>';print_r($_FILES);exit();
    if(isset($_POST['t1']))
    {
    $values = implode(", ", $_POST['e1']);
    $imgarryimp=array();
    foreach($_FILES["e5"]["tmp_name"] as $key=>$val){
    
    
    move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);
    
                         $fname = $_FILES['e5']['name'][$key];
                         $imgarryimp[]=$fname;
                         //echo $fname;
    
                         if(strlen($fname)>0)
                          {
                             $img = $fname;
                          }
                          $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
    
           if($con->query($d)==TRUE)
             {
             echo "Yoy Data Save Successfully!!!";
             }
    }
    exit;
    
    
    
    
    
                          // echo $values;exit;
                          //foreach($_POST['e1'] as $row) 
        //{ 
    
        $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
    
           if($con->query($d)==TRUE)
             {
             echo "Yoy Data Save Successfully!!!";
             }
        //}
        //exit;
    
    
    }
    ?>
    
    </form>
    
    <table>
    <?php 
    $t="select * from form";
    $y=$con->query($t);
    foreach ($y as $q);
    {
    ?>
    <tr>
    <td>Name:<?php echo $q['name'];?></td>
    <td>Address:<?php echo $q['address'];?></td>
    <td>Contact:<?php echo $q['contact'];?></td>
    <td>Gender:<?php echo $q['gender'];?></td>
    </tr>
    <?php }?>
    </table>
    
    </body>
    </html>
    

    printf \t option

    That's something controlled by your terminal, not by printf.

    printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

    How to convert the time from AM/PM to 24 hour format in PHP?

    We can use Carbon

     $time = '09:15 PM';
     $s=Carbon::parse($time);
     echo $military_time =$s->format('G:i');
    

    http://carbon.nesbot.com/docs/

    How to join two tables by multiple columns in SQL?

    You should only need to do a single join:

    SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
    FROM Evaluation e
    INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
    

    Get average color of image via Javascript

    I recently came across a jQuery plugin which does what I originally wanted https://github.com/briangonzalez/jquery.adaptive-backgrounds.js in regards to getting a dominiate color from an image.

    Getting the SQL from a Django QuerySet

    As an alternative to the other answers, django-devserver outputs SQL to the console.

    How can I keep my branch up to date with master with git?

    If your branch is local only and hasn't been pushed to the server, use

    git rebase master
    

    Otherwise, use

    git merge master
    

    Get most recent file in a directory on Linux

    ls -Frt | grep "[^/]$" | tail -n 1
    

    MySQL "NOT IN" query

    To use IN, you must have a set, use this syntax instead:

    SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)
    

    How to get MAC address of your machine using a C program?

    Using getifaddrs you can get MAC address from the family AF_PACKET.

    In order to display the MAC address to each interface, you can proceed like this:

    #include <stdio.h>
    #include <ifaddrs.h>
    #include <netpacket/packet.h>
    
    int main (int argc, const char * argv[])
    {
        struct ifaddrs *ifaddr=NULL;
        struct ifaddrs *ifa = NULL;
        int i = 0;
    
        if (getifaddrs(&ifaddr) == -1)
        {
             perror("getifaddrs");
        }
        else
        {
             for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
             {
                 if ( (ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_PACKET) )
                 {
                      struct sockaddr_ll *s = (struct sockaddr_ll*)ifa->ifa_addr;
                      printf("%-8s ", ifa->ifa_name);
                      for (i=0; i <s->sll_halen; i++)
                      {
                          printf("%02x%c", (s->sll_addr[i]), (i+1!=s->sll_halen)?':':'\n');
                      }
                 }
             }
             freeifaddrs(ifaddr);
        }
        return 0;
    }
    

    Ideone

    Sass - Converting Hex to RGBa for background opacity

    There is a builtin mixin: transparentize($color, $amount);

    background-color: transparentize(#F05353, .3);
    

    The amount should be between 0 to 1;

    Official Sass Documentation (Module: Sass::Script::Functions)