Programs & Examples On #Tombstoning

For Windows Phone applications, tombstoning is the process in which some data about the application state are saved upon app termination so that this state is re-created if the user navigates back to the tombstoned application (in order to simulate multitasking).

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

You can also search for the file. Navigate to your project directory with PowerShell and run Get-FileMissingRoot:

function Get-FileMissingRoot {

    dir -recurse |
        where {
            ($_ -is [IO.FileInfo]) -and 
            (@(".xml", ".config") -contains $_.extension) 
        } |
        foreach {
            $xml = New-Object Xml.XmlDocument;
            $filename = $_.FullName
            try {
                $xml.Load($filename)
            }
            catch {
                write ("File: " + $filename)
                write ($_.Exception.Message)
            }
        }
}

Using reCAPTCHA on localhost

  1. Register your website at – https://www.google.com/recaptcha/admin
  2. add js plugin 3.add class and your site-key provived by google enter image description here
<script src='https://www.google.com/recaptcha/api.js'></script>
 <div class="g-recaptcha" data-sitekey="your site-key"></div>

How do I parse JSON with Objective-C?

  1. I recommend and use TouchJSON for parsing JSON.
  2. To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
    NSDictionary *user;
    NSInteger i = 0;
    NSString *skey;
    if(userinfo != nil){
        for( i = 0; i < [userinfo count]; i++ ) {
            if(i)
                skey = [NSString stringWithFormat:@"%d",i];
            else
                skey = @"";
    
            user = [userinfo objectForKey:skey];
            NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
            NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
            NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
            NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
        }
    }
    

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

Sort an ArrayList based on an object field

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

When I had an error Access Error: 404 -- Not Found I fixed it by doing the following:

  1. Open command prompt and type "netstat -aon" (without the quotes)
  2. Search for port 8080 and look at its PID number/code.
  3. Open Task Manager (CTRL+ALT+DELETE), go to Services tab, and find the service with the exact PID number. Then right click it and stop the process.

Adding a JAR to an Eclipse Java library

As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start

You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

How to read a Parquet file into Pandas DataFrame?

Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

The code is simple, just type:

import pyarrow.parquet as pq

df = pq.read_table(source=your_file_path).to_pandas()

For more information, see the document from Apache pyarrow Reading and Writing Single Files

document.getElementById().value doesn't set the value

The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

How to cast Object to its actual type?

How about JsonConvert.DeserializeObject(object.ToString());

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

You just change the App_Start/WebApiConfig.cs like this:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        //Below formatter is used for returning the Json result.
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        //Default route
        config.Routes.MapHttpRoute(
           name: "ApiControllerOnly",
           routeTemplate: "api/{controller}"
       );
    }

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

Tar error: Unexpected EOF in archive

I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.

From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.

Adding days to $Date in PHP

Here has an easy way to solve this.

<?php
   $date = "2015-11-17";
   echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>

Output will be:

2015-11-22

Solution has found from here - How to Add Days to Date in PHP

Angular 2 Unit Tests: Cannot find name 'describe'

npm install @types/jasmine

As mentioned in some comments the "types": ["jasmine"] is not needed anymore, all @types packages are automatically included in compilation (since v2.1 I think).

In my opinion the easiest solution is to exclude the test files in your tsconfig.json like:

"exclude": [
    "node_modules",
    "**/*.spec.ts"
]

This works for me.

Further information in the official tsconfig docs.

How to draw an empty plot?

How about something like:

plot.new()

Can a PDF file's print dialog be opened with Javascript?

if you embed the pdf in your webpage and reference the object id, you should be able to do it.

eg. in your HTML:

<object ID="examplePDF" type="application/pdf" data="example.pdf" width="500" height="500">

in your javascript:

<script>

var pdf = document.getElementById("examplePDF");

pdf.print();

</script>

I hope that helps.

Java integer to byte array

byte[] IntToByteArray( int data ) {    
    byte[] result = new byte[4];
    result[0] = (byte) ((data & 0xFF000000) >> 24);
    result[1] = (byte) ((data & 0x00FF0000) >> 16);
    result[2] = (byte) ((data & 0x0000FF00) >> 8);
    result[3] = (byte) ((data & 0x000000FF) >> 0);
    return result;        
}

Submit form with Enter key without submit button?

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none; on a submit button in the form.

How do I pass JavaScript variables to PHP?

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

Process.start: how to get the output?

You can process your output synchronously or asynchronously.

1. Synchronous example

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

Note that it's better to process both output and errors: they must be handled separately.

(*) For some commands (here StartInfo.Arguments) you must add the /c directive, otherwise the process freezes in the WaitForExit().

2. Asynchronous example

static void runCommand() 
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

How do I convert from a string to an integer in Visual Basic?

Convert.ToIntXX doesn't like being passed strings of decimals.

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

Retrieving a random item from ArrayList

Here's a better way of doing things:

import java.util.ArrayList;
import java.util.Random;

public class facultyquotes
{
    private ArrayList<String> quotes;
    private String quote1;
    private String quote2;
    private String quote3;
    private String quote4;
    private String quote5;
    private String quote6;
    private String quote7;
    private String quote8;
    private String quote9;
    private String quote10;
    private String quote11;
    private String quote12;
    private String quote13;
    private String quote14;
    private String quote15;
    private String quote16;
    private String quote17;
    private String quote18;
    private String quote19;
    private String quote20;
    private String quote21;
    private String quote22;
    private String quote23;
    private String quote24;
    private String quote25;
    private String quote26;
    private String quote27;
    private String quote28;
    private String quote29;
    private String quote30;
    private int n;
    Random random;

    String teacher;


    facultyquotes()
    {
        quotes=new ArrayList<>();
        random=new Random();
        n=random.nextInt(3) + 0;
        quote1="life is hard";
        quote2="trouble shall come to an end";
        quote3="never give lose and never get lose";
        quote4="gamble with the devil and win";
        quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
        quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
        quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
        quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
        quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
        quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
        quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
        quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
        quote13="No one can make you feel inferior without your consent.";
        quote14="Let him who would enjoy a good future waste none of his present.";
        quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
        quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
        quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
        quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
        quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
        quote20="It is our choices, that show what we truly are, far more than our abilities.";
        quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
        quote22="The successful warrior is the average man, with laser-like focus.";
        quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
        quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
        quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
        quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
        quote27="Don’t let the fear of losing be greater than the excitement of winning.";
        quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
        quote29="There is nothing permanent except change.";
        quote30="You cannot shake hands with a clenched fist.";

        quotes.add(quote1);
        quotes.add(quote2);
        quotes.add(quote3);
        quotes.add(quote4);
        quotes.add(quote5);
        quotes.add(quote6);
        quotes.add(quote7);
        quotes.add(quote8);
        quotes.add(quote9);
        quotes.add(quote10);
        quotes.add(quote11);
        quotes.add(quote12);
        quotes.add(quote13);
        quotes.add(quote14);
        quotes.add(quote15);
        quotes.add(quote16);
        quotes.add(quote17);
        quotes.add(quote18);
        quotes.add(quote19);
        quotes.add(quote20);
        quotes.add(quote21);
        quotes.add(quote22);
        quotes.add(quote23);
        quotes.add(quote24);
        quotes.add(quote25);
        quotes.add(quote26);
        quotes.add(quote27);
        quotes.add(quote28);
        quotes.add(quote29);
        quotes.add(quote30);
    }

    public void setTeacherandQuote(String teacher)
    {
        this.teacher=teacher;
    }

