Programs & Examples On #Restsharp

RestSharp is a simple to use REST client library for .NET

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

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);

RestSharp JSON Parameter Posting

Hope this will help someone. It worked for me -

RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
    Host = "host_environment",
    Username = "UserID",
    Password = "Password"
};
request.AddJsonBody(body);

var response = client.Execute(request).Content;

How to POST request using RestSharp

it is better to use json after post your resuest like below

  var clien = new RestClient("https://smple.com/");
  var request = new RestRequest("index", Method.POST);
  request.AddHeader("Sign", signinstance);    
  request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
  var response = client.Execute<YourReturnclassSample>(request);
  if (response.StatusCode == System.Net.HttpStatusCode.Created)
   {
       return Ok(response.Content);
   }

How do I get an OAuth 2.0 authentication token in C#

The Rest Client answer is perfect! (I upvoted it)

But, just in case you want to go "raw"

..........

I got this to work with HttpClient.

/*
.nuget\packages\newtonsoft.json\12.0.1
.nuget\packages\system.net.http\4.3.4
*/

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;


    private static async Task<Token> GetElibilityToken(HttpClient client)
    {
        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

        HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
        return tok;
    }


internal class Token
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}       

Here is another working example (based off the answer above)......with a few more tweaks. Sometimes the token-service is finicky:

    private static async Task<Token> GetATokenToTestMyRestApiUsingHttpClient(HttpClient client)
    {
        /* this code has lots of commented out stuff with different permutations of tweaking the request  */

        /* this is a version of asking for token using HttpClient.  aka, an alternate to using default libraries instead of RestClient */

        OAuthValues oav = GetOAuthValues(); /* object has has simple string properties for TokenUrl, GrantType, ClientId and ClientSecret */

        var form = new Dictionary<string, string>
                {
                    { "grant_type", oav.GrantType },
                    { "client_id", oav.ClientId },
                    { "client_secret", oav.ClientSecret }
                };

        /* now tweak the http client */
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Add("cache-control", "no-cache");

        /* try 1 */
        ////client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded");

        /* try 2 */
        ////client.DefaultRequestHeaders            .Accept            .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

        /* try 3 */
        ////does not compile */client.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        ////application/x-www-form-urlencoded

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, oav.TokenUrl);
        /////req.RequestUri = new Uri(baseAddress);

        req.Content = new FormUrlEncodedContent(form);

        ////string jsonPayload = "{\"grant_type\":\"" + oav.GrantType + "\",\"client_id\":\"" + oav.ClientId + "\",\"client_secret\":\"" + oav.ClientSecret + "\"}";
        ////req.Content = new StringContent(jsonPayload,                                                Encoding.UTF8,                                                "application/json");//CONTENT-TYPE header

        req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        /* now make the request */
        ////HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        HttpResponseMessage tokenResponse = await client.SendAsync(req);
        Console.WriteLine(string.Format("HttpResponseMessage.ReasonPhrase='{0}'", tokenResponse.ReasonPhrase));

        if (!tokenResponse.IsSuccessStatusCode)
        {
            throw new HttpRequestException("Call to get Token with HttpClient failed.");
        }

        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);

        return tok;
    }

APPEND

Bonus Material!

If you ever get a

"The remote certificate is invalid according to the validation procedure."

exception......you can wire in a handler to see what is going on (and massage if necessary)

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Net;

namespace MyNamespace
{
    public class MyTokenRetrieverWithExtraStuff
    {
        public static async Task<Token> GetElibilityToken()
        {
            using (HttpClientHandler httpClientHandler = new HttpClientHandler())
            {
                httpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    return await GetElibilityToken(client);
                }
            }
        }

        private static async Task<Token> GetElibilityToken(HttpClient client)
        {
            // throws certificate error if your cert is wired to localhost // 
            //string baseAddress = @"https://127.0.0.1/someapp/oauth2/token";

            //string baseAddress = @"https://localhost/someapp/oauth2/token";

        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

            HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
            var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
            Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
            return tok;
        }

        private static bool CertificateValidationCallBack(
        object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }


            /* overcome localhost and 127.0.0.1 issue */
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                if (certificate.Subject.Contains("localhost"))
                {
                    HttpRequestMessage castSender = sender as HttpRequestMessage;
                    if (null != castSender)
                    {
                        if (castSender.RequestUri.Host.Contains("127.0.0.1"))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;

        }


        public class Token
        {
            [JsonProperty("access_token")]
            public string AccessToken { get; set; }

            [JsonProperty("token_type")]
            public string TokenType { get; set; }

            [JsonProperty("expires_in")]
            public int ExpiresIn { get; set; }

            [JsonProperty("refresh_token")]
            public string RefreshToken { get; set; }
        }

    }
}

........................

I recently found (Jan/2020) an article about all this. I'll add a link here....sometimes having 2 different people show/explain it helps someone trying to learn it.

http://luisquintanilla.me/2017/12/25/client-credentials-authentication-csharp/

php - push array into array - key issue

I think you have to go for

$arrayname[indexname] = $value;

Reset CSS display property to default value

Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.

According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29

I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row

This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.

Integer.toString(int i) vs String.valueOf(int i)

One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.

Multiple simultaneous downloads using Wget?

wget cant download in multiple connections, instead you can try to user other program like aria2.

Register 32 bit COM DLL to 64 bit Windows 7

Below link saved the day

https://msdn.microsoft.com/en-us/library/ms229076(VS.80).aspx

use the relevant RegSvcs as specified in the above link

c:\Windows\Microsoft. NET\Framework\v4.0.30319\RegSvcs.exe ....\Shared\Your.dll /tlb:Your.tlb

ngOnInit not being called when Injectable class is Instantiated

Note: this answer applies only to Angular components and directives, NOT services.

I had this same issue when ngOnInit (and other lifecycle hooks) were not firing for my components, and most searches led me here.

The issue is that I was using the arrow function syntax (=>) like this:

class MyComponent implements OnInit {
    // Bad: do not use arrow function
    public ngOnInit = () => {
        console.log("ngOnInit");
    }
}

Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:

class MyComponent implements OnInit {
    public ngOnInit() {
        console.log("ngOnInit");
    }
}

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

For UNIX, try this. It worked for me:

  1. connect MySQL use Navicat Premium with inital root/"password"
  2. UPDATE mysql.user SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N' WHERE User = 'root' AND Host = 'localhost'; FLUSH PRIVILEGES;
  3. restart MySQL

Run PostgreSQL queries from the command line

  1. Open a command prompt and go to the directory where Postgres installed. In my case my Postgres path is "D:\TOOLS\Postgresql-9.4.1-3".After that move to the bin directory of Postgres.So command prompt shows as "D:\TOOLS\Postgresql-9.4.1-3\bin>"
  2. Now my goal is to select "UserName" from the users table using "UserId" value.So the database query is "Select u."UserName" from users u Where u."UserId"=1".

The same query is written as below for psql command prompt of postgres.

D:\TOOLS\Postgresql-9.4.1-3\bin>psql -U postgres -d DatabaseName -h localhost - t -c "Select u.\"UserName\" from users u Where u.\"UserId\"=1;

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

For me the issue was because of Case sensitivity. I was using ~{fragments/Base} instead of ~{fragments/base} (The name of the file was base.html)

My development environment was windows but the server hosting the application was Linux so I was not seeing this issue during development since windows' paths are not case sensitive.

passing several arguments to FUN of lapply (and others *apply)

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}

x is a vector or a list and myfun in lapply(x, myfun) is called for each element of x separately.

Option 1

If you'd like to use whole arg1 in each myfun call (myfun(x[1], arg1), myfun(x[2], arg1) etc.), use lapply(x, myfun, arg1) (as stated above).

Option 2

If you'd however like to call myfun to each element of arg1 separately alongside elements of x (myfun(x[1], arg1[1]), myfun(x[2], arg1[2]) etc.), it's not possible to use lapply. Instead, use mapply(myfun, x, arg1) (as stated above) or apply:

 apply(cbind(x,arg1), 1, myfun)

or

 apply(rbind(x,arg1), 2, myfun).

Preferred method to store PHP arrays (json_encode vs serialize)

I made a small benchmark as well. My results were the same. But I need the decode performance. Where I noticed, like a few people above said as well, unserialize is faster than json_decode. unserialize takes roughly 60-70% of the json_decode time. So the conclusion is fairly simple: When you need performance in encoding, use json_encode, when you need performance when decoding, use unserialize. Because you can not merge the two functions you have to make a choise where you need more performance.