    public void printRandomQuotes()
    {
        System.out.println(quotes.get(n++)+"  ~ "+ teacher);  
    }

    public void printAllQuotes()
    {
        for (String i : quotes)
        {
            System.out.println(i.toString());
        }
    }
}

TSQL: How to convert local time to UTC? (SQL Server 2008)

Here is the code to convert one zone DateTime to another zone DateTime

DECLARE @UTCDateTime DATETIME = GETUTCDATE();
DECLARE @ConvertedZoneDateTime DATETIME;

-- 'UTC' to 'India Standard Time' DATETIME
SET @ConvertedZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'
SELECT @UTCDateTime AS UTCDATE,@ConvertedZoneDateTime AS IndiaStandardTime

-- 'India Standard Time' to 'UTC' DATETIME
SET @UTCDateTime = @ConvertedZoneDateTime AT TIME ZONE 'India Standard Time' AT TIME ZONE 'UTC'
SELECT @ConvertedZoneDateTime AS IndiaStandardTime,@UTCDateTime AS UTCDATE

Note: AT TIME ZONE works only on SQL Server 2016+ and the advantage is that it automatically considers Daylight when converting to a particular Time zone

TypeError: 'str' does not support the buffer interface

>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s

Well if useful for you in case removing annoying 'b' character.If anyone got better idea please suggest me or feel free to edit me anytime in here.I'm just newbie

JavaScript alert box with timer

If you want an alert to appear after a certain about time, you can use this code:

setTimeout(function() { alert("my message"); }, time);

If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm or prompt is shown.

If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.

var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);

Authentication failed because remote party has closed the transport stream

using (var client = new HttpClient(handler))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
                await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }

This worked for me

How to set layout_weight attribute dynamically from code?

If layoutparams is already defined (in XML or dynamically), Here's a one liner:

((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;

Selenium using Python - Geckodriver executable needs to be in PATH

from webdriverdownloader import GeckoDriverDownloader # vs ChromeDriverDownloader vs OperaChromiumDriverDownloader
gdd = GeckoDriverDownloader()
gdd.download_and_install()
#gdd.download_and_install("v0.19.0")

This will get you the path to your gekodriver.exe on Windows.

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\\Users\\username\\\bin\\geckodriver.exe')
driver.get('https://www.amazon.com/')

FlutterError: Unable to load asset

Encountered the same issue with a slightly different code. In my case, I was using a "assets" folder subdivided into sub-folders for assets (sprites, audio, UI).

My code was simply at first in pubspec.yaml- alternative would be to detail every single file.

flutter:

  assets:
    - assets

Indentation and flutter clean was not enough to fix it. The files in the sub-folders were not loading by flutter. It seems like flutter needs to be "taken by the hand" and not looking at sub-folders without explicitly asking it to look at them. This worked for me:

flutter:

  assets:
    - assets/sprites/
    - assets/audio/
    - assets/UI/

So I had to detail each folder and each sub-folder that contains assets (mp3, jpg, etc). Doing so made the app work and saved me tons of time as the only solution detailed above would require me to manually list 30+ assets while the code here is just a few lines and easier to maintain.

How to quit android application programmatically

It depends on how fast you want to close your app.

A safe way to close your app is finishAffinity();

It closes you app after all processes finished processing. This may need some time. If you close your app this way, and restart it after a short time, it is possible that your new application runs in the same process. With all the not finished processes and singleton objects of the old application.

If you want to be sure, that your app is closed completly use System.exit(0);

This will close your app immediatly. But it is possible, that you damage files that your app has open or an edit on shared preferences does not finish. So use this carefully.

If you use watchdog in combination with a long running task, you can see the influences of the different methods.

new ANRWatchDog(2000).setANRListener(new ANRWatchDog.ANRListener() {
    public void onAppNotResponding(ANRError error) {
        MainActivity.this.finishAffinity();
        System.exit(0);
    }
}).start();
for(int i = 0; i < 10; ++i){
    --i;
}

This kills your app after 2 seconds without displaying an ANR dialog or something like that. If you remove System.exit(0), run this code and restart the app after it is closed, you will experience some strange behaviour, because the endless loop is still running.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

java -jar server-0.0.1-SNAPSHOT.jar --spring.config.location=application-prod.properties

Why is json_encode adding backslashes?

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

VBA (Excel) Initialize Entire Array without Looping

This function works with variables for size and initial value it combines tbur & Filipe responses.

Function ArrayIniValue(iSize As Integer, iValue As Integer)
Dim sIndex As String
sIndex = "INDEX(Row(1:" & iSize & "),)"
ArrayIniValue = Evaluate("=Transpose(" & sIndex & "-" & sIndex & "+" & iValue & ")")
End Function

Called this way:

myArray = ArrayIniValue(350, 13)

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Jackson has to know in what order to pass fields from a JSON object to the constructor. It is not possible to access parameter names in Java using reflection - that's why you have to repeat this information in annotations.

Closing WebSocket correctly (HTML5, Javascript)

According to the protocol spec v76 (which is the version that browser with current support implement):

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

Both answers given worked for the problem I stated -- Thanks!

In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.

Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

How to restart Jenkins manually?

If you installed as a rpm or deb, then service jenkins restart will work also.

How to clear gradle cache?

As @Bradford20000 pointed out in the comments, there might be a gradle.properties file as well as global gradle scripts located under $HOME/.gradle. In such case special attention must be paid when deleting the content of this directory.

The .gradle/caches directory holds the Gradle build cache. So if you have any error about build cache, you can delete it.

The --no-build-cache option will run gradle without the build cache.

How to join components of a path when you are constructing a URL in Python

Using furl, pip install furl it will be:

 furl.furl('/media/path/').add(path='js/foo.js')

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

How can I create an executable JAR with dependencies using Maven?

Add to pom.xml:

  <dependency>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
            <version>1.4.4</version>
  </dependency>

and

<plugin>
       <groupId>com.jolira</groupId>
       <artifactId>onejar-maven-plugin</artifactId>
       <version>1.4.4</version>
       <executions>
              <execution>
                     <goals>
                         <goal>one-jar</goal>
                     </goals>
              </execution>
       </executions>
</plugin>

Thats it. Next mvn package will also create one fat jar additionally, including all dependency jars.

How do I test which class an object is in Objective-C?

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

How to print the current Stack Trace in .NET without any exception?

An alternative to System.Diagnostics.StackTrace is to use System.Environment.StackTrace which returns a string-representation of the stacktrace.

Another useful option is to use the $CALLER and $CALLSTACK debugging variables in Visual Studio since this can be enabled run-time without rebuilding the application.

How to hide image broken Icon using only CSS/HTML?

The trick with img::after is a good stuff, but has at least 2 downsides:

  1. not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
  2. you cannot simply hide the image, you cover it - so not that helpful when you what to show a default image in the case

I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:

img:-moz-broken{
  opacity: 0;
}

PostgreSQL - max number of parameters in "IN" clause?

There is no limit to the number of elements that you are passing to IN clause. If there are more elements it will consider it as array and then for each scan in the database it will check if it is contained in the array or not. This approach is not so scalable. Instead of using IN clause try using INNER JOIN with temp table. Refer http://www.xaprb.com/blog/2006/06/28/why-large-in-clauses-are-problematic/ for more info. Using INNER JOIN scales well as query optimizer can make use of hash join and other optimization. Whereas with IN clause there is no way for the optimizer to optimize the query. I have noticed speedup of at least 2x with this change.

json_encode is returning NULL?

You should pass utf8 encoded string in json_encode. You can use utf8_encode and array_map() function like below:

<?php
    $encoded_rows = array_map('utf8_encode', $rows);
    echo json_encode($encoded_rows);
?>

Is it correct to use DIV inside FORM?

It is totally fine .

The form will submit only its input type controls ( *also Textarea , Select , etc...).

You have nothing to worry about a div within a form.

jQuery Change event on an <input> element - any way to retain previous value?

Every DOM element has an attribute called defaultValue. You can use that to get the default value if you just want to compare the first changing of data.

If my interface must return Task what is the best way to have a no-operation implementation?

If you are using generics, all answer will give us compile error. You can use return default(T);. Sample below to explain further.

public async Task<T> GetItemAsync<T>(string id)
            {
                try
                {
                    var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
                    return response.Resource;
                }
                catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {

                    return default(T);
                }

            }

How to get the cell value by column name not by index in GridView in asp.net

Header Row cells sometimes will not work. This will just return the column Index. It will help in a lot of different ways. I know this is not the answer he is requesting. But this will help for a lot people.

public static int GetColumnIndexByHeaderText(GridView gridView, string columnName)
    {      
        for (int i = 0; i < gridView.Columns.Count ; i++)
        {
            if (gridView.Columns[i].HeaderText.ToUpper() == columnName.ToUpper() )
            {
                return i;
            }
        }     
        return -1;
    }

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

Attach to a processes output for viewing

I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc path. So if you have a program running, whose ID is 1199, cd into it:

$ cd /proc/1199

Then look for the fd directory underneath

$ cd fd

This fd directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f the one you need - in this case, stdout):

$ tail -f 1

What are best practices for multi-language database design?

Martin's solution is very similar to mine, however how would you handle a default descriptions when the desired translation isn't found ?

Would that require an IFNULL() and another SELECT statement for each field ?

The default translation would be stored in the same table, where a flag like "isDefault" indicates wether that description is the default description in case none has been found for the current language.

Get all attributes of an element using jQuery

Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.

_x000D_
_x000D_
$("#myTestDiv").click(function(){_x000D_
  var attrs = document.getElementById("myTestDiv").attributes;_x000D_
  $.each(attrs,function(i,elem){_x000D_
    $("#attrs").html(    $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<div id="myTestDiv" ekind="div" etype="text" name="stack">_x000D_
click This_x000D_
</div>_x000D_
<div id="attrs">Attributes are <div>
_x000D_
_x000D_
_x000D_

including parameters in OPENQUERY

SELECT field1 FROM OPENQUERY 
                   ([NameOfLinkedSERVER], 
                   'SELECT field1 FROM TABLENAME') 
                           WHERE field1=@someParameter T1 
                                 INNER JOIN MYSQLSERVER.DATABASE.DBO.TABLENAME           
                                 T2 ON T1.PK = T2.PK

How to efficiently remove duplicates from an array without using Set

For a sorted Array, just check the next index:

//sorted data!
public static int[] distinct(int[] arr) {
    int[] temp = new int[arr.length];

    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        int current = arr[i];

        if(count > 0 )
            if(temp[count - 1] == current)
                continue;

        temp[count] = current;
        count++;
    }

    int[] whitelist = new int[count];
    System.arraycopy(temp, 0, whitelist, 0, count);

    return whitelist;
}

In C#, what is the difference between public, private, protected, and having no access modifier?

Public - If you can see the class, then you can see the method

Private - If you are part of the class, then you can see the method, otherwise not.

Protected - Same as Private, plus all descendants can also see the method.

Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.

Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.

Never ignore the error where PHP should make an assumptions of something!!!!

If the class organized as a singleton you can always use function getInstance() and then use getData()

Likse:

$classObj = MyClass::getInstance();
$classObj->getData();

If the class is not a singleton, use

 $classObj = new MyClass();
 $classObj->getData();

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

How to make full screen background in a web page

CSS

.bbg { 
    /* The image used */
    background-image: url('...');

    /* Full height */
    height: 100%; 

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;    
}

HTML

<!doctype html>
<html class="h-100">
.
.
.
<body class="bbg">
</body>
.
.
.
</html>

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

How do I detect unsigned integer multiply overflow?

Calculate the results with doubles. They have 15 significant digits. Your requirement has a hard upper bound on c of 108 — it can have at most 8 digits. Hence, the result will be precise if it's in range, and it will not overflow otherwise.

Difference between sh and bash

/bin/sh may or may not invoke the same program as /bin/bash.

sh supports at least the features required by POSIX (assuming a correct implementation). It may support extensions as well.

bash, the "Bourne Again Shell", implements the features required for sh plus bash-specific extensions. The full set of extensions is too long to describe here, and it varies with new releases. The differences are documented in the bash manual. Type info bash and read the "Bash Features" section (section 6 in the current version), or read the current documentation online.

tap gesture recognizer - which object was tapped?

If you are adding different UIGestureRecognizer on different UIViews and want to distinguish in the action method then you can check the property view in the sender parameter which will give you the sender view.

How do I jump to a closing bracket in Visual Studio Code?

In Spanish keyboard it's Ctrl+Shift+º

It seems to change from one keyboard layout to another, so better look for it with Cmd+Shift+P and type "go to bracket" as others suggested.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

!python 'script.py'

replace script.py with your real file name, DON'T forget ''

Create an Array of Arraylists

ArrayList<Integer>[] graph = new ArrayList[numCourses] It works.

Add event handler for body.onload by javascript within <body> part

body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I believe this error message is due to a "zombie transaction".

Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?

It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.

Can you debug into the error code? Do you have a stack trace?

MySQL direct INSERT INTO with WHERE clause

Example of how to perform a INSERT INTO SELECT with a WHERE clause.

INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2

How to find the 'sizeof' (a pointer pointing to an array)?

No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof().

Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1 as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

Add "Are you sure?" to my excel button, how can I?

Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.

Sub AreYouSure()

Dim Sure As Integer

Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess

End Sub

Jesse

How to check if input date is equal to today's date?

The Best way and recommended way of comparing date in typescript is:

var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();

if(today === reqDateVar){
 // NOW
} else {
 // Some other time
}

Cannot run Eclipse; JVM terminated. Exit code=13

I had the same issue with eclipse in my both machine. I had jre 32 bit installed. So I removed 32 bit and installed 64 bit instead and it worked perfectly.

jQuery DataTables: control table width

find another useful link about this problem and it resolved my problem.

<table width="100%">
<tr>
    <td width="20%"> Left TD <td>
    <td width="80%"> Datatable </td>
</tr>
</table>

Datatables force width table

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

How to check if IEnumerable is null or empty?

Without custom helpers I recommend either ?.Any() ?? false or ?.Any() == true which are relatively concise and only need to specify the sequence once.


When I want to treat a missing collection like an empty one, I use the following extension method:

public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
    return sequence ?? Enumerable.Empty<T>();
}

This function can be combined with all LINQ methods and foreach, not just .Any(), which is why I prefer it over the more specialized helper functions people are proposing here.

how to display data values on Chart.js

Here is an updated version for Chart.js 2.3

Sep 23, 2016: Edited my code to work with v2.3 for both line/bar type.

Important: Even if you don't need the animation, don't change the duration option to 0, otherwise you will get chartInstance.controller is undefined error.

_x000D_
_x000D_
var chartData = {_x000D_
    labels: ["January", "February", "March", "April", "May", "June"],_x000D_
        datasets: [_x000D_
            {_x000D_
                fillColor: "#79D1CF",_x000D_
                strokeColor: "#79D1CF",_x000D_
                data: [60, 80, 81, 56, 55, 40]_x000D_
            }_x000D_
        ]_x000D_
    };_x000D_
_x000D_
var opt = {_x000D_
    events: false,_x000D_
    tooltips: {_x000D_
        enabled: false_x000D_
    },_x000D_
    hover: {_x000D_
        animationDuration: 0_x000D_
    },_x000D_
    animation: {_x000D_
        duration: 1,_x000D_
        onComplete: function () {_x000D_
            var chartInstance = this.chart,_x000D_
                ctx = chartInstance.ctx;_x000D_
            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);_x000D_
            ctx.textAlign = 'center';_x000D_
            ctx.textBaseline = 'bottom';_x000D_
_x000D_
            this.data.datasets.forEach(function (dataset, i) {_x000D_
                var meta = chartInstance.controller.getDatasetMeta(i);_x000D_
                meta.data.forEach(function (bar, index) {_x000D_
                    var data = dataset.data[index];                            _x000D_
                    ctx.fillText(data, bar._model.x, bar._model.y - 5);_x000D_
                });_x000D_
            });_x000D_
        }_x000D_
    }_x000D_
};_x000D_
 var ctx = document.getElementById("Chart1"),_x000D_
     myLineChart = new Chart(ctx, {_x000D_
        type: 'bar',_x000D_
        data: chartData,_x000D_
        options: opt_x000D_
     });
_x000D_
<canvas id="myChart1" height="300" width="500"></canvas>
_x000D_
_x000D_
_x000D_

download csv file from web api in angular js

I used the below solution and it worked for me.

_x000D_
_x000D_
 if (window.navigator.msSaveOrOpenBlob) {_x000D_
   var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
     type: "text/csv;charset=utf-8;"_x000D_
   });_x000D_
   navigator.msSaveBlob(blob, 'filename.csv');_x000D_
 } else {_x000D_
   var a = document.createElement('a');_x000D_
   a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);_x000D_
   a.target = '_blank';_x000D_
   a.download = 'filename.csv';_x000D_
   document.body.appendChild(a);_x000D_
   a.click();_x000D_
 }
_x000D_
_x000D_
_x000D_

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Show Console in Windows Application?

Disclaimer

There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.

This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine(), Console.Read()) with the console window if you do not show the windows forms; output to Console - Console.WriteLine() - works in both modes.

This is provided as is; no guarantees this won't do something horrible later on, but it does work.

Project steps

Start from a standard Console Application.

Mark the Main method as [STAThread]

Add a reference in your project to System.Windows.Forms

Add a Windows Form to your project.

Add the standard Windows start code to your Main method:

End Result

You will have an application that shows the Console and optionally windows forms.

Sample Code

Program.cs

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

namespace ConsoleApplication9 {
    class Program {

        [STAThread]
        static void Main(string[] args) {

            if (args.Length > 0 && args[0] == "console") {
                Console.WriteLine("Hello world!");
                Console.ReadLine();
            }
            else {
                Application.EnableVisualStyles(); 
                Application.SetCompatibleTextRenderingDefault(false); 
                Application.Run(new Form1());
            }
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ConsoleApplication9 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Click(object sender, EventArgs e) {
            Console.WriteLine("Clicked");
        }
    }
}

How to always show the vertical scrollbar in a browser?

Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..

<style>
    .scrollholder {
        position: relative;
        width: 310px; height: 350px;
        overflow: auto;
        z-index: 1;
    }
</style>

<script>
    function isTouchDevice() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    function touchScroll(id) {
        if (isTouchDevice()) { //if touch events exist...
            var el = document.getElementById(id);
            var scrollStartPos = 0;

            document.getElementById(id).addEventListener("touchstart", function (event) {
                scrollStartPos = this.scrollTop + event.touches[0].pageY;
                event.preventDefault();
            }, false);

            document.getElementById(id).addEventListener("touchmove", function (event) {
                this.scrollTop = scrollStartPos - event.touches[0].pageY;
                event.preventDefault();
            }, false);
        }
    }
</script>

<body onload="touchScroll('scrollMe')">