My benchmark in pseudo:

  • Define array $arr with a few random keys and values
  • for x < 100; x++; serialize and json_encode a array_rand of $arr
  • for y < 1000; y++; json_decode the json encoded string - calc time
  • for y < 1000; y++; unserialize the serialized string - calc time
  • echo the result which was faster

On avarage: unserialize won 96 times over 4 times the json_decode. With an avarage of roughly 1.5ms over 2.5ms.

How to get the system uptime in Windows?

Following are eight ways to find the Uptime in Windows OS.

1: By using the Task Manager

In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.

  1. Right-click on the Taskbar, and click Task Manager. You can also click CTRL+SHIFT+ESC to get to the Task Manager.
  2. In Task Manager, select the Performance tab.
  3. The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.

    "Up Time" field in Task Manager

2: By using the System Information Utility

The systeminfo command line utility checks and displays various system statistics such as installation date, installed hotfixes and more. Open a Command Prompt and type the following command:

systeminfo

You can also narrow down the results to just the line you need:

systeminfo | find "System Boot Time:"

enter image description here

3: By using the Uptime Utility

Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.

Read the following KB for more info and for the download links:

To use it, follow these steps:

  1. Download uptime.exe from the above link, and save it to a folder, preferably in one that's in the system's path (such as SYSTEM32).
  2. Open an elevated Command Prompt window. To open an elevated Command Prompt, click Start, click All Programs, click Accessories, right-click Command Prompt, and then click Run as administrator. You can also type CMD in the search box of the Start menu, and when you see the Command Prompt icon click on it to select it, hold CTRL+SHIFT and press ENTER.
  3. Navigate to where you've placed the uptime.exe utility.
  4. Run the uptime.exe utility. You can add a /? to the command in order to get more options. enter image description here

It does not offer many command line parameters:

C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
    -V   display version

C:\uptimefromcodeplex\> uptime -V
version 1.1.0

3.1: By using the old Uptime Utility

There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)

Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)

C:\uptimev100download>uptime.exe /?

UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
        server          Name or IP address of remote server to process.
        /s              Display key system events and statistics.
        /a              Display application failure events (assumes /s).
        /d:             Only calculate for events after mm/dd/yyyy.
        /p:             Only calculate for events in the previous n days.
        /heartbeat      Turn on/off the system's heartbeat
        /?              Basic usage.
        /help           Additional usage information.

4: By using the NET STATISTICS Utility

Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:

net statistics workstation

The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.

enter image description here

5: By Using the Event Viewer

Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.

Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.

Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.

  1. Click on Event Viewer (Local) in the left navigation pane.
  2. In the middle pane, click on the Information event type, and scroll down till you see Event ID 6005. Double-click the 6005 Event ID, or right-click it and select View All Instances of This Event.
  3. A list of all instances of the 6005 Event ID will be displayed. You can examine this list, look at the dates and times of each reboot event, and so on.
  4. Open Server Manager tool by right-clicking the Computer icon on the start menu (or on the Desktop if you have it enabled) and select Manage. Navigate to the Event Viewer.

enter image description here

5.1: Eventlog via PowerShell

Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}

6: Programmatically, by using GetTickCount64

GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.

7: By using WMI

wmic os get lastbootuptime

8: The new uptime.exe for Windows XP and up

Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h command-line parameter).

Additionally, this version of uptime.exe will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:

enter image description here

and when executed as uptime -h:

enter image description here

MySQL - How to select data by string length

The function that I use to find the length of the string is length, used as follows:

SELECT * FROM table ORDER BY length(column);

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

illegal character in path

The string is surrounded by double quotes. Yes, that's not a valid character in a path.

You should probably tackle it at the source, but you can strip them out with:

        path = path.Replace("\"", "");

Facebook Android Generate Key Hash

use this in kotlin for print key hash in log

try {
        val info = context.getPackageManager().getPackageInfo(context.packageName,
                PackageManager.GET_SIGNATURES);
        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            Log.d("Key hash ", android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT))
        }
    }catch (e:Exception){

    }

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

ASP.NET Identity DbContext confusion

I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

How to change the floating label color of TextInputLayout

Programmatically you can use:

/* Here you get int representation of an HTML color resources */
int yourColorWhenEnabled = ContextCompat.getColor(getContext(), R.color.your_color_enabled);
int yourColorWhenDisabled = ContextCompat.getColor(getContext(), R.color.your_color_disabled);

/* Here you get matrix of states, I suppose it is a matrix because using a matrix you can set the same color (you have an array of colors) for different states in the same array */
int[][] states = new int[][]{new int[]{android.R.attr.state_enabled}, new int[]{-android.R.attr.state_enabled}};