    <!-- title -->
    <!-- <div class="title" onselectstart="return false">Alarms</div> -->
    <div class="scrollholder" id="scrollMe">

</div>
</body>

How can I use JavaScript in Java?

I just wanted to answer something new for this question - J2V8.

Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""

Highly Efficient Java & JavaScript Integration

Github link

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Set "VM options" like: "-cp $Classpath$;your_classpath"

VM options

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

How do I measure execution time of a command on the Windows command line?

Not quite as elegant as some of the functionality on Unix, but create a cmd file which looks like:

@echo off
time < nul
yourexecutable.exe > c:\temp\output.txt
time < nul
rem on newer windows system you can try time /T

That will display the start and stop times like so:

The current time is: 10:31:57.92
Enter the new time:
The current time is: 10:32:05.94
Enter the new time:

Display label text with line breaks in c#

I know this thread is old, but...

If you're using html encoding (like AntiXSS), the previous answers will not work. The break tags will be rendered as text, rather than applying a carriage return. You can wrap your asp label in a pre tag, and it will display with whatever line breaks are set from the code behind.

Example:

<pre style="width:600px;white-space:pre-wrap;"><asp:Label ID="lblMessage" Runat="server" visible ="true"/></pre>

How to disable the ability to select in a DataGridView?

This worked for me like a charm:

row.DataGridView.Enabled = false;

row.DefaultCellStyle.BackColor = Color.LightGray;

row.DefaultCellStyle.ForeColor = Color.DarkGray;

(where row = DataGridView.NewRow(appropriate overloads);)

How to update/modify an XML file in python?

Using ElementTree:

import xml.etree.ElementTree

# Open original file
et = xml.etree.ElementTree.parse('file.xml')

# Append new tag: <a x='1' y='abc'>body text</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body text'
new_tag.attrib['x'] = '1' # must be str; cannot be an int
new_tag.attrib['y'] = 'abc'

# Write back to file
#et.write('file.xml')
et.write('file_new.xml')

note: output written to file_new.xml for you to experiment, writing back to file.xml will replace the old content.

IMPORTANT: the ElementTree library stores attributes in a dict, as such, the order in which these attributes are listed in the xml text will NOT be preserved. Instead, they will be output in alphabetical order. (also, comments are removed. I'm finding this rather annoying)

ie: the xml input text <b y='xxx' x='2'>some body</b> will be output as <b x='2' y='xxx'>some body</b>(after alphabetising the order parameters are defined)

This means when committing the original, and changed files to a revision control system (such as SVN, CSV, ClearCase, etc), a diff between the 2 files may not look pretty.

How to set radio button selected value using jquery

  <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked > 
 //       For Example it is checked
 <input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >


<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" > 
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >


      $( "input[type='radio']" ).change(function() //on change radio buttons
   {


    alert('Test');
   if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value
 {

$('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes');

}
    });

http://jsfiddle.net/6d6FJ/1/ Demo

enter image description here

Add a prefix string to beginning of each line

If you have Perl:

perl -pe 's/^/PREFIX/' input.file

Problems with entering Git commit message with Vim

You can change the comment character to something besides # like this:

git config --global core.commentchar "@"

How to count number of records per day?

select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

In a nutshell, [[ is better because it doesn't fork another process. No brackets or a single bracket is slower than a double bracket because it forks another process.

Resizing UITableView to fit content

Swift Solution

Follow these steps:

  1. Set the height constraint for the table from the storyboard.

  2. Drag the height constraint from the storyboard and create @IBOutlet for it in the view controller file.

    @IBOutlet var tableHeight: NSLayoutConstraint!
    
  3. Then you can change the height for the table dynamicaly using this code:

    override func viewWillLayoutSubviews() {
        super.updateViewConstraints()
        self.tableHeight?.constant = self.table.contentSize.height
    }
    

If the last row is cut off, try to call viewWillLayoutSubviews() in willDisplay cell function:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    self.viewWillLayoutSubviews()
}

Calculating the angle between the line defined by two points

A few answers here have tried to explain the "screen" issue where top left is 0,0 and bottom right is (positive) screen width, screen height. Most grids have the Y axis as positive above X not below.

The following method will work with screen values instead of "grid" values. The only difference to the excepted answer is the Y values are inverted.

/**
 * Work out the angle from the x horizontal winding anti-clockwise 
 * in screen space. 
 * 
 * The value returned from the following should be 315. 
 * <pre>
 * x,y -------------
 *     |  1,1
 *     |    \
 *     |     \
 *     |     2,2
 * </pre>
 * @param p1
 * @param p2
 * @return - a double from 0 to 360
 */
public static double angleOf(PointF p1, PointF p2) {
    // NOTE: Remember that most math has the Y axis as positive above the X.
    // However, for screens we have Y as positive below. For this reason, 
    // the Y values are inverted to get the expected results.
    final double deltaY = (p1.y - p2.y);
    final double deltaX = (p2.x - p1.x);
    final double result = Math.toDegrees(Math.atan2(deltaY, deltaX)); 
    return (result < 0) ? (360d + result) : result;
}

Adding a regression line on a ggplot

I found this function on a blog

 ggplotRegression <- function (fit) {

    `require(ggplot2)

    ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                         "Intercept =",signif(fit$coef[[1]],5 ),
                         " Slope =",signif(fit$coef[[2]], 5),
                         " P =",signif(summary(fit)$coef[2,4], 5)))
    }`

once you loaded the function you could simply

ggplotRegression(fit)

you can also go for ggplotregression( y ~ x + z + Q, data)

Hope this helps.

Pass arguments to Constructor in VBA

Another approach

Say you create a class clsBitcoinPublicKey

In the class module create an ADDITIONAL subroutine, that acts as you would want the real constructor to behave. Below I have named it ConstructorAdjunct.

Public Sub ConstructorAdjunct(ByVal ...)

 ...

End Sub

From the calling module, you use an additional statement

Dim loPublicKey AS clsBitcoinPublicKey

Set loPublicKey = New clsBitcoinPublicKey

Call loPublicKey.ConstructorAdjunct(...)

The only penalty is the extra call, but the advantage is that you can keep everything in the class module, and debugging becomes easier.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Context envContext = (Context)initContext.lookup("java:comp/env");

not:Context envContext = (Context)initContext.lookup("java:/comp/env");

C function that counts lines in file

You have a ; at the end of the if. Change:

  if (fp == NULL);
  return 0;

to

  if (fp == NULL) 
    return 0;

How do I check for equality using Spark Dataframe without SQL Query?

In Spark 2.4

To compare with one value:

df.filter(lower(trim($"col_name")) === "<value>").show()

To compare with collection of value:

df.filter($"col_name".isInCollection(new HashSet<>(Arrays.asList("value1", "value2")))).show()

Using OR operator in a jquery if statement

The code you wrote will always return true because state cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15).... AND is what you need not OR.

Use $.inArray instead. This returns the index of the element in the array.

JSFIDDLE DEMO

var statesArray = [10, 15, 19]; // list out all

var index = $.inArray(state, statesArray);

if(index == -1) {
    console.log("Not there in array");
    return true;

} else {
    console.log("Found it");
    return false;
}

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Other possible solution : I tried to map the result of a restTemplate.getForObject with a private class instance (defined inside of my working class). It did not work, but if I define the object to public, inside its own file, it worked correctly.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

Zero => Everything Okay

Positive => Something I expected could potentially go wrong went wrong (bad command-line, can't find file, could not connect to server)

Negative => Something I didn't expect at all went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9)

(values greater than 128 are actually negative, if you regard them as 8-bit signed binary, or twos complement)

There's a load of good standard exit-codes here

Multiprocessing vs Threading Python

The key advantage is isolation. A crashing process won't bring down other processes, whereas a crashing thread will probably wreak havoc with other threads.

How do I find out if the GPS of an Android device is enabled

In android, we can easily check whether GPS is enabled in device or not using LocationManager.

Here is a simple program to Check.

GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

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

Your java class file should be

public class ExampleApp extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

The output will looks like

enter image description here

enter image description here

Failed to execute 'createObjectURL' on 'URL':

I fixed it downloading the latest version from GgitHub GitHub url

How can I keep Bootstrap popovers alive while being hovered?

I found that the accepted answer and the similar ones to it had some flaws. Mainly that it's repeatedly adding that mouseleave listener to the element.

I've combined their solution with some custom code to achieve the functionality in question without memory leaks or listener bloat.

    var getPopoverTimeout = function ($el) {
        return $el.data('timeout');
    }
    $element.popover({
        trigger: "manual",
        html: true,
        content: ...,
        title: ...,
        container: $element
     }).on("mouseenter", function () {
        var $this = $(this);
        if (!$this.find('.popover').length) {
            $this.popover("show");
        } else if (getPopoverTimeout($element)) {
            clearTimeout(getPopoverTimeout($element));
        }
    }).on("mouseleave", function () {
        var $this = $(this);
        $element.data('timeout', setTimeout(function () {
            if (!$(".popover:hover").length) {
                $this.popover("hide")
            }
        }, 250));
    });

Which provides a nice 'hover-intent' like solution so that it doesn't flash in and out.

Displaying a vector of strings in C++

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.

#include <iostream>
#include <vector>
#include <string.h>

int main ()
{
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}

mysql extract year from date format

This should work if the date format is consistent:

select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table 

Convert Difference between 2 times into Milliseconds?

You have to convert textbox's values to DateTime (t1,t2), then:

DateTime t1,t2;
t1 = DateTime.Parse(textbox1.Text);
t2 = DateTime.Parse(textbox2.Text);
int diff = ((TimeSpan)(t2 - t1)).TotalMilliseconds;

Or use DateTime.TryParse(textbox1, out t1); Error handling is up to you.

Use css gradient over background image

Ok, I solved it by adding the url for the background image at the end of the line.

Here's my working code:

_x000D_
_x000D_
.css {_x000D_
  background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
_x000D_
_x000D_

Perl read line by line

If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

Here's how to do it:

use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

If you want to use a counter instead, use

my $count = 0;
while( my $line = <$info>)  {   
    print $line;    
    last if ++$count == 2;
}

ALTER DATABASE failed because a lock could not be placed on database

After you get the error, run

EXEC sp_who2

Look for the database in the list. It's possible that a connection was not terminated. If you find any connections to the database, run

KILL <SPID>

where <SPID> is the SPID for the sessions that are connected to the database.

Try your script after all connections to the database are removed.

Unfortunately, I don't have a reason why you're seeing the problem, but here is a link that shows that the problem has occurred elsewhere.

http://www.geakeit.co.uk/2010/12/11/sql-take-offline-fails-alter-database-failed-because-a-lock-could-not-error-5061/

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

Android Webview gives net::ERR_CACHE_MISS message

Use

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }

It should solve the error.

How to use log levels in java

Generally, you don't need all those levels, SEVERE, WARNING, INFO, FINE might be enough. We're using Log4J (not java.util.logging directly) and the following levels (which might differ in name from other logging frameworks):

  • ERROR: Any error/exception that is or might be critical. Our Logger automatically sends an email for each such message on our servers (usage: logger.error("message"); )

  • WARN: Any message that might warn us of potential problems, e.g. when a user tried to log in with wrong credentials - which might indicate an attack if that happens often or in short periods of time (usage: logger.warn("message"); )

  • INFO: Anything that we want to know when looking at the log files, e.g. when a scheduled job started/ended (usage: logger.info("message"); )

  • DEBUG: As the name says, debug messages that we only rarely turn on. (usage: logger.debug("message"); )

The beauty of this is that if you set the log level to WARN, info and debug messages have next to no performance impact. If you need to get additional information from a production system you just can lower the level to INFO or DEBUG for a short period of time (since you'd get much more log entries which make your log files bigger and harder to read). Adjusting log levels etc. can normally be done at runtime (our JBoss instance checks for changes in that config every minute or so).

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

How to specify 64 bit integers in c

How to specify 64 bit integers in c

Going against the usual good idea to appending LL.

Appending LL to a integer constant will insure the type is at least as wide as long long. If the integer constant is octal or hex, the constant will become unsigned long long if needed.

If ones does not care to specify too wide a type, then LL is OK. else, read on.

long long may be wider than 64-bit.

Today, it is rare that long long is not 64-bit, yet C specifies long long to be at least 64-bit. So by using LL, in the future, code may be specifying, say, a 128-bit number.

C has Macros for integer constants which in the below case will be type int_least64_t

#include <stdint.h>
#include <inttypes.h>

int main(void) {
  int64_t big = INT64_C(9223372036854775807);
  printf("%" PRId64 "\n", big);
  uint64_t jenny = INT64_C(0x08675309) << 32;  // shift was done on at least 64-bit type 
  printf("0x%" PRIX64 "\n", jenny);
}

output

9223372036854775807
0x867530900000000

How to use multiple LEFT JOINs in SQL?

The required SQL will be some like:-

SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....

Hope it helps.

Eloquent - where not equal to

Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)

Code::where(function ($query) {
            $query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');                  
        })->get();

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

For example folder named new under E: drive

type the command:

e:\cd new

e:\new\attrib *.* -s -h /s /d

and all the files and folders are un-hidden

getActionBar() returns null

You have to define window type as actionbar before activity render its view.

use

requestWindowFeature(Window.FEATURE_ACTION_BAR);

before calling setContentView() method.

A project with an Output Type of Class Library cannot be started directly

Just right click on the Project Solution A window pops up. Expand the common Properties. Select Start Up Project

In there on right hand side Select radio button with Single Startup Project Select your Project in there and apply.

That's it. Now save and build your project. Run the project to see the output.

What is the syntax for adding an element to a scala.collection.mutable.Map?

The point is that the first line of your codes is not what you expected.

You should use:

val map = scala.collection.mutable.Map[A,B]()

You then have multiple equivalent alternatives to add items:

scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()


scala> map("k1") = "v1"

scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))


scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))