/* You pass a ColorStateList instance to "setDefaultHintTextColor" method, remember that you have a matrix for the states of the view and an array for the colors. So the color in position "colors[0x0]" will be used for every states inside the array in the same position inside the matrix "states", so in the array "states[0x0]". So you have "colors[pos] -> states[pos]", or "colors[pos] -> color used for every states inside the array of view states -> states[pos] */
myTextInputLayout.setDefaultHintTextColor(new ColorStateList(states, new int[]{yourColorWhenEnabled, yourColorWhenDisabled})

Explanation:

Get int color value from a color resource (a way to present rgb colors used by android). I wrote ColorEnabled, but really it should be, for this answer, ColorHintExpanded & ColorViewCollapsed. Anyway this is the color you will see when the hint of a view "TextInputLayout" is on Expanded or Collapsed state; you will set it by using next array on function "setDefaultHintTextColor" of the view. Reference: Reference for TextInputLayout - search in this page the method "setDefaultHintTextColor" for more info

Looking to docs above you can see that the functions set the colors for Expanded & Collapsed hint by using a ColorStateList.

ColorStateList docs

To create the ColorStateList I first created a matrix with the states I want, in my case state_enabled & state_disabled (whose are, in TextInputLayout, equals to Hint Expanded and Hint Collapsed [I don't remember in which order lol, anyway I found it just doing a test]). Then I pass to the constructor of the ColorStateList the arrays with int values of color resources, these colors have a correspondences with the states matrix (every element in colors array correspond to the respective array in states matrix at same position). So the first element of the colors array will be used as color for every state in the first array of the states matrix (in our case the array has only 1 element: enabled state = hint expanded state for TextInputLayut). Last things states have positive / negative values, and you have only the positive values, so the state "disabled" in android attrs is "-android.state.enabled", the state "not focused" is "-android.state.focused" ecc.. ecc..

Hope this is helpful. Bye have a nice coding (:

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Remote debugging Tomcat with Eclipse

For apache-tomcat-8.5.28

modify JDPA_OPTS like the below then run like catalina.bat jpda start

JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=8000,server=y,suspend=$JPDA_SUSPEND"

Total Number of Row Resultset getRow Method

BalusC's answer is right! but I have to mention according to the user instance variable such as:

rSet.last(); 
total = rSet.getRow();

and then which you are missing

rSet.beforeFirst();

the remaining code is same you will get your desire result.

Saving and Reading Bitmaps/Images from Internal memory in Android

if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

viewModelScope.launch(Dispatchers.IO) {
            getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
            }
        }

getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

viewModelScope.launch(Dispatchers.IO) {
            val savedBitmap = BitmapFactory.decodeStream(
                getApplication<App>().openFileInput(filename).readBytes().inputStream()
            )
        }

tsc is not recognized as internal or external command

One more scenario of this error:

Install typescript locally and run the command without npm run

First, it is important to notice this is a "general" terminal error (Even if you write hello bla.js -or- wowowowow index.js):

enter image description here

"hello world" example of this error:

  1. You install typescript locally (without -g) ==> npm install typescript. https://docs.npmjs.com/downloading-and-installing-packages-locally
  2. In this case tsc commands available if you run npm run inside your local project. For example: npm run tsc -v:

enter image description here

-or- install typescript globally (Like other answer mention).

SQL Server : check if variable is Empty or NULL for WHERE clause

WHERE p.[Type] = isnull(@SearchType, p.[Type])

How to get memory available or used in C#

For the complete system you can add the Microsoft.VisualBasic Framework as a reference;

 Console.WriteLine("You have {0} bytes of RAM",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Command /usr/bin/codesign failed with exit code 1

Steps to Fix this issue:

  1. Go to Key Chain Access.
    1. Select the i-Phone Developer certificate.
    2. Lock the Certificate.( Menu bar - Lock Button)
    3. Give the Machine Password.
    4. Unlock the Certificate.

Now clean and rebuild the project, this issue will resolve.

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

log4net hierarchy and logging levels

As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.

However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:

<filter type="log4net.Filter.LevelMatchFilter">
  <levelToMatch value="WARN"/>
</filter>

Or to exclude a specific logging level by adding a "deny" node to the filter.

You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.

Reference Doc: log4net.Filter.LevelMatchFilter

If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

The code you have posted doesn't include a call to mysql_fetch_array(). However, what is most likely going wrong is that you are issuing a query that returns an error message, in which case the return value from the query function is false, and attempting to call mysql_fetch_array() on it doesn't work (because boolean false is not a mysql result object).

SQL recursive query on self referencing table (Oracle)

Do you want to do this?

SELECT id, parent_id, name, 
 (select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id

Edit Another option based on OMG's one (but I think that will perform equally):

select 
           t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
from 
    (select id, parent_id, name
    from tbl
    start with id = 1 
    connect by prior id = parent_id) t1
    left join
    tbl t2 on t2.id = t1.parent_id

Remove large .pack file created by git

The issue is that, even though you removed the files, they are still present in previous revisions. That's the whole point of git, is that even if you delete something, you can still get it back by accessing the history.

What you are looking to do is called rewriting history, and it involved the git filter-branch command.

GitHub has a good explanation of the issue on their site. https://help.github.com/articles/remove-sensitive-data

To answer your question more directly, what you basically need to run is this command with unwanted_filename_or_folder replaced accordingly:

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch unwanted_filename_or_folder' --prune-empty

This will remove all references to the files from the active history of the repo.

Next step, to perform a GC cycle to force all references to the file to be expired and purged from the packfile. Nothing needs to be replaced in these commands.

git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
# or, for older git versions (e.g. 1.8.3.1) which don't support --stdin
# git update-ref $(git for-each-ref --format='delete %(refname)' refs/original)
git reflog expire --expire=now --all
git gc --aggressive --prune=now

Maximum number of threads per process in Linux?

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

Set UITableView content inset permanently

This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):

Select Table View > Size Inspector > Content Insets: Never

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

You can wrap all tasks which can fail in block, and use ignore_errors: yes with that block.

tasks:
  - name: ls
    command: ls -la
  - name: pwd
    command: pwd

  - block:
    - name: ls non-existing txt file
      command: ls -la no_file.txt
    - name: ls non-existing pic
      command: ls -la no_pic.jpg
    ignore_errors: yes 

Read more about error handling in blocks here.

Proxy with urllib2

proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

LEFT JOIN only first row

I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.

You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...

LEFT JOIN Person ON Person.id = (
    SELECT SUBSTRING_INDEX(
        GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
    ) FROM Person
);

Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.

This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.

It is, however, useful in running data-intensive reports for admin.

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

Converting string to Date and DateTime

If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.

$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
  $timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600

How to redirect output of an entire shell script within the script itself?

Addressing the question as updated.

#...part of script without redirection...

{
    #...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...

#...residue of script without redirection...

The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)

You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.

The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.

Cassandra port usage - how are the ports used?

For Apache Cassandra 2.0 you need to take into account the following TCP ports: (See EC2 security group configuration and Apache Cassandra FAQ)

Cassandra

  • 7199 JMX monitoring port
  • 1024 - 65355 Random port required by JMX. Starting with Java 7u4 a specific port can be specified using the com.sun.management.jmxremote.rmi.port property.
  • 7000 Inter-node cluster
  • 7001 SSL inter-node cluster
  • 9042 CQL Native Transport Port
  • 9160 Thrift

DataStax OpsCenter

  • 61620 opscenterd daemon
  • 61621 Agent
  • 8888 Website

Architecture

A possible architecture with Cassandra + OpsCenter on EC2 could look like this: AWS EC2 with OpsCenter

Prevent scroll-bar from adding-up to the Width of page on Chrome

All you need to do is add:

html {
    overflow-y: scroll;
}

In your css file as this will have the scroller whether it is needed or not though you just won't be able to scroll

This means that the viewport will have the same width for both

C++ convert string to hexadecimal and vice versa

I think there is a much simpler and more elegant solution. Some of the above-mentioned methods may even throw unhandled exceptions in some cases. Here is a fool-proof (as in never goes wrong) and very fast code. Just try it and compare the results in terms of speed and compactness:

#include <string>

// Convert string of chars to its representative string of hex numbers
void stream2hex(const std::string str, std::string& hexstr, bool capital = false)
{
    hexstr.resize(str.size() * 2);
    const size_t a = capital ? 'A' - 1 : 'a' - 1;

    for (size_t i = 0, c = str[0] & 0xFF; i < hexstr.size(); c = str[i / 2] & 0xFF)
    {
        hexstr[i++] = c > 0x9F ? (c / 16 - 9) | a : c / 16 | '0';
        hexstr[i++] = (c & 0xF) > 9 ? (c % 16 - 9) | a : c % 16 | '0';
    }
}

// Convert string of hex numbers to its equivalent char-stream
void hex2stream(const std::string hexstr, std::string& str)
{
    str.resize((hexstr.size() + 1) / 2);

    for (size_t i = 0, j = 0; i < str.size(); i++, j++)
    {
        str[i] = (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) << 4, j++;
        str[i] |= (hexstr[j] & '@' ? hexstr[j] + 9 : hexstr[j]) & 0xF;
    }
}

Test the code:

#include <iostream>
int main()
{
    std::string s = "Hello World!";
    std::cout << "original string: " << s << '\n';
    stream2hex(s, s);
    std::cout << "hex format: " << s << '\n';
    hex2stream(s, s);
    std::cout << "original one: " << s << '\n';
}

and the result is:

original string: Hello World!
hex format: 48656C6C6F20576F726C6421
original one: Hello World!

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

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

    Public strHostName As String
    Public strIPAddress As String
    strHostName = System.Net.Dns.GetHostName()
    strIPAddress = System.Net.Dns.GetHostEntry(strHostName).AddressList(0).ToString()
    MessageBox.Show("Host Name: " & strHostName & "; IP Address: " & strIPAddress)

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

Is the NOLOCK (Sql Server hint) bad practice?

Prior to working on Stack Overflow, I was against NOLOCK on the principal that you could potentially perform a SELECT with NOLOCK and get back results with data that may be out of date or inconsistent. A factor to think about is how many records may be inserted/updated at the same time another process may be selecting data from the same table. If this happens a lot then there's a high probability of deadlocks unless you use a database mode such as READ COMMITED SNAPSHOT.

I have since changed my perspective on the use of NOLOCK after witnessing how it can improve SELECT performance as well as eliminate deadlocks on a massively loaded SQL Server. There are times that you may not care that your data isn't exactly 100% committed and you need results back quickly even though they may be out of date.

Ask yourself a question when thinking of using NOLOCK:

Does my query include a table that has a high number of INSERT/UPDATE commands and do I care if the data returned from a query may be missing these changes at a given moment?

If the answer is no, then use NOLOCK to improve performance.


I just performed a quick search for the NOLOCK keyword within the code base for Stack Overflow and found 138 instances, so we use it in quite a few places.

Does Google Chrome work with Selenium IDE (as Firefox does)?

There is not a Google Chrome extension comparable to Selenium IDE.

Scirocco is only a partial (and reportedly unreliable) implementation.

There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.

Sahi and TestComplete can also record, but neither are free, and are not browser plugins.

iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.

It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.

I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?

How to position a table at the center of div horizontally & vertically

Just add margin: 0 auto; to your table. No need of adding any property to div

_x000D_
_x000D_
<div style="background-color:lightgrey">_x000D_
 <table width="80%" style="margin: 0 auto; border:1px solid;text-align:center">_x000D_
    <tr>_x000D_
      <th>Name </th>_x000D_
      <th>Country</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>John</td>_x000D_
      <td>US </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Bob</td>_x000D_
      <td>India </td>_x000D_
    </tr>_x000D_
 </table>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Note: Added background color to div to visualize the alignment of table to its center

Localhost not working in chrome and firefox

You need to disable Script Debugging In Visual Studio

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Alternate table with new not null Column in existing table in SQL

The easiest way to do this is :

ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'

Ex : Adding a column x (bit datatype) to a table ABC with default value 0

ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0

PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer

How to use background thread in swift?

Swift 5

To make it easy, create a file "DispatchQueue+Extensions.swift" with this content :

import Foundation

typealias Dispatch = DispatchQueue

extension Dispatch {

    static func background(_ task: @escaping () -> ()) {
        Dispatch.global(qos: .background).async {
            task()
        }
    }

    static func main(_ task: @escaping () -> ()) {
        Dispatch.main.async {
            task()
        }
    }
}

Usage :

Dispatch.background {
    // do stuff

    Dispatch.main { 
        // update UI
    }
}

How to clear the logs properly for a Docker container?

On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:

docker logs -f --tail 100

This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...

(And thus, deleting the log is probably unnecessary)

How to search for a part of a word with ElasticSearch

you can use regexp.

{ "_id" : "1", "name" : "John Doeman" , "function" : "Janitor"}
{ "_id" : "2", "name" : "Jane Doewoman","function" : "Teacher"  }
{ "_id" : "3", "name" : "Jimmy Jackal" ,"function" : "Student"  } 

if you use this query :

{
  "query": {
    "regexp": {
      "name": "J.*"
    }
  }
}

you will given all of data that their name start with "J".Consider you want to receive just the first two record that their name end with "man" so you can use this query :

{
  "query": { 
    "regexp": {
      "name": ".*man"
    }
  }
}

and if you want to receive all record that in their name exist "m" , you can use this query :

{
  "query": { 
    "regexp": {
      "name": ".*m.*"
    }
  }
}

This works for me .And I hope my answer be suitable for solve your problem.

Is there a way to cache GitHub credentials for pushing commits?

OAuth

You can create your own personal API token (OAuth) and use it the same way as you would use your normal credentials (at: /settings/tokens). For example:

git remote add fork https://[email protected]/foo/bar
git push fork

.netrc

Another method is to configure your user/password in ~/.netrc (_netrc on Windows), e.g.

machine github.com
login USERNAME
password PASSWORD

For HTTPS, add the extra line:

protocol https

A credential helper

To cache your GitHub password in Git when using HTTPS, you can use a credential helper to tell Git to remember your GitHub username and password every time it talks to GitHub.

  • Mac: git config --global credential.helper osxkeychain (osxkeychain helper is required),
  • Windows: git config --global credential.helper wincred
  • Linux and other: git config --global credential.helper cache

Related:

Your content must have a ListView whose id attribute is 'android.R.id.list'

Inherit Activity Class instead of ListActivity you can resolve this problem.

public class ExampleActivity extends Activity  {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.mainlist);
    }
}

How to use paginator from material angular?

Component:

import { Component,  AfterViewInit, ViewChild } from @angular/core;
import { MatPaginator } from @angular/material;

export class ClassName implements AfterViewInit {
    @ViewChild(MatPaginator) paginator: MatPaginator;
    length = 1000;
    pageSize = 10;
    pageSizeOptions: number[] = [5, 10, 25, 100];

    ngAfterViewInit() {
        this.paginator.page.subscribe(
           (event) => console.log(event)
    );
}

HTML

<mat-paginator 
   [length]="length"
   [pageSize]="pageSize" 
   [pageSizeOptions]="pageSizeOptions"
   [showFirstLastButtons]="true">
</mat-paginator>

Using an attribute of the current class instance as a default value for method's parameter

Default value for parameters are evaluated at "compilation", once. So obviously you can't access self. The classic example is list as default parameter. If you add elements into it, the default value for the parameter changes!

The workaround is to use another default parameter, typically None, and then check and update the variable.

JUNIT testing void methods

If your method has no side effects, and doesn't return anything, then it's not doing anything.

If your method does some computation and returns the result of that computation, you can obviously enough assert that the result returned is correct.

If your code doesn't return anything but does have side effects, you can call the code and then assert that the correct side effects have happened. What the side effects are will determine how you do the checks.

In your example, you are calling static methods from your non-returning functions, which makes it tricky unless you can inspect that the result of all those static methods are correct. A better way - from a testing point of view - is to inject actual objects in that you call methods on. You can then use something like EasyMock or Mockito to create a Mock Object in your unit test, and inject the mock object into the class. The Mock Object then lets you assert that the correct functions were called, with the correct values and in the correct order.

For example:

private ErrorFile errorFile;

public void setErrorFile(ErrorFile errorFile) {
    this.errorFile = errorFile;
}

private void method1(arg1) {
    if (arg1.indexOf("$") == -1) {

        //Add an error message 
        errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
    }
}

Then in your test you can write:

public void testMethod1() {
    ErrorFile errorFile = EasyMock.createMock(ErrorFile.class);
    errorFile.addErrorMessage("There is a dollar sign in the specified parameter");
    EasyMock.expectLastCall(errorFile);
    EasyMock.replay(errorFile);

    ClassToTest classToTest = new ClassToTest();
    classToTest.setErrorFile(errorFile);
    classToTest.method1("a$b");

    EasyMock.verify(errorFile); // This will fail the test if the required addErrorMessage call didn't happen
}

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Java Ordered Map

LinkedHashMap maintains the order of the keys.

java.util.LinkedHashMap appears to work just like a normal HashMap otherwise.

Get the index of a certain value in an array in PHP

array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));

Application not picking up .css file (flask/python)

I'm running version 1.0.2 of flask right now. The above file structures did not work for me, but I found one that did, which are as follows:

     app_folder/ flask_app.py/ static/ style.css/ templates/
     index.html

(Please note that 'static' and 'templates' are folders, which should be named exactly the same thing.)

To check what version of flask you are running, you should open Python in terminal and type the following accordingly:

import flask

flask --version

How to trigger a click on a link using jQuery

Well you have to setup the click event first then you can trigger it and see what happens:

//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
  evt.preventDefault();
  alert($(this).attr('href'));
});

// now the manual trigger
$myLink.trigger('click');

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Socket.IO handling disconnect event

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

Server

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

Hope this will help you to think in another way

Can we make unsigned byte in Java

You can also:

public static int unsignedToBytes(byte a)
{
    return (int) ( ( a << 24) >>> 24);
}    

Explanation:

let's say a = (byte) 133;

In memory it's stored as: "1000 0101" (0x85 in hex)

So its representation translates unsigned=133, signed=-123 (as 2's complement)

a << 24

When left shift is performed 24 bits to the left, the result is now a 4 byte integer which is represented as:

"10000101 00000000 00000000 00000000" (or "0x85000000" in hex)

then we have

( a << 24) >>> 24

and it shifts again on the right 24 bits but fills with leading zeros. So it results to:

"00000000 00000000 00000000 10000101" (or "0x00000085" in hex)

and that is the unsigned representation which equals to 133.

If you tried to cast a = (int) a; then what would happen is it keeps the 2's complement representation of byte and stores it as int also as 2's complement:

(int) "10000101" ---> "11111111 11111111 11111111 10000101"

And that translates as: -123

Request is not available in this context

Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.

Here's what I'm using when not in Classic Mode. The overhead is negligible.

/// <summary>
/// Class is called only on the first request
/// </summary>
private class AppStart
{
    static bool _init = false;
    private static Object _lock = new Object();

    /// <summary>
    /// Does nothing after first request
    /// </summary>
    /// <param name="context"></param>
    public static void Start(HttpContext context)
    {
        if (_init)
        {
            return;
        }
        //create class level lock in case multiple sessions start simultaneously
        lock (_lock)
        {
            if (!_init)
            {
                string server = context.Request.ServerVariables["SERVER_NAME"];
                string port = context.Request.ServerVariables["SERVER_PORT"];
                HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
                _init = true;
            }
        }
    }
}

protected void Session_Start(object sender, EventArgs e)
{
    //initializes Cache on first request
    AppStart.Start(HttpContext.Current);
}

fatal: git-write-tree: error building trees

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

UICollectionView cell selection and cell reuse

What I did to solve this was to make the changes in the customized cell. You have a custom cell called DataSetCell in its class you could do the following (the code is in swift)

override var isSelected: Bool {
    didSet {
        if isSelected {
            changeStuff
        } else {
            changeOtherStuff
        }
    }
}

What this does is that every time the cell is selected, deselected, initialized or get called from the reusable queue, that code will run and the changes will be made. Hope this helps you.

Best way to do Version Control for MS Excel

I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:

  • Treat the workbook like any other application. Seperate logic, config and data.
  • Separate code from the workbook.
  • Build the UI programmatically.
  • Write a build script to reconstruct the workbook.

Convert unix time to readable date in pandas dataframe

If you try using:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))