scala> map.put("k3", "v3")
res3: Option[String] = None

scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))

And starting Scala 2.13:

scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

SQL Server Escape an Underscore

I had a similar issue using like pattern '%_%' did not work - as the question indicates :-)

Using '%\_%' did not work either as this first \ is interpreted "before the like".

Using '%\\_%' works. The \\ (double backslash) is first converted to single \ (backslash) and then used in the like pattern.

Conversion of Char to Binary in C

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

How to debug a GLSL shader?

I am sharing a fragment shader example, how i actually debug.

#version 410 core

uniform sampler2D samp;
in VS_OUT
{
    vec4 color;
    vec2 texcoord;
} fs_in;

out vec4 color;

void main(void)
{
    vec4 sampColor;
    if( texture2D(samp, fs_in.texcoord).x > 0.8f)  //Check if Color contains red
        sampColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);  //If yes, set it to white
    else
        sampColor = texture2D(samp, fs_in.texcoord); //else sample from original
    color = sampColor;

}

enter image description here

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

DateTime "null" value

For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue, because it is a value type rather than a reference type.

You can also use a nullable DateTime, like this:

DateTime? MyNullableDate;

Or the longer form:

Nullable<DateTime> MyNullableDate;

And, finally, there's a built in way to reference the default of any type. This returns null for reference types, but for our DateTime example it will return the same as DateTime.MinValue:

default(DateTime)

or, in more recent versions of C#,

default

How do I override nested NPM dependency versions?

For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".

For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "glob": "7.1.2",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  }
},

Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  },
  "dependencies": {
    "glob": {
      "version": "3.2.11"
    }
  }
},

Now remove your node_modules folder, run npm install and it will add missing parts to the "dependencies" section.

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

call a static method inside a class?

Let's assume this is your class:

class Test
{
    private $baz = 1;

    public function foo() { ... }

    public function bar() 
    {
        printf("baz = %d\n", $this->baz);
    }

    public static function staticMethod() { echo "static method\n"; }
}

From within the foo() method, let's look at the different options:

$this->staticMethod();

So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.

$this::staticMethod();

Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:

self::staticMethod();

Now, before you start thinking that the :: is the static call operator, let me give you another example:

self::bar();

This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.

To see all of this in action, see this 3v4l.org output.

Using two values for one switch case statement

Just do

case text1: case text4: 
     do stuff;
     break;

Print a div using javascript in angularJS single page application

I done this way:

$scope.printDiv = function (div) {
  var docHead = document.head.outerHTML;
  var printContents = document.getElementById(div).outerHTML;
  var winAttr = "location=yes, statusbar=no, menubar=no, titlebar=no, toolbar=no,dependent=no, width=865, height=600, resizable=yes, screenX=200, screenY=200, personalbar=no, scrollbars=yes";

  var newWin = window.open("", "_blank", winAttr);
  var writeDoc = newWin.document;
  writeDoc.open();
  writeDoc.write('<!doctype html><html>' + docHead + '<body onLoad="window.print()">' + printContents + '</body></html>');
  writeDoc.close();
  newWin.focus();
}

Update Git branches from master

If you've been working on a branch on-and-off, or lots has happened in other branches while you've been working on something, it's best to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.

git checkout master
git pull
git checkout local_branch_name
git rebase master
git push --force # force required if you've already pushed

Notes:

  • Don't rebase branches that you've collaborated with others on.
  • You should rebase on the branch to which you will be merging which may not always be master.

There's a chapter on rebasing at http://git-scm.com/book/ch3-6.html, and loads of other resources out there on the web.

How to see the changes in a Git commit?

You can also try this easy way:

git show <COMMIT>

SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

select Subject, 
       CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration 
where MerchantId =@MerchantID 

How to print a two dimensional array?

I am also a beginner and I've just managed to crack this using two nested for loops.

I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.

P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.

public static void printGrid() {
    for (int i = 0; i < moleGrid.length; i++) {
        for (int j = 0; j < moleGrid[0].length; j++) {
            if (j == 0 || j % (moleGrid.length - 1) != 0) {
                System.out.print(moleGrid[i][j]);
            }
            else {
                System.out.println(moleGrid[i][j]);
            }
         }
     }
}

Hope it helps!

How can I find and run the keytool

Alternatively you can do the following :

  • copy the bat file below in any folder already present in your PATH environment variable
  • then simply use keytool command in any Windows shell

Actual location of keytool is defined in the bat file. In case the location is wrong the bat file will scan your system to detect potential locations in ProgramFiles (sub)folders.