and receive an error :

"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

This means the DATE_FIELD is not specified in seconds.

In my case, it was milli seconds - EPOCH time.

The conversion worked using below:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms')) 

Run JavaScript in Visual Studio Code

I would suggest you to use a simple and easy plugin called as Quokka which is very popular these days and helps you debug your code on the go. Quokka.js. One biggest advantage in using this plugin is that you save a lot of time to go on web browser and evaluate your code, with help of this you can see everything happening in VS code, which saves a lot of time.

How to convert comma separated string into numeric array in javascript

You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

var arr = [1,2,3],
    strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
    arr.push( + strings[i] );

Or, in one step, using Array map to convert them and applying them to one single push:

arr.push.apply(arr, strVale.split(",").map(Number));

Java: String - add character n-times

for(int i = 0; i < n; i++) {
    existing_string += 'c';
}

but you should use StringBuilder instead, and save memory

int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
    builder.append(" append ");
}

System.out.println(builder.toString());

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The solution (at least on OSX) is:

  1. Download the latest chromedriver file.
  2. Unzip the downloaded file.
  3. Search the location of the old chromedriver file on your computer and replace it with the new chromedriver file.
  4. Right-click the chromedriver file and click open. Do not double click as Mac will not open it the proper way.
  5. Once the file runs for the first time, you can close it and the update will have taken place.

How do I syntax check a Bash script without running it?

If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that

bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \;  2>&1 > /dev/null)
  if [ "$bashErrLines" != "" ]; then 
   # at least one sh file in the bin dir has a syntax error
   echo $bashErrLines; 
   exit; 
  fi

Change "sh" with "bash" depending on your needs

How to float a div over Google Maps?

Try this:

<style>
   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>

<div id="wrapper">
   <div id="google_map">

   </div>

   <div id="over_map">

   </div>
</div>

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

Your module and your class AthleteList have the same name. The line

import AthleteList

imports the module and creates a name AthleteList in your current scope that points to the module object. If you want to access the actual class, use

AthleteList.AthleteList

In particular, in the line

return(AthleteList(templ.pop(0), templ.pop(0), templ))

you are actually accessing the module object and not the class. Try

return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

A bracket - [ or ] - means that end of the range is inclusive -- it includes the element listed. A parenthesis - ( or ) - means that end is exclusive and doesn't contain the listed element. So for [first1, last1), the range starts with first1 (and includes it), but ends just before last1.

Assuming integers:

  • (0, 5) = 1, 2, 3, 4
  • (0, 5] = 1, 2, 3, 4, 5
  • [0, 5) = 0, 1, 2, 3, 4
  • [0, 5] = 0, 1, 2, 3, 4, 5

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

How to deal with SQL column names that look like SQL keywords?

If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.

select [select]
from [table]

How copy data from Excel to a table using Oracle SQL Developer

For PLSQL version 9.0.0.1601

  1. From the context menu of the Table, choose "Edit Data"
  2. Insert or edit the data
  3. Post change

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

How can I generate Javadoc comments in Eclipse?

Shift-Alt-J is a useful keyboard shortcut in Eclipse for creating Javadoc comment templates.

Invoking the shortcut on a class, method or field declaration will create a Javadoc template:

public int doAction(int i) {
    return i;
}

Pressing Shift-Alt-J on the method declaration gives:

/**
 * @param i
 * @return
 */
public int doAction(int i) {
    return i;
}

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

I cannot start SQL Server browser

My approach was similar to @SoftwareFactor, but different, perhaps because I'm running a different OS, Windows Server 2012. These steps worked for me.

Control Panel > System and Security > Administrative Tools > Services, right-click SQL Server Browser > Properties > General tab, change Startup type to Automatic, click Apply button, then click Start button in Service Status area.

Defining Z order of views of RelativeLayout in Android

I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:

childView1.bringToFront();

parentView.invalidate();

Working Copy Locked

To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:

I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).

So to resolve this:

Either

1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe

1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe

Then

2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.

From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.

How to add Headers on RESTful call using Jersey Client API

I use the header(name, value) method and give the return to webResource var:

Client client = Client.create();
WebResource webResource = client.resource("uri");

MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request

appKey = "Bearer " + appKey; // appKey is unique number

//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
    .header("Content-Type", "application/json;charset=UTF-8")
    .header("Authorization", appKey)
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);

Git command to display HEAD commit id?

According to https://git-scm.com/docs/git-log, for more pretty output in console you can use --decorate argument of git-log command:

git log --pretty=oneline --decorate

will print:

2a5ccd714972552064746e0fb9a7aed747e483c7 (HEAD -> master) New commit
fe00287269b07e2e44f25095748b86c5fc50a3ef (tag: v1.1-01) Commit 3
08ed8cceb27f4f5e5a168831d20a9d2fa5c91d8b (tag: v1.1, tag: v1.0-0.1) commit 1
116340f24354497af488fd63f4f5ad6286e176fc (tag: v1.0) second
52c1cdcb1988d638ec9e05a291e137912b56b3af test

How do I copy an entire directory of files into an existing directory using Python?

docs explicitly state that destination directory should not exist:

The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories.

I think your best bet is to os.walk the second and all consequent directories, copy2 directory and files and do additional copystat for directories. After all that's precisely what copytree does as explained in the docs. Or you could copy and copystat each directory/file and os.listdir instead of os.walk.

How do I generate a list with a specified increment step?

The following example shows benchmarks for a few alternatives.

library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
##                     test replications elapsed  relative user.self sys.self
## 2          (0:5e+05) * 2          100   0.587  3.536145     0.344    0.244
## 1     seq(0, 1e6, by = 2)         100   2.760 16.626506     1.832    0.900
## 3 seq.int(0, 1e6, by = 2)         100   0.166  1.000000     0.056    0.096

In this case, seq.int is the fastest method and seq the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq as the most readable solution.

SQL UPDATE all values in a field with appended string CONCAT not working

Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.

getting the ng-object selected with ng-change

You can also directly get selected value using following code

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

Matlab: Running an m-file from command-line

Here are the steps:

  1. Start the command line.
  2. Enter the folder containing the .m file with cd C:\M1\M2\M3
  3. Run the following: C:\E1\E2\E3\matlab.exe -r mfile

Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r option tries to start the given .m file as soon as startup occurs.

C# "No suitable method found to override." -- but there is one

I ran into a similar situation with code that WAS working , then was not.

Turned while dragging / dropping code within a file, I moved an object into another set of braces. Took longer to figure out than I care to admit.

Bit once I move the code back into its proper place, the error resolved.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How do you clone an Array of Objects in Javascript?

forget eval() (is the most misused feature of JS and makes the code slow) and slice(0) (works for simple data types only)

This is the best solution for me:

Object.prototype.clone = function() {
  var myObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i != 'clone') {
        if (this[i] && typeof this[i] == "object") {
          myObj[i] = this[i].clone();
        } else 
            myObj[i] = this[i];
        } 
    }
  return myObj;
};

Corrupt jar file

This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.

The problem occurs when you zip back the folder.

A valid Runnable/Executable JAR has the next structure:

myJAR (Main-Directory)
    |-META-INF (Mandatory)
             |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
    |-com 
         |-MainClass.class (must to implement the main method, mandatory)
    |-properties files (optional)
    |-etc (optional)

If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar

Once you're done try execute it on the command line using:

java -jar myJAR.jar 

When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:

**myJAR (Main-Directory)
    |-myJAR (creates another directory making the file corrupted)**
          |-META-INF (Mandatory)
                   |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
          |-com 
              |-MainClass.class (must to implement the main method, mandatory)
          |-properties files (optional)
          |-etc (optional)

:)

git ahead/behind info between master and branch?

After doing a git fetch, you can run git status to show how many commits the local branch is ahead or behind of the remote version of the branch.

This won't show you how many commits it is ahead or behind of a different branch though. Your options are the full diff, looking at github, or using a solution like Vimhsa linked above: Git status over all repo's

How can I access the MySQL command line with XAMPP for Windows?

To access the mysql command in Windows without manually changing directories, do this:

  • Go to Control Panel > System > Advanced system settings.
  • System Properties will appear.
  • Click on the 'Advanced' tab.
  • Click 'Environment Variables'.
  • Under System Variables, locate 'Path' and click Edit.
  • Append the path to your MySQL installation to the end of the exisiting 'Variable value'. Example:

    %systemDrive%\xampp\mysql\bin\ 

    or, if you prefer

    c:\xampp\mysql\bin\ 
  • Finally, open a new command prompt to make this change take effect.

Note that MySQL's documentation on Setting Environment Variables has little to say about handling this in Windows.

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

Command CompileSwift failed with a nonzero exit code in Xcode 10

in my case the problem was due to watchkit extension being set to swift 3 while the main project's target was set to swift 4.2

CSS3 equivalent to jQuery slideUp and slideDown?

why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery

Here is the code for sliding up and down

Here is the code for sliding left to right

Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

json_encode/json_decode - returns stdClass instead of Array in PHP

There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).

The concrete code is by Michal Migurski and by Matt Knapp:

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

Can a unit test project load the target application's app.config file?

The simplest way to do this is to add the .config file in the deployment section on your unit test.

To do so, open the .testrunconfig file from your Solution Items. In the Deployment section, add the output .config files from your project's build directory (presumably bin\Debug).

Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.

Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config to match the unit test's name.

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

How to change a string into uppercase

s = 'sdsd'
print (s.upper())
upper = raw_input('type in something lowercase.')
lower = raw_input('type in the same thing caps lock.')
print upper.upper()
print lower.lower()

How to concatenate text from multiple rows into a single text string in SQL server?

SELECT STUFF((SELECT ', ' + name FROM [table] FOR XML PATH('')), 1, 2, '')

Here's a sample:

DECLARE @t TABLE (name VARCHAR(10))
INSERT INTO @t VALUES ('Peter'), ('Paul'), ('Mary')
SELECT STUFF((SELECT ', ' + name FROM @t FOR XML PATH('')), 1, 2, '')
--Peter, Paul, Mary

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token

Handler.java (leave some overload method)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

MessageQueue.java do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

How to replace a string in an existing file in Perl?

Anything wrong with a one-liner?

$ perl -pi.bak -e 's/blue/red/g' *_classification.dat

Explanation

  • -p processes, then prints <> line by line
  • -i activates in-place editing. Files are backed up using the .bak extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line

Converting an int to a binary string representation in Java?

Using bit shift is a little quicker...

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

    while (N > 0 ) {
        binary.append( N % 2 );
        N >>= 1;
     }

    return binary.reverse().toString();

}

Batch file to run a command in cmd within a directory

This question is 5 years old. I wonder why still nobody has found the /d switch to set the working folder:

start /d "c:\activiti-5.9\setup" cmd /k ant demo.start

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Can I set text box to readonly when using Html.TextBoxFor?

To make it read only

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})

To diable

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

grep using a character vector with multiple patterns

Have you tried the match() or charmatch() functions?

Example use:

match(c("A1", "A9", "A6"), myfile$Letter)

How to save local data in a Swift app?

Okey so thanks to @bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

I've found that the answer is quite simple for some basic string storage.

let defaults = NSUserDefaults.standardUserDefaults()

// Store
defaults.setObject("theGreatestName", forKey: "username")

// Receive
if let name = defaults.stringForKey("username")
{
    print(name)
    // Will output "theGreatestName"
}

I've summarized it here http://ridewing.se/blog/save-local-data-in-swift/

Performing a Stress Test on Web Application?

At the risk of being accused of shameless self promotion I would like to point out that in my quest for a free load testing tool I went to this article: http://www.devcurry.com/2010/07/10-free-tools-to-loadstress-test-your.html

Either I couldn't get the throughput I wanted, or I couldn't get the flexibility I wanted. AND I wanted to easily aggregate the results of multiple load test generation hosts in post test analysis.

I tried out every tool on the list and to my frustration found that none of them quite did what I wanted to be able to do. So I built one and am sharing it.

Here it is: http://sourceforge.net/projects/loadmonger

PS: No snide comments on the name from folks who are familiar with urban slang. I wasn't but am slightly more worldly now.

Load JSON text into class object in c#

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques enter image description here

Regex: Check if string contains at least one digit

The regular expression you are looking for is simply this:

[0-9]

You do not mention what language you are using. If your regular expression evaluator forces REs to be anchored, you need this:

.*[0-9].*

Some RE engines (modern ones!) also allow you to write the first as \d (mnemonically: digit) and the second would then become .*\d.*.

Can we rely on String.isEmpty for checking null condition on a String in Java?

I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);

From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29

isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true
 StringUtils.isBlank(" ")       = true
 StringUtils.isBlank("bob")     = false
 StringUtils.isBlank("  bob  ") = false
 
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace

How can you strip non-ASCII characters from a string? (in C#)

I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is bzlm's solution. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for extended ASCII codes i.e. upto 255 which is the ISO 8859-1

It finds and strips out non-ascii characters(greater than 255)

Dim str1 as String= "â, ??î or ôu? n?i?++$-?!??4?od;/?'®;?:?)///1!@#"

Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1", 
                                                New EncoderReplacementFallback(String.empty),
                                                New DecoderReplacementFallback())

Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)

Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)

console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!??4od;/';:)///1!@#$%^yz:

Here's a working fiddle for the code

Replace the encoding as per the requirement, rest should remain the same.

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

how to check if item is selected from a comboBox in C#

I've found that using this null comparison works well:

if (Combobox.SelectedItem != null){
   //Do something
}
else{
  MessageBox.show("Please select a item");
}

This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

Can I stop 100% Width Text Boxes from extending beyond their containers?

Just came across this problem myself, and the only solution I could find that worked in all my test browsers (IE6, IE7, Firefox) was the following:

  1. Wrap the input field in two separate DIVs
  2. Set the outer DIV to width 100%, this prevents our container from overflowing the document
  3. Put padding in the inner DIV of the exact amount to compensate for the horizontal overflow of the input.
  4. Set custom padding on the input so it overflows by the same amount as I allowed for in the inner DIV

The code:

<div style="width: 100%">
    <div style="padding-right: 6px;">
        <input type="text" style="width: 100%; padding: 2px; margin: 0;
                                  border : solid 1px #999" />
    </div>
</div>

Here, the total horizontal overflow for the input element is 6px - 2x(padding + border) - so we set a padding-right for the inner DIV of 6px.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Migrating from VMWARE to VirtualBox

Note: I am not sure this will be of any help to you, but you never know.

I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html

ENJOY :-)

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

I had the same program, I hope this could help.

I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.

Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.

Now you can add your <...>.dll at the Project->Add Reference->Browse

Thanks

How to add option to select list in jQuery

For me this one worked

success: function(data){
            alert("SUCCCESS");
            $.each(data,function(index,itemData){
                console.log(JSON.stringify(itemData));
                $("#fromDay").append( new Option(itemData.lookupLabel,itemData.id) )
            });
        }

Is there a standard sign function (signum, sgn) in C/C++?

You can use boost::math::sign() method from boost/math/special_functions/sign.hpp if boost is available.

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Using the fileProvider is the way to go. But you can use this simple workaround:

WARNING: It will be fixed in next Android release - https://issuetracker.google.com/issues/37122890#comment4

replace:

startActivity(intent);

by

startActivity(Intent.createChooser(intent, "Your title"));

write() versus writelines() and concatenated strings

Exercise 16 from Zed Shaw's book? You can use escape characters as follows:

paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()

How to get the first day of the current week and month?

This week in milliseconds:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week:   " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

This month in milliseconds:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month:  " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

DOS: find a string, if found then run another script

C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"

Check if event exists on element

use jquery event filter

you can use it like this

$("a:Event(click)")

pop/remove items out of a python tuple

say you have a dict with tuples as keys, e.g: labels = {(1,2,0): 'label_1'} you can modify the elements of the tuple keys as follows:

formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}

Here, we ignore the last elements.

Finding the source code for built-in Python functions?

Let's go straight to your question.

Finding the source code for built-in Python functions?

The source code is located at Python/bltinmodule.c

To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>, for instance, sorted() is implemented in builtin_sorted.

For your pleasure I'll post the implementation of sorted():

builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
    PyObject *newlist, *v, *seq, *callable;

    /* Keyword arguments are passed through list.sort() which will check
       them. */
    if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
        return NULL;

    newlist = PySequence_List(seq);
    if (newlist == NULL)
        return NULL;

    callable = _PyObject_GetAttrId(newlist, &PyId_sort);
    if (callable == NULL) {
        Py_DECREF(newlist);
        return NULL;
    }

    assert(nargs >= 1);
    v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
    Py_DECREF(callable);
    if (v == NULL) {
        Py_DECREF(newlist);
        return NULL;
    }
    Py_DECREF(v);
    return newlist;
}

As you may have noticed, that's not Python code, but C code.

Restart container within pod

The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.

Since you have a deployment setup that uses replica set. You can delete the pod using kubectl delete pod test-1495806908-xn5jn and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.

How to pass model attributes from one Spring MVC controller to another controller?

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

How to handle a lost KeyStore password in Android?

Android brute force will not work if your both the passwords are different so the best option might be like that try to find the file named as

log.idea

in your C:/users/your named account then you might found that in there in android folder open that file lpg.idea in notepad and then search for

alias

using find option in notepad you will find it that the password and alias and alias passwors has been shown there

jquery find element by specific class when element has multiple classes

you are looking for http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture

How to create a fixed-size array of objects

Swift 4

You can somewhat think about it as array of object vs. array of references.

  • [SKSpriteNode] must contain actual objects
  • [SKSpriteNode?] can contain either references to objects, or nil

Examples

  1. Creating an array with 64 default SKSpriteNode:

    var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
                                               count: 64))
    
  2. Creating an array with 64 empty slots (a.k.a optionals):

    var optionalSprites = [SKSpriteNode?](repeatElement(nil,
                                          count: 64))
    
  3. Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?] into [SKSpriteNode]):

    let flatSprites = optionalSprites.flatMap { $0 }
    

    The count of the resulting flatSprites depends on the count of objects in optionalSprites: empty optionals will be ignored, i.e. skipped.

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

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

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

How to Create Multiple Where Clause Query Using Laravel Eloquent?

As per my suggestion if you are doing filter or searching

then you should go with :

        $results = User::query();
        $results->when($request->that, function ($q) use ($request) {
            $q->where('that', $request->that);
        });
        $results->when($request->this, function ($q) use ($request) {
            $q->where('this', $request->that);
        });
        $results->when($request->this_too, function ($q) use ($request) {
            $q->where('this_too', $request->that);
        });
        $results->get();

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

yet another solution which uses the fact that np.nan != np.nan:

In [149]: df.query("EPS == EPS")
Out[149]:
                 STK_ID  EPS  cash
STK_ID RPT_Date
600016 20111231  600016  4.3   NaN
601939 20111231  601939  2.5   NaN

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

Actually you can do it.

Although, someone should note that repeating the CASE statements are not bad as it seems. SQL Server's query optimizer is smart enough to not execute the CASE twice so that you won't get any performance hit because of that.

Additionally, someone might use the following logic to not repeat the CASE (if it suits you..)

INSERT INTO dbo.T1
(
    Col1,
    Col2,
    Col3
)
SELECT
    1,
    SUBSTRING(MyCase.MergedColumns, 0, CHARINDEX('%', MyCase.MergedColumns)),
    SUBSTRING(MyCase.MergedColumns, CHARINDEX('%', MyCase.MergedColumns) + 1, LEN(MyCase.MergedColumns) - CHARINDEX('%', MyCase.MergedColumns))
FROM
    dbo.T1 t
LEFT OUTER JOIN
(
    SELECT CASE WHEN 1 = 1 THEN '2%3' END MergedColumns
) AS MyCase ON 1 = 1

This will insert the values (1, 2, 3) for each record in the table T1. This uses a delimiter '%' to split the merged columns. You can write your own split function depending on your needs (e.g. for handling null records or using complex delimiter for varchar fields etc.). But the main logic is that you should join the CASE statement and select from the result set of the join with using a split logic.

How can I show a hidden div when a select option is selected?

Check this code. It awesome code for hide div using select item.

HTML

<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
    <option value="1">YES</option>
    <option value="2">NO</option>
</select>

<div id="div1" style="display:block;">
    <input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
    <input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
    <input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
    <input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
    <datalist id="cars">
        <option>Value 1</option>
        <option>Value 2</option>
        <option>Value 3</option>
        <option>Value 4</option>
    </datalist>
</div>

JS

<script>
    function showDiv(prefix,chooser) 
    {
            for(var i=0;i<chooser.options.length;i++) 
            {
                var div = document.getElementById(prefix+chooser.options[i].value);
                div.style.display = 'none';
            }

            var selectedOption = (chooser.options[chooser.selectedIndex].value);

            if(selectedOption == "1")
            {
                displayDiv(prefix,"1");
            }
            if(selectedOption == "2")
            {
                displayDiv(prefix,"2");
            }
    }

    function displayDiv(prefix,suffix) 
    {
            var div = document.getElementById(prefix+suffix);
            div.style.display = 'block';
    }
</script>

Duplicate symbols for architecture x86_64 under Xcode

I got the same error when I added a pod repository

pod 'SWRevealViewController'

for an already added source code (SWRevealViewController) from gitHub. So, the error will be fixed by either removing the source code or pod repository.

Case # 2:

The 2nd time, this error appeared when I declare a constant in .h file.

NSString * const SomeConstant  = @"SomeValue";
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
...
...

Parameter "stratify" from method "train_test_split" (scikit Learn)

Try running this code, it "just works":

from sklearn import cross_validation, datasets 

iris = datasets.load_iris()

X = iris.data[:,:2]
y = iris.target

x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)

y_test

array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
       1, 2, 1, 1, 0, 2, 1])

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

just add your .jar file in applet tag as an attribute as shown below:

<applet
    code="file.class"
    archive="file.jar"
    height=550 
    width=1100>         
</applet>

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

Initialize/reset struct to zero/null

 struct x myX;
 ...
 memset(&x, 0, sizeof(myX));

Get the value of a dropdown in jQuery

Another option:

$("#<%=dropDownId.ClientID%>").children("option:selected").val();

Not equal to != and !== in PHP

You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php

It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.

  1. create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,

    environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"

  2. add these to your Dockerfile,

    RUN apt-get clean && apt-get update && apt-get install -y locales

    RUN locale-gen en_CA.UTF-8

    COPY ./default_locale /etc/default/locale

    RUN chmod 0755 /etc/default/locale

    ENV LC_ALL=en_CA.UTF-8

    ENV LANG=en_CA.UTF-8

    ENV LANGUAGE=en_CA.UTF-8

This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.

Add padding on view programmatically

You can set padding to your view by pro grammatically throughout below code -

view.setPadding(0,1,20,3);

And, also there are different type of padding available -

Padding

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

These, links will refer Android Developers site. Hope this helps you lot.

Is it possible to disable scrolling on a ViewPager

I created a Kotlin version based on converting this answer from Java: https://stackoverflow.com/a/13437997/8023278

There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.

class SwipeLockableViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    private var swipeEnabled = false

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onTouchEvent(event)
            false -> false
        }
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return when (swipeEnabled) {
            true -> super.onInterceptTouchEvent(event)
            false -> false
        }
    }

    fun setSwipePagingEnabled(swipeEnabled: Boolean) {
        this.swipeEnabled = swipeEnabled
    }
}

Then in our layout xml we use our new SwipeLockableViewPager instead of the standard ViewPager

<mypackage.SwipeLockableViewPager 
        android:id="@+id/myViewPager" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" />

Now in our activity/fragment we can call myViewPager.setSwipePagingEnabled(false) and users won't be able to swipe between pages


UPDATE

As of 2020 we now have ViewPager2. If you migrate to ViewPager2 there is a built in method to disable swiping: myViewPager2.isUserInputEnabled = false

Elegant solution for line-breaks (PHP)

\n didn't work for me. the \n appear in the bodytext of the email I was sending.. this is how I resolved it.

str_pad($input, 990); //so that the spaces will pad out to the 990 cut off.

Traversing text in Insert mode

You seem to misuse vim, but that's likely due to not being very familiar with it.

The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.