Also find keytool2.bat, a convinient shortcut for "keytool -v -list -keystore", which is widely used to quickly check the content of a jks file.

keytool.bat :


:: 
:: 
:: "keytool alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: also see keytool2.bat that automatically adds the following parameters in the keytool command line : -v -list -keystore, for quick display of jks content
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe

rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

keytool2.bat :


:: 
:: 
:: "keytool2 alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: keytool2 automatically adds the following parameters in the keytool command line : -v -list -keystore
:: thus, to quickly display the full content of a jks file, usage is simply : keytool2 \path\to\your\keystore.jks [-alias your_alias]
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe


rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% -v -list -keystore %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

How to see indexes for a database or table in MySQL?

Why not show create table myTable ?

Someone told me this but I didn't see anyone mention here, anything bad?

It's neat if you just want to take a glance at the indexes along with column infomations.

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

grep -r --include=*.{cc,h} "hello" .

This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this . (current) directory

From another stackoverflow question

Is it not possible to define multiple constructors in Python?

The easiest way is through keyword arguments:

class City():
  def __init__(self, city=None):
    pass

someCity = City(city="Berlin")

This is pretty basic stuff. Maybe look at the Python documentation?

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

Writelines writes lines without newline, Just fills the file

As we have well established here, writelines does not append the newlines for you. But, what everyone seems to be missing, is that it doesn't have to when used as a direct "counterpart" for readlines() and the initial read persevered the newlines!

When you open a file for reading in binary mode (via 'rb'), then use readlines() to fetch the file contents into memory, split by line, the newlines remain attached to the end of your lines! So, if you then subsequently write them back, you don't likely want writelines to append anything!

So if, you do something like:

with open('test.txt','rb') as f: lines=f.readlines()
with open('test.txt','wb') as f: f.writelines(lines)

You should end up with the same file content you started with.

How to use git merge --squash?

if you get error: Committing is not possible because you have unmerged files.

git checkout master
git merge --squash bugfix
git add .
git commit -m "Message"

fixed all the Conflict files

git add . 

you could also use

git add [filename]

How do I debug error ECONNRESET in Node.js?

Had the same problem today. After some research i found a very useful --abort-on-uncaught-exception node.js option. Not only it provides much more verbose and useful error stack trace, but also saves core file on application crash allowing further debug.

JavaScript REST client Library

For reference I want to add about ExtJS, as explained in Manual: RESTful Web Services. In short, use method to specify GET, POST, PUT, DELETE. Example:

Ext.Ajax.request({
    url: '/articles/restful-web-services',
    method: 'PUT',
    params: {
        author: 'Patrick Donelan',
        subject: 'RESTful Web Services are easy with Ext!'
    }
});

If the Accept header is necessary, it can be set as a default for all requests:

Ext.Ajax.defaultHeaders = {
    'Accept': 'application/json'
};

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

Read an Excel file directly from a R script

As noted above in many of the other answers, there are many good packages that connect to the XLS/X file and get the data in a reasonable way. However, you should be warned that under no circumstances should you use the clipboard (or a .csv) file to retrieve data from Excel. To see why, enter =1/3 into a cell in excel. Now, reduce the number of decimal points visible to you to two. Then copy and paste the data into R. Now save the CSV. You'll notice in both cases Excel has helpfully only kept the data that was visible to you through the interface and you've lost all of the precision in your actual source data.

ImportError: Cannot import name X

This is a circular dependency. we can solve this problem by using import module or class or function where we needed. if we use this approach, we can fix circular dependency

A.py

from B import b2
def a1():
    print('a1')
    b2()

B.py

def b1():
   from A import a1
   print('b1')
   a1()

def b2():
   print('b2')
if __name__ == '__main__':
   b1() 

IE8 support for CSS Media Query

The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:

<!--[if lt IE 9]>
<script src="respond.min.js"></script>
<![endif]-->

It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

CustomErrors mode="Off"

For Sharepoint 2010 applications, you should also edit C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\web.config and define <customErrors mode="Off" />

Set up an HTTP proxy to insert a header

i'd try tinyproxy. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for Lua, especially after seeing how well it worked for mysqlproxy

How to read existing text files without defining path

As your project is a console project you can pass the path to the text files that you want to read via the string[] args

static void Main(string[] args)
{
}

Within Main you can check if arguments are passed

if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}

Extract an argument

string fileToRead = args[0];

Nearly all languages support the concept of argument passing and follow similar patterns to C#.

For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

Right Click on your project: Run (As) -> Maven clean Right Click on your project: Run (As) -> Maven install

Naming threads and thread-pools of ExecutorService

As other answers already said, you may create and use your own implementation of the java.util.concurrent.ThreadFactory interface (no external libraries required). I am pasting my code below because it is different than previous answers since it uses String.format method and takes a base name for the threads as a constructor argument:

import java.util.concurrent.ThreadFactory;

public class NameableThreadFactory implements ThreadFactory{
    private int threadsNum;
    private final String namePattern;

    public NameableThreadFactory(String baseName){
        namePattern = baseName + "-%d";
    }

    @Override
    public Thread newThread(Runnable runnable){
        threadsNum++;
        return new Thread(runnable, String.format(namePattern, threadsNum));
    }    
}

And this is an example of usage:

ThreadFactory  threadFactory = new NameableThreadFactory("listenerThread");        
final ExecutorService executorService = Executors.newFixedThreadPool(5, threadFactory);

EDIT: making my ThreadFactory implementation thread-safe, thanks to @mchernyakov for pointing it out.
Even though nowhere in the ThreadFactory documentation is said that its implementations must be thread-safe, the fact that the DefaultThreadFactory is thread-safe is a big hint:

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NameableThreadFactory implements ThreadFactory{
    private final AtomicInteger threadsNum = new AtomicInteger();

    private final String namePattern;

    public NameableThreadFactory(String baseName){
        namePattern = baseName + "-%d";
    }

    @Override
    public Thread newThread(Runnable runnable){
        return new Thread(runnable, String.format(namePattern, threadsNum.addAndGet(1)));
    }    
}

Testing the type of a DOM element in JavaScript

Although the previous answers work perfectly, I will just add another way where the elements can also be classified using the interface they have implemented.

Refer W3 Org for available interfaces

_x000D_
_x000D_
console.log(document.querySelector("#anchorelem") instanceof HTMLAnchorElement);_x000D_
console.log(document.querySelector("#divelem") instanceof HTMLDivElement);_x000D_
console.log(document.querySelector("#buttonelem") instanceof HTMLButtonElement);_x000D_
console.log(document.querySelector("#inputelem") instanceof HTMLInputElement);
_x000D_
<a id="anchorelem" href="">Anchor element</a>_x000D_
<div id="divelem">Div Element</div>_x000D_
<button id="buttonelem">Button Element</button>_x000D_
<br><input id="inputelem">
_x000D_
_x000D_
_x000D_

The interface check can be made in 2 ways as elem instanceof HTMLAnchorElement or elem.constructor.name == "HTMLAnchorElement", both returns true

Best way to find if an item is in a JavaScript array?

[ ].has(obj)

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
{
    value:function(o, flag){
    if (flag === undefined) {
        return this.indexOf(o) !== -1;
    } else {   // only for raw js object
        for(var v in this) {
            if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
        }
        return false;                       
    },
    // writable:false,
    // enumerable:false
})

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

comparing raw objects

[o1].has(o2,true) // true if every level value is same

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

How to return temporary table from stored procedure

YES YOU CAN.