Here's a couple of use-cases:

  • You accidentally typed "accifentally". No problem, the sequence EscFfrdA will correct the mistake and bring you back to where you were editing. The Ff movement will move your cursor backwards to the first encountered "f" character. Compare that with Ctrl+DeldEnd, which does virtually the same in a casual editor, but takes more keystrokes and makes you move your hand out of the alphanumeric area of the keyboard.
  • You accidentally typed "you accidentally typed", but want to correct it to "you intentionally typed". Then Esc2bcw will erase the word you want to fix and bring you to insert mode, so you can immediately retype it. To get back to editing, just press A instead of End, so you don't have to move your hand to reach the End key.
  • You accidentally typed "mouse" instead of "mice". No problem - the good old Ctrl+w will delete the previous word without leaving insert mode. And it happens to be much faster to erase a small word than to fix errors within it. I'm so used to it that I had closed the browser page when I was typing this message...!
  • Repetition count is largely underused. Before making a movement, you can type a number; and the movement will be repeated this number of times. For example, 15h will bring your cursor 15 characters back and 4j will move your cursor 4 lines down. Start using them and you'll get used to it soon. If you made a mistake ten characters back from your cursor, you'll find out that pressing the key 10 times is much slower than the iterative approach to moving the cursor. So you can instead quickly type the keys 12h (as a rough of guess how many characters back that you need to move your cursor), and immediately move forward twice with ll to quickly correct the error.

But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.

In where shall I use isset() and !empty()

In the most general way :

  • isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
  • empty tests if a variable (...) contains some non-empty data.


To answer question 1 :

$str = '';
var_dump(isset($str));

gives

boolean true

Because the variable $str exists.


And question 2 :

You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.

Now, to work on its value, when you know there is such a value : that is the job of empty.

Python: subplot within a loop: first panel appears in wrong position

The problem is the indexing subplot is using. Subplots are counted starting with 1! Your code thus needs to read

fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):

    #this part is just arranging the data for contourf 
    ind2 = py.find(zz==i+1)
    sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
    sfr_mass_sub = sfr_mass[ind2]
    zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')


    temp = 251+i  # this is to index the position of the subplot
    ax=plt.subplot(temp)
    ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
    plt.subplots_adjust(hspace = .5,wspace=.001)

    #just annotating where each contour plot is being placed
    ax.set_title(str(temp))

Note the change in the line where you calculate temp

What is the difference between a function expression vs declaration in JavaScript?

They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.

So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

Example: Function Expression

alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; } 

Example: Function Declaration

alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; } 


As for the second part of your question:

var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

Trying to check if username already exists in MySQL database using PHP

Try this:

$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")

Don't add $con to mysql_query() function.

Disclaimer: using the username variable in the string passed to mysql_query, as shown above, is a trivial SQL injection attack vector in so far the username depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.

How to filter files when using scp to copy dir recursively?

There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

rsync -av --exclude '*.svn' user@server:/my/dir .

(this line copy rsync from distant folder to current one)

Recent versions of rsync tunnel over an ssh connection automatically by default.

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

SVG drop shadow using css3

You can easily add a drop-shadow effect to an svg-element using the drop-shadow() CSS function and rgba color values. By using rgba color values you can change the opacity of your shadow.

_x000D_
_x000D_
img.light-shadow{_x000D_
  filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.4));_x000D_
}_x000D_
_x000D_
img.dark-shadow{_x000D_
  filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 1));_x000D_
}
_x000D_
<img class="light-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />_x000D_
<img class="dark-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />
_x000D_
_x000D_
_x000D_

.Net: How do I find the .NET version?

MSDN details it here very nicely on how to check it from registry:

To find .NET Framework versions by viewing the registry (.NET Framework 1-4)

  1. On the Start menu, choose Run.
  2. In the Open box, enter regedit.exe.You must have administrative credentials to run regedit.exe.
  3. In the Registry Editor, open the following subkey:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP

The installed versions are listed under the NDP subkey. The version number is stored in the Version entry. For the .NET Framework 4 the Version entry is under the Client or Full subkey (under NDP), or under both subkeys.

To find .NET Framework versions by viewing the registry (.NET Framework 4.5 and later)

  1. On the Start menu, choose Run.
  2. In the Open box, enter regedit.exe. You must have administrative credentials to run regedit.exe.
  3. In the Registry Editor, open the following subkey:

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

Note that the path to the Full subkey includes the subkey Net Framework rather than .NET Framework

Check for a DWORD value named Release. The existence of the Release DWORD indicates that the .NET Framework 4.5 or newer has been installed on that computer.

enter image description here

Note: The last row in the above snapshot which got clipped reads On all other OS versions: 461310. I tried my level best to avoid the information getting clipped while taking the screenshot but the table was way too big.

Sorting hashmap based on keys

Using the TreeMap you can sort the Map.

Map<String, String> map = new HashMap<String, String>();        
Map<String, String> treeMap = new TreeMap<String, String>(map);
//show hashmap after the sort
for (String str : treeMap.keySet()) {
    System.out.println(str);
}

fstream won't create a file

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

How to set background color of HTML element using css properties in JavaScript

You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.

Your CSS would obviously be something like:

.highlight {
    background:#ff00aa;
}

Then in JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

Controller not a function, got undefined, while defining controllers globally

I had this problem when I accidentally redeclared myApp:

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);

After the redeclare, Controller1 stops working and raises the OP error.

Best HTML5 markup for sidebar

The ASIDE has since been modified to include secondary content as well.

HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/

Excerpt:

With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I had the same problem. None of the solutions here worked. I had to completely reinstall eclipse and make a new workspace. Then it worked!

Linux command-line call not returning what it should from os.system?

using commands module
import commands
""" 
Get high load process details 
"""
result = commands.getoutput("ps aux | sort -nrk 3,3 | head -n 1")
print result  -- python 2x
print (result) -- python 3x 

CSS How to set div height 100% minus nPx

In CSS3 you could use

height: calc(100% - 60px);

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

I know there were lots of answers here, but the TL;DR version is this (If you're using Xamarin Studio):

  1. Right click the Android project in the solution tree
  2. Select Options
  3. Go to Android Build
  4. Go to Advanced tab
  5. Check the architectures you use in your emulator (Probably x86 / armeabi-v7a / armeabi)
  6. Make a kickass app :)

Stack, Static, and Heap in C++

A similar question was asked, but it didn't ask about statics.

Summary of what static, heap, and stack memory are:

  • A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.

  • The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.

  • Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).

When you would want to use each one:

  • Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)

  • Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.

  • Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.

Garbage Collection

I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.

Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see reference counting). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B points out that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)

Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine.

ES6 class variable alternatives

You can mimic es6 classes behaviour... and use your class variables :)

Look mum... no classes!

// Helper
const $constructor = Symbol();
const $extends = (parent, child) =>
  Object.assign(Object.create(parent), child);
const $new = (object, ...args) => {
  let instance = Object.create(object);
  instance[$constructor].call(instance, ...args);
  return instance;
}
const $super = (parent, context, ...args) => {
  parent[$constructor].call(context, ...args)
}
// class
var Foo = {
  classVariable: true,

  // constructor
  [$constructor](who){
    this.me = who;
    this.species = 'fufel';
  },

  // methods
  identify(){
    return 'I am ' + this.me;
  }
}

// class extends Foo
var Bar = $extends(Foo, {

  // constructor
  [$constructor](who){
    $super(Foo, this, who);
    this.subtype = 'barashek';
  },

  // methods
  speak(){
    console.log('Hello, ' + this.identify());
  },
  bark(num){
    console.log('Woof');
  }
});

var a1 = $new(Foo, 'a1');
var b1 = $new(Bar, 'b1');
console.log(a1, b1);
console.log('b1.classVariable', b1.classVariable);

I put it on GitHub

SQL - Rounding off to 2 decimal places

As an add-on to the answers below, when using INT or non-decimal datatypes in your formulas, remember to multiply the value by 1 and the number of decimals you prefer.

i.e. - TotalPackages is an INT and so the denominator TotalContainers, but I want my result to have up to 6 decimal places.

thus:

((m.TotalPackages * 1.000000) / m.TotalContainers) AS Packages,

Select data from date range between two dates

SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

What is the maximum length of a URL in different browsers?

ASP.NET 2 and SQL Server reporting services 2005 have a limit of 2028. I found this out the hard way, where my dynamic URL generator would not pass over some parameters to a report beyond that point. This was under Internet Explorer 8.