In your stored procedure, you fill the table @tbRetour.

At the very end of your stored procedure, you write:

SELECT * FROM @tbRetour 

To execute the stored procedure, you write:

USE [...]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'

GO

How to use PrintWriter and File classes in Java?

Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder. If that does not work.

PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

CXF: No message body writer found for class - automatically mapping non-simple resources

You can also configure CXFNonSpringJAXRSServlet (assuming JSONProvider is used):

<init-param>
  <param-name>jaxrs.providers</param-name>
  <param-value>
      org.apache.cxf.jaxrs.provider.JSONProvider
      (writeXsiType=false)
  </param-value> 
</init-param>

Best way to display data via JSON using jQuery

Something like this:

$.getJSON("http://mywebsite.com/json/get.php?cid=15",
        function(data){
          $.each(data.products, function(i,product){
            content = '<p>' + product.product_title + '</p>';
            content += '<p>' + product.product_short_description + '</p>';
            content += '<img src="' + product.product_thumbnail_src + '"/>';
            content += '<br/>';
            $(content).appendTo("#product_list");
          });
        });

Would take a json object made from a PHP array returned with the key of products. e.g:

Array('products' => Array(0 => Array('product_title' => 'Product 1',
                                     'product_short_description' => 'Product 1 is a useful product',
                                     'product_thumbnail_src' => '/images/15/1.jpg'
                                    )
                          1 => Array('product_title' => 'Product 2',
                                     'product_short_description' => 'Product 2 is a not so useful product',
                                     'product_thumbnail_src' => '/images/15/2.jpg'
                                    )
                         )
     )

To reload the list you would simply do:

$("#product_list").empty();

And then call getJSON again with new parameters.

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

How to use ImageBackground to set background image for screen in react-native

Two options:

  1. Try setting width and height to width and height of the device screen
  2. Good old position absolute

Code for #2:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}

Edit: For option #2 you can experiment with resizeMode="stretch|cover"

Edit 2: Keep in mind that option #2 renders the image and then everything after that in this order, which means that some pixels are rendered twice, this might have a very small performance impact (usually unnoticeable) but just for your information

Difficulty with ng-model, ng-repeat, and inputs

The problem seems to be in the way how ng-model works with input and overwrites the name object, making it lost for ng-repeat.

As a workaround, one can use the following code:

<div ng-repeat="name in names">
    Value: {{name}}
    <input ng-model="names[$index]">                         
</div>

Hope it helps

How to convert PDF files to images

The NuGet package Pdf2Png is available for free and is only protected by the MIT License, which is very open.

I've tested around a bit and this is the code to get it to convert a PDF file to an image (tt does save the image in the debug folder).

using cs_pdf_to_image;
using PdfToImage;

private void BtnConvert_Click(object sender, EventArgs e)
{
    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            string PdfFile = openFileDialog1.FileName;
            string PngFile = "Convert.png";
            List<string> Conversion = cs_pdf_to_image.Pdf2Image.Convert(PdfFile, PngFile);
            Bitmap Output = new Bitmap(PngFile);
            PbConversion.Image = Output;
        }
        catch(Exception E)
        {
            MessageBox.Show(E.Message);
        }
    }
}

How to check if object has any properties in JavaScript?

var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist

Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOT loop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)

When do I need to use a semicolon vs a slash in Oracle SQL?

I only use the forward slash once at the end of each script, to tell sqlplus that there is not more lines of code. In the middle of a script, I do not use a slash.

Getting the actual usedrange

Public Sub FindTrueUsedRange(RowLast As Long, ColLast As Long)
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    RowLast = 0
    ColLast = 0
    ActiveSheet.UsedRange.Select
    Cells(1, 1).Activate
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    On Error GoTo -1: On Error GoTo Quit
    Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Activate
    On Error GoTo -1: On Error GoTo 0
    RowLast = Selection.Row
    Cells(1, 1).Activate
    Selection.End(xlToRight).Select
    Selection.End(xlToRight).Select
    Cells.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Activate
    ColLast = Selection.Column
Quit:
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    On Error GoTo -1: On Error GoTo 0
End Sub

How to upload a file to directory in S3 bucket using boto

For upload folder example as following code and S3 folder picture enter image description here

import boto
import boto.s3
import boto.s3.connection
import os.path
import sys    

# Fill in info on data to upload
# destination bucket name
bucket_name = 'willie20181121'
# source directory
sourceDir = '/home/willie/Desktop/x/'  #Linux Path
# destination directory name (on s3)
destDir = '/test1/'   #S3 Path

#max size in bytes before uploading in parts. between 1 and 5 GB recommended
MAX_SIZE = 20 * 1000 * 1000
#size of parts when uploading in parts
PART_SIZE = 6 * 1000 * 1000

access_key = 'MPBVAQ*******IT****'
secret_key = '11t63yDV***********HgUcgMOSN*****'

conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        host = '******.org.tw',
        is_secure=False,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn.create_bucket(bucket_name,
        location=boto.s3.connection.Location.DEFAULT)


uploadFileNames = []
for (sourceDir, dirname, filename) in os.walk(sourceDir):
    uploadFileNames.extend(filename)
    break

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()

for filename in uploadFileNames:
    sourcepath = os.path.join(sourceDir + filename)
    destpath = os.path.join(destDir, filename)
    print ('Uploading %s to Amazon S3 bucket %s' % \
           (sourcepath, bucket_name))

    filesize = os.path.getsize(sourcepath)
    if filesize > MAX_SIZE:
        print ("multipart upload")
        mp = bucket.initiate_multipart_upload(destpath)
        fp = open(sourcepath,'rb')
        fp_num = 0
        while (fp.tell() < filesize):
            fp_num += 1
            print ("uploading part %i" %fp_num)
            mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE)

        mp.complete_upload()

    else:
        print ("singlepart upload")
        k = boto.s3.key.Key(bucket)
        k.key = destpath
        k.set_contents_from_filename(sourcepath,
                cb=percent_cb, num_cb=10)

PS: For more reference URL

Insert null/empty value in sql datetime column by default

if there is no value inserted, the default value should be null,empty

In the table definition, make this datetime column allows null, be not defining NOT NULL:

...
DateTimeColumn DateTime,
...

I HAVE ALLOWED NULL VARIABLES THOUGH.

Then , just insert NULL in this column:

INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);

Or, you can make use of the DEFAULT constaints:

...
DateTimeColumn DateTime DEFAULT NULL,
...

Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:

INSERT INTO Table(name, ...)
VALUES('foo bar', ..);

What does "xmlns" in XML mean?

It defines an XML Namespace.

In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"

In the document, you see elements like: <android:foo />

Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo /> with regards to what it "means" when an XML parser reads the document.

NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.

Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/

How to format Joda-Time DateTime to only mm/dd/yyyy?

I have a very dumb but working option. if you have the String fullDate = "11/15/2013 08:00:00";

   String finalDate = fullDate.split(" ")[0];

That should work easy and fast. :)

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

C++ code file extension? .cc vs .cpp

.cpp is the recommended extension for C++ as far as I know. Some people even recommend using .hpp for C++ headers, just to differentiate from C.

Although the compiler doesn't care what you do, it's personal preference.

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Java 8 for multiple strings:

import com.google.common.base.CaseFormat;



String camelStrings = "YOUR_UPPER, YOUR_TURN, ALT_TAB";

List<String> camelList = Arrays.asList(camelStrings.split(","));
camelList.stream().forEach(i -> System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, i) + ", "));

C++, What does the colon after a constructor mean?

It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.

If you use = to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.