Programs & Examples On #Socks

Socket Secure (SOCKS for short) is an Internet protocol that routes network packets between a client and server through a Proxy server.

How to make python Requests work via socks proxy

# SOCKS5 proxy for HTTP/HTTPS
proxiesDict = {
    'http' : "socks5://1.2.3.4:1080",
    'https' : "socks5://1.2.3.4:1080"
}

# SOCKS4 proxy for HTTP/HTTPS
proxiesDict = {
    'http' : "socks4://1.2.3.4:1080",
    'https' : "socks4://1.2.3.4:1080"
}

# HTTP proxy for HTTP/HTTPS
proxiesDict = {
    'http' : "1.2.3.4:1080",
    'https' : "1.2.3.4:1080"
}

hadoop copy a local file system folder to HDFS

If you copy a folder from local then it will copy folder with all its sub folders to HDFS.

For copying a folder from local to hdfs, you can use

hadoop fs -put localpath

or

hadoop fs -copyFromLocal localpath

or

hadoop fs -put localpath hdfspath

or

hadoop fs -copyFromLocal localpath hdfspath

Note:

If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.

To copy from hdfs to local

 hadoop fs -get hdfspath localpath

Difference between FetchType LAZY and EAGER in Java Persistence API?

By default, for all collection and map objects the fetching rule is FetchType.LAZY and for other instances it follows the FetchType.EAGER policy.
In brief, @OneToMany and @ManyToMany relations does not fetch the related objects (collection and map) implicictly but the retrieval operation is cascaded through the field in @OneToOne and @ManyToOne ones.

(courtesy :- objectdbcom)

Maven does not find JUnit tests to run

I struggle with this problem. In my case I wasn't importing the right @Test annotation.

1) Check if the @Test is from org.junit.jupiter.api.Test (if you are using Junit 5).

2) With Junit5 instead of @RunWith(SpringRunner.class), use @ExtendWith(SpringExtension.class)

import org.junit.jupiter.api.Test;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application.properties")    
public class CotacaoTest {
    @Test
    public void testXXX() {

    }
}

How do I convert a String object into a Hash object?

Please consider this solution. Library+spec:

File: lib/ext/hash/from_string.rb:

require "json"

module Ext
  module Hash
    module ClassMethods
      # Build a new object from string representation.
      #
      #   from_string('{"name"=>"Joe"}')
      #
      # @param s [String]
      # @return [Hash]
      def from_string(s)
        s.gsub!(/(?<!\\)"=>nil/, '":null')
        s.gsub!(/(?<!\\)"=>/, '":')
        JSON.parse(s)
      end
    end
  end
end

class Hash    #:nodoc:
  extend Ext::Hash::ClassMethods
end

File: spec/lib/ext/hash/from_string_spec.rb:

require "ext/hash/from_string"

describe "Hash.from_string" do
  it "generally works" do
    [
      # Basic cases.
      ['{"x"=>"y"}', {"x" => "y"}],
      ['{"is"=>true}', {"is" => true}],
      ['{"is"=>false}', {"is" => false}],
      ['{"is"=>nil}', {"is" => nil}],
      ['{"a"=>{"b"=>"c","ar":[1,2]}}', {"a" => {"b" => "c", "ar" => [1, 2]}}],
      ['{"id"=>34030, "users"=>[14105]}', {"id" => 34030, "users" => [14105]}],

      # Tricky cases.
      ['{"data"=>"{\"x\"=>\"y\"}"}', {"data" => "{\"x\"=>\"y\"}"}],   # Value is a `Hash#inspect` string which must be preserved.
    ].each do |input, expected|
      output = Hash.from_string(input)
      expect([input, output]).to eq [input, expected]
    end
  end # it
end

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

Distinct() with lambda?

Take another way:

var distinctValues = myCustomerList.
Select(x => x._myCaustomerProperty).Distinct();

The sequence return distinct elements compare them by property '_myCaustomerProperty' .

How to stop INFO messages displaying on spark console?

You set disable the Logs by setting its level to OFF as follows:

Logger.getLogger("org").setLevel(Level.OFF);
Logger.getLogger("akka").setLevel(Level.OFF);

or edit log file and set log level to off by just changing the following property:

log4j.rootCategory=OFF, console

XSS filtering function in PHP

Try using for Clean XSS

xss_clean($data): "><script>alert(String.fromCharCode(74,111,104,116,111,32,82,111,98,98,105,101))</script>

ITSAppUsesNonExemptEncryption export compliance while internal testing?

To select from dropdown please start typing following line:

App Uses Non-Exempt Encryption

What is the difference between JAX-RS and JAX-WS?

Can JAX-RS do Asynchronous Request like JAX-WS?

1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.

Can JAX-RS access a web service that is not running on the Java platform, and vice versa?

2) I can't think of any reason it wouldn't be able to.

What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?

3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.

What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?

4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.

On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.

http to https through .htaccess

Try this:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Source: https://www.ndchost.com/wiki/apache/redirect-http-to-https

(I tried so many different blocks of code, this 3 liner worked flawlessly)

PHPUnit assert that an exception was thrown?

<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.

"Initializing" variables in python?

You are asking to initialize four variables using a single float object, which of course is not iterable. You can do -

  1. grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
  2. grade_1 = grade_2 = grade_3 = grade_4 = 0.0

Unless you want to initialize them with different values of course.

Configuration System Failed to Initialize

I started to get this problem after uninstalling Oracle Client Drivers and it removed my C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\machine.config!

Copying it from another computer resolved the problem.

How does the Spring @ResponseBody annotation work?

The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

RS256 vs HS256: What's the difference?

Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.

  • RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

  • HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.

Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.

Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.

The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json, which contains the public key (or keys) of the account.

If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

Proper way to renew distribution certificate for iOS

Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks

CSS: fixed to bottom and centered

I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look

#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}

then in html...

<div id="enclose">
    <div id="problem">
    <!--this is where the text/markup would go-->
    </div>
</div>

There ya go!
-Hypertextie

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

How to write a basic swap function in Java

  class Swap2Values{
    public static void main(String[] args){
       int a = 20, b = 10;

       //before swaping
       System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);

       //swapping
       a = a + b;
       b = a - b;
       a = a - b;

       //after swapping
      System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
    }
  }

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.

How to preview git-pull without doing fetch?

You can fetch from a remote repo, see the differences and then pull or merge.

This is an example for a remote repo called origin and a branch called master tracking the remote branch origin/master:

git checkout master                                                  
git fetch                                        
git diff origin/master
git pull --rebase origin master

convert json ipython notebook(.ipynb) to .py file

  1. Go to https://jupyter.org/
  2. click on nbviewer
  3. Enter the location of your file and render it.
  4. Click on view as code (shown as < />)

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

Array.push() and unique items

You have to use === -1, if it equals to -1 i.e. item is not available in your array:

  this.items = [];

  add(item) {
    if(this.items.indexOf(item) === -1) {
      this.items.push(item);
      console.log(this.items);
    }
  }

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

Attributes / member variables in interfaces?

In Java you can't. Interface has to do with methods and signature, it does not have to do with the internal state of an object -- that is an implementation question. And this makes sense too -- I mean, simply because certain attributes exist, it does not mean that they have to be used by the implementing class. getHeight could actually point to the width variable (assuming that the implementer is a sadist).

(As a note -- this is not true of all languages, ActionScript allows for declaration of pseudo attributes, and I believe C# does too)

Getting selected value of a combobox

I had a similar error, My Class is

public class ServerInfo
{
    public string Text { get; set; }
    public string Value { get; set; }
    public string PortNo { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.

// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;

I hope this helps someone! Cheers!

Java Generics With a Class & an Interface - Together

Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:

<T extends ClassA & InterfaceB>

See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName for each one that you need.

This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max, which (wrapped onto two lines) is:

public static <T extends Object & Comparable<? super T>> T
                                           max(Collection<? extends T> coll)

why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.

It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:

class classB { }
interface interfaceC { }

public class MyClass<T extends classB & interfaceC> {
    Class<T> variable;
}

to get variable that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>, the class name must come first, and interfaces follow. And of course you can only list a single class.

JSLint is suddenly reporting: Use the function form of "use strict"

This is how simple it is: If you want to be strict with all your code, add "use strict"; at the start of your JavaScript.

But if you only want to be strict with some of your code, use the function form. Anyhow, I would recomend you to use it at the beginning of your JavaScript because this will help you be a better coder.

SQL Server - after insert trigger - update another column in the same table

It depends on the recursion level for triggers currently set on the DB.

If you do this:

SP_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO

Or this:

ALTER DATABASE db_name
SET RECURSIVE_TRIGGERS OFF

That trigger above won't be called again, and you would be safe (unless you get into some kind of deadlock; that could be possible but maybe I'm wrong).

Still, I do not think this is a good idea. A better option would be using an INSTEAD OF trigger. That way you would avoid executing the first (manual) update over the DB. Only the one defined inside the trigger would be executed.

An INSTEAD OF INSERT trigger would be like this:

CREATE TRIGGER setDescToUpper ON part_numbers
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO part_numbers (
        colA,
        colB,
        part_description
    ) SELECT
        colA,
        colB,
        UPPER(part_description)
    ) FROM
        INSERTED
END
GO

This would automagically "replace" the original INSERT statement by this one, with an explicit UPPER call applied to the part_description field.

An INSTEAD OF UPDATE trigger would be similar (and I don't advise you to create a single trigger, keep them separated).

Also, this addresses @Martin comment: it works for multirow inserts/updates (your example does not).

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Limit file format when using <input type="file">?

Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension.

But still, the accept attribute of <input type = "file"> can help to provide a filter in the file select dialog box of the OS. For example,

_x000D_
_x000D_
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" />
_x000D_
_x000D_
_x000D_

should provide a way to filter out files other than .xls or .xlsx. Although the MDN page for input element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.

So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:

_x000D_
_x000D_
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
 accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> 
_x000D_
_x000D_
_x000D_

[Edge (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is All files (*).]

You can also use asterisks in MIME-types. For example:

_x000D_
_x000D_
<input type="file" accept="image/*" /> <!-- all image types --> 
<input type="file" accept="audio/*" /> <!-- all audio types --> 
<input type="file" accept="video/*" /> <!-- all video types --> 
_x000D_
_x000D_
_x000D_

W3C recommends authors to specify both MIME-types and corresponding extensions in the accept attribute. So, the best approach is:

_x000D_
_x000D_
<!-- Right approach: Use both file extensions and corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
 accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> 
_x000D_
_x000D_
_x000D_

JSFiddle of the same: here.

Reference: List of MIME-types

IMPORTANT: Using the accept attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be this), and definitely file types MUST be verified on the server, using a combination of MIME-type using both the file extension and its binary signature (ASP.NET, PHP, Ruby, Java). You might also want to refer to these tables for file types and their magic numbers, to perform a more robust server-side verification.

Here are three good reads on file-uploads and security.

EDIT: Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:

        $.ajax({
            type: "POST",
            crossdomain: true,
            url: "http://localhost:1415/anything",
            dataType: "json",
            data: JSON.stringify({
                anydata1: "any1",
                anydata2: "any2",
            }),
            success: function (result) {
                console.log(result)
            },
            error: function (xhr, status, err) {
                console.error(xhr, status, err);
            }
        });

with this headers on c# server:

                    if (request.HttpMethod == "OPTIONS")
                    {
                          response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                          response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                          response.AddHeader("Access-Control-Max-Age", "1728000");
                    }
                    response.AppendHeader("Access-Control-Allow-Origin", "*");

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

How to change font of UIButton with Swift

Take a look here.

You should set the font of the button's titleLabel instead.

myButton.titleLabel!.font = UIFont(name: "...", 10)

CSS hover vs. JavaScript mouseover

Why not both? Use jQuery for animated effects and CSS as the fallback. This gives you the benefits of jQuery with graceful degradation.

CSS:

a {color: blue;}
a:hover {color: red;}

jQuery (uses jQueryUI to animate color):

$('a').hover( 
  function() {
    $(this)
      .css('color','blue')
      .animate({'color': 'red'}, 400);
  },
  function() {
    $(this)
      .animate({'color': 'blue'}, 400);
  }
);

demo

SQL to find the number of distinct values in a column

SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;

you've got to count that distinct col, then give it an alias.

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

Regular expression for floating point numbers

[+/-] [0-9]*.[0-9]+

Try this solution.

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

How to lock orientation of one view controller to portrait mode only in Swift

Swift 3 & 4

Set the supportedInterfaceOrientations property of specific UIViewControllers like this:

class MyViewController: UIViewController {

    var orientations = UIInterfaceOrientationMask.portrait //or what orientation you want
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    get { return self.orientations }
    set { self.orientations = newValue }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //...
}

UPDATE

This solution only works when your viewController is not embedded in UINavigationController, because the orientation inherits from parent viewController.
For this case, you can create a subclass of UINavigationViewController and set these properties on it.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

For Chrome on Android, you can use the -webkit-tap-highlight-color CSS property:

-webkit-tap-highlight-color is a non-standard CSS property that sets the color of the highlight that appears over a link while it's being tapped. The highlighting indicates to the user that their tap is being successfully recognized, and indicates which element they're tapping on.

To remove the highlighting completely, you can set the value to transparent:

-webkit-tap-highlight-color: transparent;

Be aware that this might have consequences on accessibility: see outlinenone.com

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

Copying formula to the next row when inserting a new row

You need to insert the new row and then copy from the source row to the newly inserted row. Excel allows you to paste special just formulas. So in Excel:

  • Insert the new row
  • Copy the source row
  • Select the newly created target row, right click and paste special
  • Paste as formulas

VBA if required with Rows("1:1") being source and Rows("2:2") being target:

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Clear

Rows("1:1").Copy
Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

Iterating over a 2 dimensional python list

Use zip and itertools.chain. Something like:

>>> from itertools import chain
>>> l = chain.from_iterable(zip(*l))
<itertools.chain object at 0x104612610>
>>> list(l)
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

Read lines from a file into a Bash array

One alternate way if file contains strings without spaces with 1string each line:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

Check:

Print whole Array:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

Scroll / Jump to id without jQuery

on anchor tag use href and not onclick

<a href="#target1">asdf<a>

And div:

<div id="target1">some content</div>

Modifying Objects within stream in Java8 while iterating

The functional way would imho be:

import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateTestRun {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("a", "b", "c");
        System.out.println(lines); // [a, b, c]
        Predicate<? super String> predicate = value -> "b".equals(value);
        lines = lines.stream().filter(predicate.negate()).collect(toList());

        System.out.println(lines); // [a, c]
    }
}

In this solution the original list is not modified, but should contain your expected result in a new list that is accessible under the same variable as the old one

Remove URL parameters without refreshing page

Running this js for me cleared any params on the current url without refreshing the page.

window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);

Android dependency has different version for the compile and runtime

Replace a hard coded version to + example:

implementation 'com.google.android.gms:play-services-base:+'
implementation 'com.google.android.gms:play-services-maps:+'

Float and double datatype in Java

The Wikipedia page on it is a good place to start.

To sum up:

  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).

  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

There may be certain libraries that actually force your usage of float, but in general - unless you can guarantee that your result will be small enough to fit in float's prescribed range, then it's best to opt with double.

If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal, which can support an arbitrary amount of precision and handle situations like that elegantly.

count number of rows in a data frame in R based on group

Here is another way of using aggregate to count rows by group:

my.data <- read.table(text = '
    month.year    my.cov
      Jan.2000     apple
      Jan.2000      pear
      Jan.2000     peach
      Jan.2001     apple
      Jan.2001     peach
      Feb.2002      pear
', header = TRUE, stringsAsFactors = FALSE, na.strings = NA)

rows.per.group  <- aggregate(rep(1, length(my.data$month.year)),
                             by=list(my.data$month.year), sum)
rows.per.group

#    Group.1 x
# 1 Feb.2002 1
# 2 Jan.2000 3
# 3 Jan.2001 2

Difference between a SOAP message and a WSDL?

We need to define what is a web service before telling what are the difference between the SOAP and WSDL where the two (SOAP and WSDL) are components of a web service

Most applications are developed to interact with users, the user enters or searches for data through an interface and the application then responds to the user's input.

A Web service does more or less the same thing except that a Web service application communicates only from machine to machine or application to application. There is often no direct user interaction.

A Web service basically is a collection of open protocols that is used to exchange data between applications. The use of open protocols enables Web services to be platform independent. Software that are written in different programming languages and that run on different platforms can use Web services to exchange data over computer networks such as the Internet. In other words, Windows applications can talk to PHP, Java and Perl applications and many others, which in normal circumstances would not be possible.

How Do Web Services Work?

Because different applications are written in different programming languages, they often cannot communicate with each other. A Web service enables this communication by using a combination of open protocols and standards, chiefly XML, SOAP and WSDL. A Web service uses XML to tag data, SOAP to transfer a message and finally WSDL to describe the availability of services. Let's take a look at these three main components of a Web service application.

Simple Object Access Protocol (SOAP)

The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages between applications without confronting interoperability issues (interoperability meaning the platform that a Web service is running on becomes irrelevant). Another protocol that has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP ensures that you do not have to worry about what kind of Web server -- whether Apache or IIS or any other -- serves you the pages you are viewing or whether the pages you view were created in ASP.NET or HTML.

Because SOAP is used both for requesting and responding, its contents vary slightly depending on its purpose.

Below is an example of a SOAP request and response message

SOAP Request:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPrice> 
    <m:BookName>The Fleamarket</m:BookName> 
    </m:GetBookPrice> 
</soap:Body> 
</soap:Envelope>

SOAP Response:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPriceResponse> 
    <m: Price>10.95</m: Price> 
    </m:GetBookPriceResponse> 
</soap:Body> 
</soap:Envelope> 

Although both messages look the same, they carry out different methods. For instance looking at the above examples you can see that the requesting message uses the GetBookPrice method to get the book price. The response is carried out by the GetBookPriceResponse method, which is going to be the message that you as the "requestor" will see. You can also see that the messages are composed using XML.

Web Services Description Language or WSDL

WSDL is a document that describes a Web service and also tells you how to access and use its methods.

WSDL takes care of how do you know what methods are available in a Web service that you stumble across on the Internet.

Take a look at a sample WSDL file:

<?xml version="1.0" encoding="UTF-8"?> 
<definitions  name ="DayOfWeek"  
  targetNamespace="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:tns="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"  
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://schemas.xmlsoap.org/wsdl/">  
  <message name="DayOfWeekInput"> 
    <part name="date" type="xsd:date"/> 
  </message> 
  <message name="DayOfWeekResponse"> 
    <part name="dayOfWeek" type="xsd:string"/> 
  </message> 
  <portType name="DayOfWeekPortType"> 
    <operation name="GetDayOfWeek"> 
      <input message="tns:DayOfWeekInput"/> 
      <output message="tns:DayOfWeekResponse"/> 
    </operation> 
  </portType> 
  <binding name="DayOfWeekBinding" type="tns:DayOfWeekPortType"> 
    <soap:binding style="document"  
      transport="http://schemas.xmlsoap.org/soap/http"/> 
    <operation name="GetDayOfWeek"> 
      <soap:operation soapAction="getdayofweek"/> 
      <input> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"  
          encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </input> 
      <output> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"   
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </output> 
    </operation> 
  </binding> 
  <service name="DayOfWeekService" > 
    <documentation> 
      Returns the day-of-week name for a given date 
    </documentation> 
    <port name="DayOfWeekPort" binding="tns:DayOfWeekBinding"> 
      <soap:address location="http://localhost:8090/dayofweek/DayOfWeek"/> 
    </port> 
  </service> 
</definitions> 

The main things to remember about a WSDL file are that it provides you with:

  • A description of a Web service

  • The methods a Web service uses and the parameters that it takes

  • A way to locate Web services

  • How to solve static declaration follows non-static declaration in GCC C code?

    You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

    void inlet_update_my_ratio(object_t *myobject);
    //some where the implementation is like this
    static void inlet_update_my_ratio(object_t *myobject) {
    //code
    }
    

    If you remove the static from the implementation, the error will go away as below.

     void inlet_update_my_ratio(object_t *myobject) {
        //code
        }
    

    ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

    Right click on your folder on your server or local machine and give full permissions to

    IIS_IUSRS

    that's it.

    Get only the Date part of DateTime in mssql

    Another nifty way is:

    DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
    

    Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.

    Edit - other date calculations:

    First Day of Month:

    DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
    

    First Day of the Year:

    DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
    

    First Day of the Quarter:

    DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
    

    Last Day of Prior Month:

    DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
    

    Last Day of Current Month:

    DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
    

    Last Day of Current Year:

    DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
    

    First Monday of the Month:

    DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)        
    

    Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.

    Does VBA have Dictionary Structure?

    VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.

    Dim d
    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "aaa"
    d.Add "b", "bbb"
    d.Add "c", "ccc"
    
    If d.Exists("c") Then
        MsgBox d("c")
    End If
    

    Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

    This works great for large tables.

    SELECT NUM_ROWS FROM ALL_TABLES WHERE TABLE_NAME = 'TABLE_NAME_IN_UPPERCASE';
    

    For small to medium size tables, following will be ok.

    SELECT COUNT(Primary_Key) FROM table_name;
    

    Cheers,

    get the value of "onclick" with jQuery?

    i have never done this, but it would be done like this:

    var script = $('#google').attr("onclick")
    

    How to convert int to QString?

    Moreover to convert whatever you want, you can use QVariant. For an int to a QString you get:

    QVariant(3).toString();
    

    A float to a string or a string to a float:

    QVariant(3.2).toString();
    QVariant("5.2").toFloat();
    

    How do I fetch lines before/after the grep result in bash?

    The way to do this is near the top of the man page

    grep -i -A 10 'error data'
    

    How long to brute force a salted SHA-512 hash? (salt provided)

    There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

    The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

    To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

    As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

    One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

    How do I send a file as an email attachment using Linux command line?

    I use SendEmail, which was created for this scenario. It's packaged for Ubuntu so I assume it's available

    sendemail -f [email protected] -t [email protected] -m "Here are your files!" -a file1.jpg file2.zip

    http://caspian.dotconf.net/menu/Software/SendEmail/

    Reading numbers from a text file into an array in C

    There are two problems in your code:

    • the return value of scanf must be checked
    • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

    The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

    The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        int i, j;
        short unsigned digitArray[16];
        i = 0;
        while (
            i != sizeof(digitArray) / sizeof(digitArray[0])
         && 1 == scanf("%1hu", digitArray + i)
        ) {
            i++;
        }
        for (j = 0; j != i; j++) {
            printf("%hu\n", digitArray[j]);
        }
        return 0;
    }
    

    How do I convert a list into a string with spaces in Python?

    you can iterate through it to do it

    my_list = ['how', 'are', 'you']
    my_string = " "
    for a in my_list:
        my_string = my_string + ' ' + a
    print(my_string)
    

    output is

     how are you
    

    you can strip it to get

    how are you
    

    like this

    my_list = ['how', 'are', 'you']
    my_string = " "
    for a in my_list:
        my_string = my_string + ' ' + a
    print(my_string.strip())
    
    

    Flatten nested dictionaries, compressing keys

    There are two big considerations that the original poster needs to consider:

    1. Are there keyspace clobbering issues? For example, {'a_b':{'c':1}, 'a':{'b_c':2}} would result in {'a_b_c':???}. The below solution evades the problem by returning an iterable of pairs.
    2. If performance is an issue, does the key-reducer function (which I hereby refer to as 'join') require access to the entire key-path, or can it just do O(1) work at every node in the tree? If you want to be able to say joinedKey = '_'.join(*keys), that will cost you O(N^2) running time. However if you're willing to say nextKey = previousKey+'_'+thisKey, that gets you O(N) time. The solution below lets you do both (since you could merely concatenate all the keys, then postprocess them).

    (Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or anything equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key a then a_1 then a_1_i..., and then calculating a then a_1 then a_1_ii..., but really you shouldn't have to calculate a_1 again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on {1:{1:{1:{1:...(N times)...{1:SOME_LARGE_DICTIONARY_OF_SIZE_N}...}}}})

    Below is a function I wrote flattenDict(d, join=..., lift=...) which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one).

    from collections import Mapping
    from itertools import chain
    from operator import add
    
    _FLAG_FIRST = object()
    
    def flattenDict(d, join=add, lift=lambda x:x):
        results = []
        def visit(subdict, results, partialKey):
            for k,v in subdict.items():
                newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k))
                if isinstance(v,Mapping):
                    visit(v, results, newKey)
                else:
                    results.append((newKey,v))
        visit(d, results, _FLAG_FIRST)
        return results
    

    To better understand what's going on, below is a diagram for those unfamiliar with reduce(left), otherwise known as "fold left". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here, J is our join function. We preprocess each kn with lift(k).

                   [k0,k1,...,kN].foldleft(J)
                               /    \
                             ...    kN
                             /
           J(k0,J(k1,J(k2,k3)))
                           /  \
                          /    \
               J(J(k0,k1),k2)   k3
                        /   \
                       /     \
                 J(k0,k1)    k2
                     /  \
                    /    \
                   k0     k1
    

    This is in fact the same as functools.reduce, but where our function does this to all key-paths of the tree.

    >>> reduce(lambda a,b:(a,b), range(5))
    ((((0, 1), 2), 3), 4)
    

    Demonstration (which I'd otherwise put in docstring):

    >>> testData = {
            'a':1,
            'b':2,
            'c':{
                'aa':11,
                'bb':22,
                'cc':{
                    'aaa':111
                }
            }
        }
    from pprint import pprint as pp
    
    >>> pp(dict( flattenDict(testData, lift=lambda x:(x,)) ))
    {('a',): 1,
     ('b',): 2,
     ('c', 'aa'): 11,
     ('c', 'bb'): 22,
     ('c', 'cc', 'aaa'): 111}
    
    >>> pp(dict( flattenDict(testData, join=lambda a,b:a+'_'+b) ))
    {'a': 1, 'b': 2, 'c_aa': 11, 'c_bb': 22, 'c_cc_aaa': 111}    
    
    >>> pp(dict( (v,k) for k,v in flattenDict(testData, lift=hash, join=lambda a,b:hash((a,b))) ))
    {1: 12416037344,
     2: 12544037731,
     11: 5470935132935744593,
     22: 4885734186131977315,
     111: 3461911260025554326}
    

    Performance:

    from functools import reduce
    def makeEvilDict(n):
        return reduce(lambda acc,x:{x:acc}, [{i:0 for i in range(n)}]+range(n))
    
    import timeit
    def time(runnable):
        t0 = timeit.default_timer()
        _ = runnable()
        t1 = timeit.default_timer()
        print('took {:.2f} seconds'.format(t1-t0))
    
    >>> pp(makeEvilDict(8))
    {7: {6: {5: {4: {3: {2: {1: {0: {0: 0,
                                     1: 0,
                                     2: 0,
                                     3: 0,
                                     4: 0,
                                     5: 0,
                                     6: 0,
                                     7: 0}}}}}}}}}
    
    import sys
    sys.setrecursionlimit(1000000)
    
    forget = lambda a,b:''
    
    >>> time(lambda: dict(flattenDict(makeEvilDict(10000), join=forget)) )
    took 0.10 seconds
    >>> time(lambda: dict(flattenDict(makeEvilDict(100000), join=forget)) )
    [1]    12569 segmentation fault  python
    

    ... sigh, don't think that one is my fault...


    [unimportant historical note due to moderation issues]

    Regarding the alleged duplicate of Flatten a dictionary of dictionaries (2 levels deep) of lists in Python:

    That question's solution can be implemented in terms of this one by doing sorted( sum(flatten(...),[]) ). The reverse is not possible: while it is true that the values of flatten(...) can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.)

    Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

    you could try

    $('*').not('#div').bind('touchmove', false);
    

    add this if necessary

    $('#div').bind('touchmove');
    

    note that everything is fixed except #div

    HTML.ActionLink method

    If you want to go all fancy-pants, here's how you can extend it to be able to do this:

    @(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))
    

    You will need to put this in the System.Web.Mvc namespace:

    public static class MyProjectExtensions
    {
        public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
    
            var link = new TagBuilder("a");
    
            string actionName = ExpressionHelper.GetExpressionText(expression);
            string controllerName = typeof(TController).Name.Replace("Controller", "");
    
            link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
            link.SetInnerText(linkText);
    
            return new MvcHtmlString(link.ToString());
        }
    
        public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
    
            var link = new TagBuilder("a");
    
            string actionName = ExpressionHelper.GetExpressionText(expression);
            string controllerName = typeof(TController).Name.Replace("Controller", "");
    
            link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
            link.SetInnerText(linkText);
    
            return new MvcHtmlString(link.ToString());
        }
    
        public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
    
            var attributes = AnonymousObjectToKeyValue(htmlAttributes);
    
            var link = new TagBuilder("a");
    
            string actionName = ExpressionHelper.GetExpressionText(expression);
            string controllerName = typeof(TController).Name.Replace("Controller", "");
    
            link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
            link.MergeAttributes(attributes, true);
            link.SetInnerText(linkText);
    
            return new MvcHtmlString(link.ToString());
        }
    
        private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
        {
            var dictionary = new Dictionary<string, object>();
    
            if (anonymousObject == null) return dictionary;
    
            foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
            {
                dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
            }
    
            return dictionary;
        }
    }
    

    This includes two overrides for Route Values and HTML Attributes, also, all of your views would need to add: @using YourProject.Controllers or you can add it to your web.config <pages><namespaces>

    how to execute php code within javascript

    If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:

    <button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
    <div id="resultMsg"></div>
    <script type="text/javascript">
    function funk(){
      alert("asdasd");
      document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
    }
    </script>
    

    However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:

    <button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
    <div id="resultMsg"></div>
    <script type="text/javascript">
    function funk(){
      alert("asdasd");
      $('#resultMsg').load('path/to/php/script/order_item.php');
    }
    </script>
    

    This runs the php script and loads whatever message it returns into <div id="resultMsg">.

    order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:

    <?php
    // do adding to cart stuff here
    echo 'Added to cart';
    ?>
    

    For this to work you will need to include jQuery on your page, by adding this in your <head> tag:

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    

    Checkbox for nullable boolean

    I had a similar issue in the past.

    Create a Checkbox input in HTML, and set the attribute name="Foo" This should still post properly.

    <input type="checkbox" name="Foo" checked="@model.Foo.Value" /> Foo Checkbox<br />
    

    CSS width of a <span> tag

    Use the attribute 'display' as in the example:

    <span style="background: gray; width: 100px; display:block;">hello</span>
    <span style="background: gray; width: 200px; display:block;">world</span>
    

    Comma separated results in SQL

    If you're stuck with SQL Server <2017, you can use GroupConcat. The syntax and the performance is far better than the FOR XML PATH sollution.

    Installation:

    -- https://codeplexarchive.blob.core.windows.net/archive/projects/groupconcat/groupconcat.zip
    create assembly [GroupConcat] from 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C01030058898C510000000000000000E00002210B010B00001E000000080000000000007E3D0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000243D000057000000004000003804000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000841D000000200000001E000000020000000000000000000000000000200000602E7273726300000038040000004000000006000000200000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000002600000000000000000000000000004000004200000000000000000000000000000000603D0000000000004800000002000500C02C00006410000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003202731100000A7D010000042A0000001330040047000000010000110F01281200000A2D3D0F01281300000A0A027B01000004066F1400000A2C1A027B01000004250B06250C07086F1500000A17586F1600000A2A027B0100000406176F1700000A2A001B30050089000000020000110F017B010000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B01000004076F1400000A2C29027B01000004250D072513040911046F1500000A0F017B01000004076F1500000A586F1600000A2B19027B01000004070F017B01000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0000000110000002000D006D7A000E000000001B3003009B00000003000011027B010000043989000000027B010000046F1D00000A16317B731E00000A0A027B010000046F1800000A0D2B341203281900000A0B160C2B1E061201281A00000A6F1F00000A260672010000706F1F00000A260817580C081201282000000A32D81203281B00000A2DC3DE0E1203FE160300001B6F1C00000ADC06066F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A000110000002002B00416C000E00000000133003003900000004000011036F2500000A0A0206732600000A7D01000004160B2B1B027B01000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF2A0000001B3002005B0000000500001103027B010000046F1D00000A6F2800000A027B010000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0300000406282A00000A2C0702067D030000042A5E02731100000A7D02000004027E2B00000A7D030000042A133004004F000000010000110F01281200000A2D450F01281300000A0A027B02000004066F1400000A2C1B027B02000004250B06250C07086F1500000A17586F1600000A2B0D027B0200000406176F1700000A020428070000062A001B300500A300000002000011027B03000004282C00000A2C0D020F017B030000047D030000040F017B020000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B02000004076F1400000A2C29027B02000004250D072513040911046F1500000A0F017B02000004076F1500000A586F1600000A2B19027B02000004070F017B02000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0001100000020027006D94000E000000001B300300B300000003000011027B0200000439A1000000027B020000046F1D00000A163E90000000731E00000A0A027B020000046F1800000A0D2B351203281900000A0B160C2B1F061201281A00000A6F1F00000A2606027B030000046F1F00000A260817580C081201282000000A32D71203281B00000A2DC2DE0E1203FE160300001B6F1C00000ADC06066F2100000A027B030000046F2D00000A59027B030000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A000110000002002E004270000E00000000133003004500000004000011036F2500000A0A0206732600000A7D02000004160B2B1B027B02000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D030000042A0000001B300200670000000500001103027B020000046F1D00000A6F2800000A027B020000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B030000046F2900000A2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0500000406282A00000A2C0702067D050000042AEA027B060000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D060000042A7A02731100000A7D04000004027E2B00000A7D0500000402167D060000042A00001330040056000000010000110F01281200000A2D4C0F01281300000A0A027B04000004066F1400000A2C1B027B04000004250B06250C07086F1500000A17586F1600000A2B0D027B0400000406176F1700000A0204280E0000060205280F0000062A00001B300500B800000002000011027B05000004282C00000A2C0D020F017B050000047D05000004027B060000042D0D020F017B060000047D060000040F017B040000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B04000004076F1400000A2C29027B04000004250D072513040911046F1500000A0F017B04000004076F1500000A586F1600000A2B19027B04000004070F017B04000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0110000002003C006DA9000E000000001B300300D700000007000011027B0400000439C5000000027B040000046F1D00000A163EB4000000731E00000A0B027B06000004183313027B04000004731E000006733100000A0A2B0C027B04000004733200000A0A066F3300000A13042B351204283400000A0C160D2B1F071202281A00000A6F1F00000A2607027B050000046F1F00000A260917580D091202282000000A32D71204283500000A2DC2DE0E1204FE160600001B6F1C00000ADC07076F2100000A027B050000046F2D00000A59027B050000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A0001100000020052004294000E00000000133003005100000004000011036F2500000A0A0206732600000A7D04000004160B2B1B027B04000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D0500000402036F3600000A7D060000042A0000001B300200730000000500001103027B040000046F1D00000A6F2800000A027B040000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B050000046F2900000A03027B060000046F3700000A2A000110000002001D002F4C000E00000000EA027B080000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D080000042A4E02731100000A7D0700000402167D080000042A00133004004F000000010000110F01281200000A2D450F01281300000A0A027B07000004066F1400000A2C1B027B07000004250B06250C07086F1500000A17586F1600000A2B0D027B0700000406176F1700000A020428160000062A001B3005009E00000002000011027B080000042D0D020F017B080000047D080000040F017B070000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B07000004076F1400000A2C29027B07000004250D072513040911046F1500000A0F017B07000004076F1500000A586F1600000A2B19027B07000004070F017B07000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A000001100000020022006D8F000E000000001B300300C800000008000011027B0700000439B6000000027B070000046F1D00000A163EA5000000731E00000A0B027B08000004183313027B07000004731E000006733100000A0A2B0C027B07000004733200000A0A066F3300000A13052B3A1205283400000A0C1202281A00000A0D1613042B1A07096F1F00000A260772010000706F1F00000A2611041758130411041202282000000A32DB1205283500000A2DBDDE0E1205FE160600001B6F1C00000ADC07076F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A01100000020052004799000E00000000133003004500000004000011036F2500000A0A0206732600000A7D07000004160B2B1B027B07000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F3600000A7D080000042A0000001B300200670000000500001103027B070000046F1D00000A6F2800000A027B070000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B080000046F3700000A2A000110000002001D002F4C000E000000002204036F3800000A2A1E02283900000A2A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C000000C4060000237E0000300700006405000023537472696E677300000000940C00006C00000023555300000D0000100000002347554944000000100D00005403000023426C6F6200000000000000020000015717A2090900000000FA253300160000010000002500000006000000080000001E0000001E0000000500000039000000180000000800000003000000040000000400000006000000010000000300000000000A00010000000000060081007A000A00B20097000600C3007A000600E500CA000600F100CA000A001F010A0106004E0144010600600144010A009C010A010A00CA01970006001702050206002E02050206004B02050206006A02050206008302050206009C0205020600B70205020600D202050206000A03EB0206001E030502060057033703060077033703060095037A000A00AB0397000A00CC0397000600D303EB020600E903EB0217002B04000006004404CA00060070047A0006009A048E040600EB047A00060014057A0006001E057A000E002D05CA0006004005CA008F002B0400000000000001000000000001000100092110001A00270005000100010009211000330027000500020007000921100042002700050004000E00092110005200270005000700160001001000610027000D0009001D000100FE0010000100FE0010000100730139000100FE001000010073013900010095014F000100FE001000010095014F005020000000008600050118000100602000000000860029011C000100B4200000000086003401220002005C210000000086003A0128000300142200000000E6015B012D0004005C2200000000E6016D0133000500D4220000000081087D011C00060004230000000086000501180007001C2300000000860029013C000700782300000000860034014400090038240000000086003A0128000A00082500000000E6015B012D000B005C2500000000E6016D0133000C00E0250000000081087D011C000D001026000000008108A40152000E004B26000000008600050118000F006C26000000008600290158000F00D026000000008600340162001200A4270000000086003A0128001300982800000000E6015B012D001400F82800000000E6016D01330015008829000000008108A40152001600C329000000008600050118001700D82900000000860029016D001700342A000000008600340175001900F02A0000000086003A0128001A00D42B00000000E6015B012D001B00282C00000000E6016D0133001C00AC2C00000000E601B6017B001D00B52C000000008618BE0118001F0000000100C40100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200EC0100000100DC0100000000000000000100E20100000100E40100000100E60100000100E60100000100C40100000200EC0100000300F60100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200F60100000100DC0100000000000000000100E20100000100E40100000100010200000200030202000900030009000400090005000900060006005100BE0118005900BE01BA006100BE01BA006900BE01BA007100BE01BA007900BE01BA008100BE01BA008900BE01BA009100BE01BA009900BE01BF00A100BE01BA00A900BE01C400B100BE011800B900BE011800C100BE01C900D100BE0142011400BE0118003100F4034F013100FF035301140009045701140015045D0114001E0464011400270464011400360477011C005304890124005F049B011C0067044F01F1007C04180014008404B701F900BE011800F900A804BB012400FF03C101F900AF04B701F900BA04C6011900C10453013100CA04CD013900D604B7011400BE01C4003900E004530141006D01C40041006D01BA000101F204F9010101000539000101060503020101AF04B7014900FF0308020901BE01BA00110126050C022C00BE0119022C00BE012C022C0036043902340053048901340067044F0139004E05080241006D0167020101570587021900BE01180024000B0081002E006B0035032E002B000E032E0013008C022E001B009D022E0023000E032E003B0014032E0033008C022E0043000E032E0053000E032E0063002C0343007B00CF0063007B00CF0064000B00940083007B00CF00A3007B00CF00E4000B00810004010B00A70044010B009400E4010B00810004020B00A70064020B009400E4020B00810044030B0094006C01A001D301E501EA01FF014D026C0203000100040002000500040000008B014A0000008B014A000000AF0168000000AF01680001000700030001000E00050001000F0007000100160009000A004801820194011102450204800000010000000D13F49F00000000000027000000020000000000000000000000010071000000000002000000000000000000000001008B000000000002000000000000000000000001007A000000000000000000003C4D6F64756C653E0047726F7570436F6E6361742E646C6C0047524F55505F434F4E4341540047726F7570436F6E6361740047524F55505F434F4E4341545F440047524F55505F434F4E4341545F44530047524F55505F434F4E4341545F530052657665727365436F6D7061726572006D73636F726C69620053797374656D0056616C7565547970650053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E536572766572004942696E61727953657269616C697A65004F626A6563740053797374656D2E436F6C6C656374696F6E732E47656E657269630049436F6D706172657260310044696374696F6E61727960320076616C75657300496E69740053797374656D2E446174612E53716C54797065730053716C537472696E6700416363756D756C617465004D65726765005465726D696E6174650053797374656D2E494F0042696E61727952656164657200526561640042696E6172795772697465720057726974650064656C696D69746572007365745F44656C696D697465720044656C696D6974657200736F727442790053716C42797465007365745F536F7274427900536F7274427900436F6D70617265002E63746F720056414C55450053716C46616365744174747269627574650047726F7570007200770076616C75650044454C494D4954455200534F52545F4F52444552007800790053797374656D2E5265666C656374696F6E00417373656D626C795469746C6541747472696275746500417373656D626C794465736372697074696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E41747472696275746500417373656D626C79436F6D70616E7941747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C7954726164656D61726B41747472696275746500417373656D626C7943756C747572654174747269627574650053797374656D2E52756E74696D652E496E7465726F70536572766963657300436F6D56697369626C6541747472696275746500417373656D626C7956657273696F6E4174747269627574650053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053657269616C697A61626C654174747269627574650053716C55736572446566696E656441676772656761746541747472696275746500466F726D6174005374727563744C61796F7574417474726962757465004C61796F75744B696E64006765745F49734E756C6C006765745F56616C756500436F6E7461696E734B6579006765745F4974656D007365745F4974656D0041646400456E756D657261746F7200476574456E756D657261746F72004B657956616C7565506169726032006765745F43757272656E74006765745F4B6579004D6F76654E6578740049446973706F7361626C6500446973706F7365006765745F436F756E740053797374656D2E5465787400537472696E674275696C64657200417070656E64006765745F4C656E6774680052656D6F766500546F537472696E67006F705F496D706C696369740052656164496E7433320052656164537472696E6700537472696E67006F705F496E657175616C69747900456D7074790049734E756C6C4F72456D70747900457863657074696F6E00436F6E7665727400546F4279746500536F7274656444696374696F6E6172796032004944696374696F6E617279603200526561644279746500436F6D70617265546F0000000000032C00006549006E00760061006C0069006400200053006F0072007400420079002000760061006C00750065003A00200075007300650020003100200066006F007200200041005300430020006F00720020003200200066006F007200200044004500530043002E0000008002D97266C26949A672EA780F71C8980008B77A5C561934E08905151211010E0706151215020E0803200001052001011119052001011108042000111905200101121D05200101122102060E072002011119111905200101110C04280011190206050520010111250920030111191119112505200101111004280011250720020111191125052001011114052002080E0E12010001005408074D617853697A65A00F000012010001005408074D617853697A65FFFFFFFF12010001005408074D617853697A6504000000042001010E0420010102042001010805200101116572010002000000050054080B4D61784279746553697A65FFFFFFFF5402124973496E76617269616E74546F4E756C6C73015402174973496E76617269616E74546F4475706C696361746573005402124973496E76617269616E74546F4F726465720154020D49734E756C6C4966456D7074790105200101116D06151215020E08032000020320000E0520010213000620011301130007200201130013010A07030E151215020E080E0A2000151171021300130106151171020E080A2000151175021300130106151175020E080420001300160705151175020E080E151171020E08151215020E080E03200008052001127D0E0420001301062002127D080805000111190E110704127D151175020E0808151171020E0804070208080E0702151175020E08151171020E08050002020E0E0307010E040001020E032000050400010505071512808D020E08122002011512809102130013011512110113000C2001011512809102130013010B20001511809502130013010715118095020E081907051512808D020E08127D151175020E080815118095020E0804200101051A07061512808D020E08127D151175020E080E0815118095020E08042001080E1001000B47726F7570436F6E63617400007001006B537472696E6720636F6E636174656E6174696F6E2061676772656761746520666F722053514C205365727665722E2044726F702D696E207265706C6163656D656E7420666F72206275696C742D696E204D7953514C2047524F55505F434F4E4341542066756E74696F6E2E000005010000000017010012436F7079726967687420C2A920203230313100000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773014C3D000000000000000000006E3D0000002000000000000000000000000000000000000000000000603D00000000000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000E00300000000000000000000E00334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE0000010000000100F49F0D1300000100F49F0D133F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B00440030000010053007400720069006E006700460069006C00650049006E0066006F0000001C0300000100300030003000300030003400620030000000F0006C00010043006F006D006D0065006E0074007300000053007400720069006E006700200063006F006E0063006100740065006E006100740069006F006E002000610067006700720065006700610074006500200066006F0072002000530051004C0020005300650072007600650072002E002000440072006F0070002D0069006E0020007200650070006C006100630065006D0065006E007400200066006F00720020006200750069006C0074002D0069006E0020004D007900530051004C002000470052004F00550050005F0043004F004E004300410054002000660075006E00740069006F006E002E00000040000C000100460069006C0065004400650073006300720069007000740069006F006E0000000000470072006F007500700043006F006E00630061007400000040000F000100460069006C006500560065007200730069006F006E000000000031002E0030002E0034003800370037002E00340030003900340038000000000040001000010049006E007400650072006E0061006C004E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C0000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003100310000004800100001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C00000038000C000100500072006F0064007500630074004E0061006D00650000000000470072006F007500700043006F006E00630061007400000044000F000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0034003800370037002E00340030003900340038000000000048000F00010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0034003800370037002E003400300039003400380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000803D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 with permission_set = safe;
    create aggregate [dbo].[GROUP_CONCAT]    (@VALUE [nvarchar](4000))                                                      returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT];
    create aggregate [dbo].[GROUP_CONCAT_D]  (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4))                            returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_D];
    create aggregate [dbo].[GROUP_CONCAT_DS] (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4), @SORT_ORDER [tinyint])     returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_DS];
    create aggregate [dbo].[GROUP_CONCAT_S]  (@VALUE [nvarchar](4000), @SORT_ORDER [tinyint])                               returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_S];
    
    go
    

    Usage:

    declare @liststr varchar(max)
    select @liststr = dbo.group_concat_d(institutionname, ',')
    from education
    where studentnumber = '111'
    group by studentnumber;
    select @liststr
    

    GroupConcat does not support ordering, though. You could use PIVOT, CTE's and windows functions if you need ordering:

    drop table if exists #students;
    create table #students (
        name        varchar(20),
        institution varchar(20),
        year        int -- order by year
    )
    go
    
    insert into #students(name, institution, year)
    values
        ('Simon', 'INSTITUTION1', 2005),
        ('Simon', 'INSTITUTION2', 2008);
    
    with cte as (
        select name,
               institution,
               rn = row_number() over (partition by name order by year)
        from #students
    )
    select name,
           [1] +
           isnull((',' + [2]), '') +
           isnull((',' + [3]), '') +
           isnull((',' + [4]), '') +
           isnull((',' + [5]), '') +
           isnull((',' + [6]), '') +
           isnull((',' + [7]), '') +
           isnull((',' + [8]), '') +
           isnull((',' + [9]), '') +
           isnull((',' + [10]), '') +
           isnull((',' + [11]), '') +
           isnull((',' + [12]), '') +
           isnull((',' + [13]), '') +
           isnull((',' + [14]), '') +
           isnull((',' + [15]), '') +
           isnull((',' + [16]), '') +
           isnull((',' + [17]), '') +
           isnull((',' + [18]), '') +
           isnull((',' + [19]), '') +
           isnull((',' + [20]), '')
    from cte
        pivot (
        max(institution)
        for rn in ([1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20])
        ) as piv
    

    Could not resolve this reference. Could not locate the assembly

    You most likely get this message when the project points to an old location of the assembly where it no longer exists. Since you were able to build it once, the assembly has already been copied into your bin\Debug / bin\Release folders so your project can still find a copy.

    If you open the references node of the project in your solution explorer, there should be a yellow icon next to the reference. Remove the reference and add it again from the correct location.

    If you want to know the location it was referenced from, you'd have to open the .csproj file in a text editor and look for the HintPath for that assembly - the IDE for some reason does not show this information.

    Clear data in MySQL table with PHP?

    TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

    we can use for truncate

    TRUNCATE TABLE tablename
    

    we can use for delete

    DELETE FROM tablename
    

    we can also give conditions as below

    DELETE FROM tablename WHERE id='xyz'

    Domain Account keeping locking out with correct password every few minutes

    I think this highlights a serious deficiency in Windows. We have a (techincal) user account that we use for our system consisting of a windows service and websites, with the app pools configured to run as this user.

    Our company has a security policy that after 5 bad passwords, it locks the account out.

    Now finding out what locks out the account is practically impossible in a enterprise. When the account is locked out, the AD server should log from what process and what server caused the lock out.

    I've looked into it and it (lock out tools) and it doesnt do this. only possible thing is a tool but you have to run it on the server and wait to see if any process is doing it. But in a enterprise with 1000s of servers thats impossible, you have to guess. Its crazy.

    Looping over elements in jQuery

    I have used the following before:

    var my_form = $('#form-id');
    var data = {};
    
    $('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
        function() {
            var name = $(this).attr('name');
            var val = $(this).val();
    
            if (!data.hasOwnProperty(name)) {
                data[name] = new Array;
            }
    
            data[name].push(val);
        }
    );
    

    This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

    Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

    Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).

    How can I prevent a window from being resized with tkinter?

    You could use:

    parentWindow.maxsize(#,#);
    parentWindow.minsize(x,x);
    

    At the bottom of your code to set the fixed window size.

    How do you validate a URL with a regular expression in Python?

    Nowadays, in 90% of case if you working with URL in Python you probably use python-requests. Hence the question here - why not reuse URL validation from requests?

    from requests.models import PreparedRequest
    import requests.exceptions
    
    
    def check_url(url):
        prepared_request = PreparedRequest()
        try:
            prepared_request.prepare_url(url, None)
            return prepared_request.url
        except requests.exceptions.MissingSchema, e:
            raise SomeException
    

    Features:

    • Don't reinvent the wheel
    • DRY
    • Work offline
    • Minimal resource

    How to use [DllImport("")] in C#?

    You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

    using System.Runtime.InteropServices;
    
    
    public class WindowHandling
    {
        [DllImport("User32.dll")]
        public static extern int SetForegroundWindow(IntPtr point);
    
        public void ActivateTargetApplication(string processName, List<string> barcodesList)
        {
            Process p = Process.Start("notepad++.exe");
            p.WaitForInputIdle();
            IntPtr h = p.MainWindowHandle;
            SetForegroundWindow(h);
            SendKeys.SendWait("k");
            IntPtr processFoundWindow = p.MainWindowHandle;
        }
    }
    

    How to upsert (update or insert) in SQL Server 2005

    You can check if the row exists, and then INSERT or UPDATE, but this guarantees you will be performing two SQL operations instead of one:

    1. check if row exists
    2. insert or update row

    A better solution is to always UPDATE first, and if no rows were updated, then do an INSERT, like so:

    update table1 
    set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
    where id = 'val1'
    
    if @@ROWCOUNT = 0
      insert into table1(id, name, itemname, itemcatName, itemQty)
      values('val1', 'val2', 'val3', 'val4', 'val5')
    

    This will either take one SQL operations, or two SQL operations, depending on whether the row already exists.

    But if performance is really an issue, then you need to figure out if the operations are more likely to be INSERT's or UPDATE's. If UPDATE's are more common, do the above. If INSERT's are more common, you can do that in reverse, but you have to add error handling.

    BEGIN TRY
      insert into table1(id, name, itemname, itemcatName, itemQty)
      values('val1', 'val2', 'val3', 'val4', 'val5')
    END TRY
    BEGIN CATCH
      update table1 
      set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
      where id = 'val1'
    END CATCH
    

    To be really certain if you need to do an UPDATE or INSERT, you have to do two operations within a single TRANSACTION. Theoretically, right after the first UPDATE or INSERT (or even the EXISTS check), but before the next INSERT/UPDATE statement, the database could have changed, causing the second statement to fail anyway. This is exceedingly rare, and the overhead for transactions may not be worth it.

    Alternately, you can use a single SQL operation called MERGE to perform either an INSERT or an UPDATE, but that's also probably overkill for this one-row operation.

    Consider reading about SQL transaction statements, race conditions, SQL MERGE statement.

    How to find children of nodes using BeautifulSoup

    try this:

    li = soup.find("li", { "class" : "test" })
    children = li.find_all("a") # returns a list of all <a> children of li
    

    other reminders:

    The find method only gets the first occurring child element. The find_all method gets all descendant elements and are stored in a list.

    CORS: credentials mode is 'include'

    Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

    On the Angular side required adding option flag withCredentials: true for Cookie transport:

    constructor(public http: HttpClient) {
    }
    
    public get(url: string = ''): Observable<any> {
        return this.http.get(url, { withCredentials: true });
    }
    

    On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            // This Origin header you can see that in Network tab
            configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
            configuration.setAllowedMethods(Arrays.asList("GET","POST"));
            configuration.setAllowedHeaders(Arrays.asList("content-type"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()...
        }
    }
    

    Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

    Using $window or $location to Redirect in AngularJS

    I believe the way to do this is $location.url('/RouteTo/Login');

    Edit for Clarity

    Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

    For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

    window.location = "http://www.my-domain.com/login"
    

    How to remove "disabled" attribute using jQuery?

    2018, without JQuery

    I know the question is about JQuery: this answer is just FYI.

    document.getElementById('edit').addEventListener(event => {
        event.preventDefault();
        [...document.querySelectorAll('.inputDisabled')].map(e => e.disabled = false);
    }); 
    

    Ruby on Rails: Clear a cached page

    Check for a static version of your page in /public and delete it if it's there. When Rails 3.x caches pages, it leaves a static version in your public folder and loads that when users hit your site. This will remain even after you clear your cache.

    Using curl to upload POST data with files

    Here is my solution, I have been reading a lot of posts and they were really helpful. Finally I wrote some code for small files, with cURL and PHP that I think its really useful.

    public function postFile()
    {    
            $file_url = "test.txt";  //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
            $eol = "\r\n"; //default line-break for mime type
            $BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
            $BODY=""; //init my curl body
            $BODY.= '--'.$BOUNDARY. $eol; //start param header
            $BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
            $BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
            $BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
            $BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
            $BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
            $BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
            $BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
            $BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
    
    
    
            $ch = curl_init(); //init curl
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                             'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
                             ,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
                        );
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
            curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
            curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
            curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
            curl_setopt($ch, CURLOPT_POST, true); //set as post
            curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY 
    
    
            $response = curl_exec($ch); // start curl navigation
    
         print_r($response); //print response
    
    }
    

    With this we should be get on the "api.endpoint.post" the following vars posted. You can easily test with this script, and you should be receive this debugs on the function postFile() at the last row.

    print_r($response); //print response
    
    public function getPostFile()
    {
    
        echo "\n\n_SERVER\n";
        echo "<pre>";
        print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
        echo "/<pre>";
        echo "_POST\n";
        echo "<pre>";
        print_r($_POST['sometext']);
        echo "/<pre>";
        echo "_FILES\n";
        echo "<pre>";
        print_r($_FILEST['somefile']);
        echo "/<pre>";
    }
    

    It should work well, they may be better solutions but this works and is really helpful to understand how the Boundary and multipart/from-data mime works on PHP and cURL library.

    Use sed to replace all backslashes with forward slashes

    If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

    $ p='C:\foo\bar.xml'
    $ printf '%s\n' "$p"
    C:\foo\bar.xml
    $ printf '%s\n' "${p//\\//}"
    C:/foo/bar.xml
    

    This may be leaner and clearer that filtering through a command such as tr or sed.

    how to start the tomcat server in linux?

    I know this is old question, but this command helped me!

    Go to your Tomcat Directory
    Just type this command in your terminal:

    ./catalina.sh start
    

    Rounding BigDecimal to *always* have two decimal places

    value = value.setScale(2, RoundingMode.CEILING)
    

    Iterating through a string word by word

    s = 'hi how are you'
    l = list(map(lambda x: x,s.split()))
    print(l)
    

    Output: ['hi', 'how', 'are', 'you']

    setting system property

    System.setProperty("gate.home", "/some/directory");
    

    For more information, see:

    How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

    I usually use some #define and constants to make the calculation easy:

    #define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds
    const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;
    

    Hence my code would look like this:

    timespec sleepValue = {0};
    
    sleepValue.tv_nsec = INTERVAL_MS;
    nanosleep(&sleepValue, NULL);
    

    Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

    just pass the date time to this func. it would print out in time ago format for you

    date_default_timezone_set('your-time-zone');
    function convert($datetime){
      $time=strtotime($datetime);
      $diff=time()-$time;
      $diff/=60;
      $var1=floor($diff);
      $var=$var1<=1 ? 'min' : 'mins';
      if($diff>=60){
        $diff/=60;
        $var1=floor($diff);
        $var=$var1<=1 ? 'hr' : 'hrs';
        if($diff>=24){$diff/=24;$var1=floor($diff);$var=$var1<=1 ? 'day' : 'days';
        if($diff>=30.4375){$diff/=30.4375;$var1=floor($diff);$var=$var1<=1 ? 'month' : 'months';
        if($diff>=12){$diff/=12;$var1=floor($diff);$var=$var1<=1 ? 'year' : 'years';}}}}
        echo $var1,' ',$var,' ago';
      }
    

    python filter list of dictionaries based on key value

    You can try a list comp

    >>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
    >>> keyValList = ['type2','type3']
    >>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
    >>> expectedResult
    [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
    

    Another way is by using filter

    >>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
    [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
    

    Does VBA contain a comment block syntax?

    There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

    What are the correct version numbers for C#?

    The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

    The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

    Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

    How to convert an NSTimeInterval (seconds) into minutes

    Forgive me for being a Stack virgin... I'm not sure how to reply to Brian Ramsay's answer...

    Using round will not work for second values between 59.5 and 59.99999. The second value will be 60 during this period. Use trunc instead...

     double progress;
    
     int minutes = floor(progress/60);
     int seconds = trunc(progress - minutes * 60);
    

    Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

    now you can use the last 1.0.0-rc1 this way :

    classpath 'com.android.tools.build:gradle:1.0.0-rc1'
    

    This needs Gradle 2.0 if you don't have it Android Studio will ask you to download it

    How do I run a Python program?

    You can just call

    python /path/to/filename.py
    

    How to install requests module in Python 3.4, instead of 2.7

    On Windows with Python v3.6.5

    py -m pip install requests
    

    Generating a list of pages (not posts) without the index file

    I can offer you a jquery solution

    add this in your <head></head> tag

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

    add this after </ul>

     <script> $('ul li:first').remove(); </script> 

    How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

    For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

    import pandas as pd
    import dask.dataframe as dd
    pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works
    
    train_data = dd.read_csv('./data/train.csv')    
    train_data.head(5)
    

    Jquery button click() function is not working

    You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

    $("#buildyourform").on('click', "#add", function() {
        // your code...
    });
    

    Also, you can make your HTML strings easier to read by mixing line quotes:

    var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');
    

    Or even supplying the attributes as an object:

    var fieldWrapper = $('<div></div>', { 
        'class': 'fieldwrapper',
        'name': 'field' + intId,
        'id': 'field' + intId
    });
    

    Binding an enum to a WinForms combo box, and then setting it

    The code

    comboBox1.SelectedItem = MyEnum.Something;
    

    is ok, the problem must reside in the DataBinding. DataBinding assignments occur after the constructor, mainly the first time the combobox is shown. Try to set the value in the Load event. For example, add this code:

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        comboBox1.SelectedItem = MyEnum.Something;
    }
    

    And check if it works.

    Convert integer to hexadecimal and back again

    int to hex:

    int a = 72;

    Console.WriteLine("{0:X}", a);

    hex to int:

    int b = 0xB76;

    Console.WriteLine(b);

    struct.error: unpack requires a string argument of length 4

    The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

    struct {                   11
        char a;      012345678901
        short b;     ------------
        char c;      axbbcxxxdddd
        int d;
    };
    

    This structure will occupy 12 bytes of memory (x being pad bytes).

    Python works similarly (see the struct documentation):

    >>> import struct
    >>> struct.pack('BHBL',1,2,3,4)
    '\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
    >>> struct.calcsize('BHBL')
    12
    

    Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

    >>> struct.calcsize('=BHBL')
    8
    >>> struct.pack('=BHBL',1,2,3,4)
    '\x01\x02\x00\x03\x04\x00\x00\x00'
    

    Beware of letting struct handle padding. In C, these structures:

    struct A {       struct B {
        short a;         int a;
        char b;          char b;
    };               };
    

    are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

    >>> struct.pack('LB',1,2)
    '\x01\x00\x00\x00\x02'
    >>> struct.pack('LBLB',1,2,3,4)
    '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
    

    How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

    I have written a string extension for replacement of 'String: subString:'

    extension String {
        
        func sliceByCharacter(from: Character, to: Character) -> String? {
            let fromIndex = self.index(self.index(of: from)!, offsetBy: 1)
            let toIndex = self.index(self.index(of: to)!, offsetBy: -1)
            return String(self[fromIndex...toIndex])
        }
        
        func sliceByString(from:String, to:String) -> String? {
            //From - startIndex
            var range = self.range(of: from)
            let subString = String(self[range!.upperBound...])
            
            //To - endIndex
            range = subString.range(of: to)
            return String(subString[..<range!.lowerBound])
        }
        
    }
    

    Usage : "Date(1511508780012+0530)".sliceByString(from: "(", to: "+")

    Example Result : "1511508780012"

    PS: Optionals are forced to unwrap. Please add Type safety check wherever necessary.

    How do I recognize "#VALUE!" in Excel spreadsheets?

    Use IFERROR(value, value_if_error)

    How do I install Python libraries in wheel format?

    Have you checked this http://docs.python.org/2/install/ ?

    1. First you have to install the module

      $ pip install requests

    2. Then, before using it you must import it from your program.

      from requests import requests

      Note that your modules must be in the same directory.

    3. Then you can use it.

      For this part you have to check for the documentation.

    PDF Editing in PHP?

    Tcpdf is also a good liabrary for generating pdf in php http://www.tcpdf.org/

    Static Vs. Dynamic Binding in Java

    There are three major differences between static and dynamic binding while designing the compilers and how variables and procedures are transferred to the runtime environment. These differences are as follows:

    Static Binding: In static binding three following problems are discussed:

    • Definition of a procedure

    • Declaration of a name(variable, etc.)

    • Scope of the declaration

    Dynamic Binding: Three problems that come across in the dynamic binding are as following:

    • Activation of a procedure

    • Binding of a name

    • Lifetime of a binding

    How to format numbers by prepending 0 to single-digit numbers?

    with this function you can print with any n digits you want

    function frmtDigit(num, n) {
        isMinus = num < 0;
        if (isMinus)
            num *= -1;
        digit = '';
        if (typeof n == 'undefined')
            n = 2;//two digits
        for (i = 1; i < n; i++) {
            if (num < (1 + Array(i + 1).join("0")))
                digit += '0';
        }
        digit = (isMinus ? '-' : '') + digit + num;
        return digit;
    };
    

    Setting equal heights for div's with jQuery

    <div class('a')>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
    </div>
    <div class('b')>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
       <div class('.cols-to-eq')></div>
    </div>
    var a = ['.a','.b'];
    a.forEach(function(value) {
        var column = 0;
        $(value).find('.cols-to-eq').each(function(){
            if($(this).height() > column){
                column = $(this).height();
            }
        });
        $(value).find('.cols-to-
        eq').attr('style','height:'+column+'px');
       });
    

    Android: Bitmaps loaded from gallery are rotated in ImageView

    The methods below scales AND rotates the bitmap according to the orientation:

    public Bitmap scaleAndRotateImage(String path, int orientation, final int targetWidth, final int targetHeight)
    {
        Bitmap bitmap = null;
    
        try
        {
            // Check the dimensions of the Image
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
    
            // Adjust the Width and Height
            int sourceWidth, sourceHeight;
            if (orientation == 90 || orientation == 270)
            {
                sourceWidth = options.outHeight;
                sourceHeight = options.outWidth;
            }
            else
            {
                sourceWidth = options.outWidth;
                sourceHeight = options.outHeight;
            }
    
            // Calculate the maximum required scaling ratio if required and load the bitmap
            if (sourceWidth > targetWidth || sourceHeight > targetHeight)
            {
                float widthRatio = (float)sourceWidth / (float)targetWidth;
                float heightRatio = (float)sourceHeight / (float)targetHeight;
                float maxRatio = Math.max(widthRatio, heightRatio);
                options.inJustDecodeBounds = false;
                options.inSampleSize = (int)maxRatio;
                bitmap = BitmapFactory.decodeFile(path, options);
            }
            else
            {
                bitmap = BitmapFactory.decodeFile(path);
            }
    
            // We need to rotate the bitmap (if required)
            int orientationInDegrees = exifToDegrees(orientation);
            if (orientation > 0)
            {
                Matrix matrix = new Matrix();
                if (orientation != 0f)
                {
                    matrix.preRotate(orientationInDegrees);
                };
    
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            }
    
            // Re-scale the bitmap if necessary
            sourceWidth = bitmap.getWidth();
            sourceHeight = bitmap.getHeight();
    
            if (sourceWidth != targetWidth || sourceHeight != targetHeight)
            {
                float widthRatio = (float)sourceWidth / (float)targetWidth;
                float heightRatio = (float)sourceHeight / (float)targetHeight;
                float maxRatio = Math.max(widthRatio, heightRatio);
                sourceWidth = (int)((float)sourceWidth / maxRatio);
                sourceHeight = (int)((float)sourceHeight / maxRatio);
                bitmap = Bitmap.createScaledBitmap(bitmap, sourceWidth, sourceHeight, true);
            }
        }
        catch (Exception e)
        {
            Logger.d("Could not rotate the image");
            Logger.d(e.getMessage());
        }
        return bitmap;
    }
    

    Example:

    public void getPictureFromDevice(Uri Uri,ImageView imageView)
    {
        try
        {
            ExifInterface exifInterface = new ExifInterface(Uri.getPath());
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    
            Bitmap bitmap = scaleAndRotateImage(Uri.getPath(), orientation, imageView.getWidth(), imageView.getHeight());
            imageView.setImageBitmap(bitmap);
        }
        catch (OutOfMemoryError outOfMemoryError)
        {
            Logger.d(outOfMemoryError.getLocalizedMessage());
            Logger.d("Failed to load image from filePath (out of memory)");
            Logger.d(Uri.toString());
        }
        catch (Exception e)
        {
            Logger.d("Failed to load image from filePath");
            Logger.d(Uri.toString());
        }
    }
    

    git command to move a folder inside another

     git mv common include
    

    should work.

    From the git mv man page:

    git mv [-f] [-n] [-k] <source> ... <destination directory>
    

    In the second form, the last argument has to be an existing directory; the given sources will be moved into this directory.
    The index is updated after successful completion, but the change must still be committed.

    No "git add" should be done before the move.


    Note: "git mv A B/", when B does not exist as a directory, should error out, but it didn't.

    See commit c57f628 by Matthieu Moy (moy) for Git 1.9/2.0 (Q1 2014):

    Git used to trim the trailing slash, and make the command equivalent to 'git mv file no-such-dir', which created the file no-such-dir (while the trailing slash explicitly stated that it could only be a directory).

    This patch skips the trailing slash removal for the destination path.
    The path with its trailing slash is passed to rename(2), which errors out with the appropriate message:

    $ git mv file no-such-dir/
    fatal: renaming 'file' failed: Not a directory
    

    Getters \ setters for dummies

    In addition to @millimoose's answer, setters can also be used to update other values.

    function Name(first, last) {
        this.first = first;
        this.last = last;
    }
    
    Name.prototype = {
        get fullName() {
            return this.first + " " + this.last;
        },
    
        set fullName(name) {
            var names = name.split(" ");
            this.first = names[0];
            this.last = names[1];
        }
    };
    

    Now, you can set fullName, and first and last will be updated and vice versa.

    n = new Name('Claude', 'Monet')
    n.first # "Claude"
    n.last # "Monet"
    n.fullName # "Claude Monet"
    n.fullName = "Gustav Klimt"
    n.first # "Gustav"
    n.last # "Klimt"
    

    PHP Undefined Index

    The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.

    When you submit the form it will then exist, and it won't complain about it.

    #so change
    $_GET['query_age'];
    #to:
    (!empty($_GET['query_age']) ? $_GET['query_age'] : null);
    

    Change drawable color programmatically

    Syntax

    "your image name".setColorFilter("your context".getResources().getColor("color name"));
    

    Example

    myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));
    

    How to configure a HTTP proxy for svn

    There are two common approaches for this:

    If you are on Windows, you can also write http-proxy- options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.

    Conda command not found

    Maybe you should type add this to your .bashrc or .zshrc

    export PATH="/anaconda3/bin":$PATH
    

    It worked for me.

    Checking from shell script if a directory contains files

    The solutions so far use ls. Here's an all bash solution:

    #!/bin/bash
    shopt -s nullglob dotglob     # To include hidden files
    files=(/some/dir/*)
    if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi
    

    Find where python is installed (if it isn't default dir)

    Have a look at sys.path:

    >>> import sys
    >>> print(sys.path)
    

    How to access environment variable values?

    There's also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

    from envs import env
    env('SECRET_KEY') # 'your_secret_key_here'
    env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']
    

    Creating a thumbnail from an uploaded image

    I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.

    But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).

    If you are having questions about how to use this function, then try taking a look at the well documented version here.

    function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
        list($original_width, $original_height, $original_type) = getimagesize($filepath);
        if ($original_width > $original_height) {
            $new_width = $thumbnail_width;
            $new_height = intval($original_height * $new_width / $original_width);
        } else {
            $new_height = $thumbnail_height;
            $new_width = intval($original_width * $new_height / $original_height);
        }
        $dest_x = intval(($thumbnail_width - $new_width) / 2);
        $dest_y = intval(($thumbnail_height - $new_height) / 2);
    
        if ($original_type === 1) {
            $imgt = "ImageGIF";
            $imgcreatefrom = "ImageCreateFromGIF";
        } else if ($original_type === 2) {
            $imgt = "ImageJPEG";
            $imgcreatefrom = "ImageCreateFromJPEG";
        } else if ($original_type === 3) {
            $imgt = "ImagePNG";
            $imgcreatefrom = "ImageCreateFromPNG";
        } else {
            return false;
        }
    
        $old_image = $imgcreatefrom($filepath);
        $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background
    
        // figuring out the color for the background
        if(is_array($background) && count($background) === 3) {
          list($red, $green, $blue) = $background;
          $color = imagecolorallocate($new_image, $red, $green, $blue);
          imagefill($new_image, 0, 0, $color);
        // apply transparent background only if is a png image
        } else if($background === 'transparent' && $original_type === 3) {
          imagesavealpha($new_image, TRUE);
          $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
          imagefill($new_image, 0, 0, $color);
        }
    
        imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
        $imgt($new_image, $thumbpath);
        return file_exists($thumbpath);
    }
    

    What is the best way to know if all the variables in a Class are null?

    I think this is a solution that solves your problem easily: (return true if any of the parameters is not null)

      public boolean isUserEmpty(){ 
    boolean isEmpty;
    isEmpty =  isEmpty = Stream.of(id,
                name)
            .anyMatch(userParameter -> userParameter != null);
    
    return isEmpty;}
    

    Another solution to the same task is:(you can change it to if(isEmpty==0) checks if all the parameters are null.

    public boolean isUserEmpty(){  
           long isEmpty;
                isEmpty = Stream.of(id,
                        name)
                        .filter(userParameter -> userParameter != null).count();
    
                if (isEmpty > 0) {
                    return true;
                } else {
                    return false;
                }
        }
    

    Java switch statement multiple cases

    // Noncompliant Code Example

    switch (i) {
      case 1:
        doFirstThing();
        doSomething();
        break;
      case 2:
        doSomethingDifferent();
        break;
      case 3:  // Noncompliant; duplicates case 1's implementation
        doFirstThing();
        doSomething();
        break;
      default:
        doTheRest();
    }
    
    if (a >= 0 && a < 10) {
      doFirstThing();
    
      doTheThing();
    }
    else if (a >= 10 && a < 20) {
      doTheOtherThing();
    }
    else if (a >= 20 && a < 50) {
      doFirstThing();
      doTheThing();  // Noncompliant; duplicates first condition
    }
    else {
      doTheRest();
    }
    

    //Compliant Solution

    switch (i) {
      case 1:
      case 3:
        doFirstThing();
        doSomething();
        break;
      case 2:
        doSomethingDifferent();
        break;
      default:
        doTheRest();
    }
    
    if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
      doFirstThing();
      doTheThing();
    }
    else if (a >= 10 && a < 20) {
      doTheOtherThing();
    }
    else {
      doTheRest();
    }
    

    How to Store Historical Data

    You could just partition the tables no?

    "Partitioned Table and Index Strategies Using SQL Server 2008 When a database table grows in size to the hundreds of gigabytes or more, it can become more difficult to load new data, remove old data, and maintain indexes. Just the sheer size of the table causes such operations to take much longer. Even the data that must be loaded or removed can be very sizable, making INSERT and DELETE operations on the table impractical. The Microsoft SQL Server 2008 database software provides table partitioning to make such operations more manageable."

    in python how do I convert a single digit number into a double digits string?

    >>> a=["%02d" % x for x in range(24)]
    >>> a
    ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
    >>> 
    

    It is that simple

    cannot load such file -- bundler/setup (LoadError)

    I got this error in a fresh Rails app with bundle correctly installed. Commenting out the spring gem in Gemfile resolved the problem.

    Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

    For react-native-firebase, adding this to app/build.gradle dependencies section made it work for me:

    implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
    implementation('com.squareup.okio:okio:1.15.0') { force = true }
    implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}
    

    How to get a Fragment to remove itself, i.e. its equivalent of finish()?

    If you are using the new Navigation Component, is simple as

    findNavController().popBackStack()
    

    It will do all the FragmentTransaction in behind for you.

    How to get JS variable to retain value after page refresh?

    This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.

    When you need to set a variable that should be reflected in the next page(s), use:

    var someVarName = "value";
    localStorage.setItem("someVarKey", someVarName);
    

    And in any page (like when the page has loaded), get it like:

    var someVarName = localStorage.getItem("someVarKey");
    

    .getItem() will return null if no value stored, or the value stored.

    Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.

    MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.

    It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).


    References:

    Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

    Short answer

    Install the latest version of mongodb.

    A little longer answer

    Make sure your package.json is using the latest version of mongodb, then remove node_modules/mongodb and do npm install again. If you didn't use mongodb as a direct dependency, try to find which package is using mongdb. I used:

    find . -type f -name package.json | xargs grep mongodb
    ...
    ./sails-mongo/package.json:    "mongodb": "1.4.26",
    ...
    

    So I updated ./sails-mongo/package.json to:

    "mongodb": "2.1.7",
    

    Then remove node_modules/mongodb and do npm install again. Seems fine now.

    Even longer answer

    I don't like the current suggested way of using

    require('../browser_build/bson')
    

    Since looking at ../browser_build/bson.js, a 4k+ lines file, which seem also a "non-native" implementation. So although it won't spit out any complains, it is still "using pure JS version", which means slower performance.

    Looking at https://github.com/mongodb/js-bson/issues/145 and https://github.com/mongodb/js-bson/issues/165, it seems like the issue was caused by:

    antoniofruci commented on Sep 15, 2015

    I just found out that c++ code has been moved out 6 months ago and it is now an optional dependency: bson-ext. Indeed, if you install latest version no error occurs.

    So I tried to remove the whole node_modules and still got the same error. And looking at package.json of node_modules/mongodb, its version is still 1.4.26, not latest 2.1.7.

    Apparently my mongodb comes as a dependency of another package I installed: sails-mongo. Modifying the package.json of sails-mongo and redoing npm install finally solve the issue.

    My eclipse won't open, i download the bundle pack it keeps saying error log

    Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

    This will be a JRE and JDK package.

    There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

    How to get href value using jQuery?

    If your html link is like this:

    <a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>
    

    Then you can access the href in jquery as given below (there is no need to use "a" in href for this)

    $(".linkClass").on("click",accesshref);
    
    function accesshref()
     {
     var url = $(".linkClass").attr("href");
     //OR
     var url = $(this).attr("href");
    }
    

    Javascript : get <img> src and set as variable?

    in this situation, you would grab the element by its id using getElementById and then just use .src

    var youtubeimgsrc = document.getElementById("youtubeimg").src;
    

    SQL Server: Error converting data type nvarchar to numeric

    I was running into this error while converting from nvarchar to float.
    What I had to do was to use the LEFT function on the nvarchar field.

    Example: Left(Field,4)

    Basically, the query will look like:

    Select convert(float,left(Field,4)) from TABLE
    

    Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
    Hope it helps someone out there.

    Pythonic way to check if a file exists?

    This was the best way for me. You can retrieve all existing files (be it symbolic links or normal):

    os.path.lexists(path)

    Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().
    
    New in version 2.4.
    

    Safe String to BigDecimal conversion

    String value = "1,000,000,000.999999999999999";
    BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
    System.out.println(money);
    

    Full code to prove that no NumberFormatException is thrown:

    import java.math.BigDecimal;
    
    public class Tester {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String value = "1,000,000,000.999999999999999";
            BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
            System.out.println(money);
        }
    }
    

    Output

    1000000000.999999999999999

    Why does javascript replace only first instance when using replace?

    You need to set the g flag to replace globally:

    date.replace(new RegExp("/", "g"), '')
    // or
    date.replace(/\//g, '')
    

    Otherwise only the first occurrence will be replaced.

    Database Structure for Tree Data Structure

    If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)

    In common LDAP is used to organize records in hierarchical structure.

    Auto-refreshing div with jQuery - setTimeout or another method?

    Another modification:

    function update() {
      $.get("response.php", function(data) {
        $("#some_div").html(data);
        window.setTimeout(update, 10000);
      });
    }
    

    The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.

    Also, if the server fails to respond, it won't keep trying.

    I've used a similar method in the past using .ajax to handle even more complex behaviour:

    function update() {
      $("#notice_div").html('Loading..'); 
      $.ajax({
        type: 'GET',
        url: 'response.php',
        timeout: 2000,
        success: function(data) {
          $("#some_div").html(data);
          $("#notice_div").html(''); 
          window.setTimeout(update, 10000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $("#notice_div").html('Timeout contacting server..');
          window.setTimeout(update, 60000);
        }
    }
    

    This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.

    This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.

    Eclipse IDE for Java - Full Dark Theme

    You can use this great theme from above and add predefined theme only for editor from this site:

    http://eclipsecolorthemes.org/

    (I use guari and retta and I think that looks real good :)

    I hope that it will help someone :)

    Is it possible to embed animated GIFs in PDFs?

    It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.

    Using Transactions or SaveChanges(false) and AcceptAllChanges()?

    Because some database can throw an exception at dbContextTransaction.Commit() so better this:

    using (var context = new BloggingContext()) 
    { 
      using (var dbContextTransaction = context.Database.BeginTransaction()) 
      { 
        try 
        { 
          context.Database.ExecuteSqlCommand( 
              @"UPDATE Blogs SET Rating = 5" + 
                  " WHERE Name LIKE '%Entity Framework%'" 
              ); 
    
          var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
          foreach (var post in query) 
          { 
              post.Title += "[Cool Blog]"; 
          } 
    
          context.SaveChanges(false); 
    
          dbContextTransaction.Commit(); 
    
          context.AcceptAllChanges();
        } 
        catch (Exception) 
        { 
          dbContextTransaction.Rollback(); 
        } 
      } 
    } 
    

    Foreach loop, determine which is the last iteration of the loop

    How to convert foreach to react to the last element:

    List<int> myList = new List<int>() {1, 2, 3, 4, 5};
    Console.WriteLine("foreach version");
    {
        foreach (var current in myList)
        {
            Console.WriteLine(current);
        }
    }
    Console.WriteLine("equivalent that reacts to last element");
    {
        var enumerator = myList.GetEnumerator();
        if (enumerator.MoveNext() == true) // Corner case: empty list.
        {
            while (true)
            {
                int current = enumerator.Current;
    
                // Handle current element here.
                Console.WriteLine(current);
    
                bool ifLastElement = (enumerator.MoveNext() == false);
                if (ifLastElement)
                {
                    // Cleanup after last element
                    Console.WriteLine("[last element]");
                    break;
                }
            }
        }
        enumerator.Dispose();
    }
    

    Reset the Value of a Select Box

    The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

    <form>
      <select>
        <option>one</option>
        <option>two</option>
        <option selected>three</option>
      </select>
      <input type="reset" value="Reset" />
    </form>
    

    Or, using JavaScript, it can be done in following way:

    HTML Code:

    <select>
      <option selected>one</option>
      <option>two</option>
      <option>three</option>
    </select>
    <button id="revert">Reset</button>
    

    And JavaScript code:

    const button = document.getElementById("revert");
    const options = document.querySelectorAll('select option');
    button.onclick = () => {
      for (var i = 0; i < options.length; i++) {
        options[i].selected = options[i].defaultSelected;
      }
    }
    

    Both of these methods will work if you have multiple selected items or single selected item.

    Angularjs -> ng-click and ng-show to show a div

    Just remove css from your js fiddle, ng-show will controll it. AngularJS sets the display style to none (using an !important flag). And remove this class when it must be shown.

    Collections.sort with multiple fields

    (originally from Ways to sort lists of objects in Java based on multiple fields)

    Original working code in this gist

    Using Java 8 lambda's (added April 10, 2019)

    Java 8 solves this nicely by lambda's (though Guava and Apache Commons might still offer more flexibility):

    Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
                .thenComparing(Report::getStudentNumber)
                .thenComparing(Report::getSchool));
    

    Thanks to @gaoagong's answer below.

    Note that one advantage here is that the getters are evaluated lazily (eg. getSchool() is only evaluated if relevant).

    Messy and convoluted: Sorting by hand

    Collections.sort(pizzas, new Comparator<Pizza>() {  
        @Override  
        public int compare(Pizza p1, Pizza p2) {  
            int sizeCmp = p1.size.compareTo(p2.size);  
            if (sizeCmp != 0) {  
                return sizeCmp;  
            }  
            int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings);  
            if (nrOfToppingsCmp != 0) {  
                return nrOfToppingsCmp;  
            }  
            return p1.name.compareTo(p2.name);  
        }  
    });  
    

    This requires a lot of typing, maintenance and is error prone. The only advantage is that getters are only invoked when relevant.

    The reflective way: Sorting with BeanComparator

    ComparatorChain chain = new ComparatorChain(Arrays.asList(
       new BeanComparator("size"), 
       new BeanComparator("nrOfToppings"), 
       new BeanComparator("name")));
    
    Collections.sort(pizzas, chain);  
    

    Obviously this is more concise, but even more error prone as you lose your direct reference to the fields by using Strings instead (no typesafety, auto-refactorings). Now if a field is renamed, the compiler won’t even report a problem. Moreover, because this solution uses reflection, the sorting is much slower.

    Getting there: Sorting with Google Guava’s ComparisonChain

    Collections.sort(pizzas, new Comparator<Pizza>() {  
        @Override  
        public int compare(Pizza p1, Pizza p2) {  
            return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();  
            // or in case the fields can be null:  
            /* 
            return ComparisonChain.start() 
               .compare(p1.size, p2.size, Ordering.natural().nullsLast()) 
               .compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast()) 
               .compare(p1.name, p2.name, Ordering.natural().nullsLast()) 
               .result(); 
            */  
        }  
    });  
    

    This is much better, but requires some boiler plate code for the most common use case: null-values should be valued less by default. For null-fields, you have to provide an extra directive to Guava what to do in that case. This is a flexible mechanism if you want to do something specific, but often you want the default case (ie. 1, a, b, z, null).

    And as noted in the comments below, these getters are all evaluated immediately for each comparison.

    Sorting with Apache Commons CompareToBuilder

    Collections.sort(pizzas, new Comparator<Pizza>() {  
        @Override  
        public int compare(Pizza p1, Pizza p2) {  
            return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();  
        }  
    });  
    

    Like Guava’s ComparisonChain, this library class sorts easily on multiple fields, but also defines default behavior for null values (ie. 1, a, b, z, null). However, you can’t specify anything else either, unless you provide your own Comparator.

    Again, as noted in the comments below, these getters are all evaluated immediately for each comparison.

    Thus

    Ultimately it comes down to flavor and the need for flexibility (Guava’s ComparisonChain) vs. concise code (Apache’s CompareToBuilder).

    Bonus method

    I found a nice solution that combines multiple comparators in order of priority on CodeReview in a MultiComparator:

    class MultiComparator<T> implements Comparator<T> {
        private final List<Comparator<T>> comparators;
    
        public MultiComparator(List<Comparator<? super T>> comparators) {
            this.comparators = comparators;
        }
    
        public MultiComparator(Comparator<? super T>... comparators) {
            this(Arrays.asList(comparators));
        }
    
        public int compare(T o1, T o2) {
            for (Comparator<T> c : comparators) {
                int result = c.compare(o1, o2);
                if (result != 0) {
                    return result;
                }
            }
            return 0;
        }
    
        public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
            Collections.sort(list, new MultiComparator<T>(comparators));
        }
    }
    

    Ofcourse Apache Commons Collections has a util for this already:

    ComparatorUtils.chainedComparator(comparatorCollection)

    Collections.sort(list, ComparatorUtils.chainedComparator(comparators));
    

    method in class cannot be applied to given types

    call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error

    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

    I had the same problem, my code is below:

    private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
    private Statement stmt = conn.createStatement();
    

    I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:

    No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud
    

    so I loaded the driver class, as below, when I saw other answers posted:

    Class.forName("com.mysql.jdbc.Driver");
    

    It works now! I don't know why it works well locally, I need your help, thank you so much!

    Angular 2 / 4 / 5 not working in IE11

    In polyfills.ts

    import 'core-js/es6/symbol';
    import 'core-js/es6/object';
    import 'core-js/es6/function';
    import 'core-js/es6/parse-int';
    import 'core-js/es6/parse-float';
    import 'core-js/es6/number';
    import 'core-js/es6/math';
    import 'core-js/es6/string';
    import 'core-js/es6/date';
    
    import 'core-js/es6/array';
    import 'core-js/es7/array';
    
    import 'core-js/es6/regexp';
    import 'core-js/es6/map';
    import 'core-js/es6/weak-map';
    import 'core-js/es6/weak-set';
    import 'core-js/es6/set';
    
    /** IE10 and IE11 requires the following for NgClass support on SVG elements */
     import 'classlist.js';  // Run `npm install --save classlist.js`.
    
    /** Evergreen browsers require these. **/
    import 'core-js/es6/reflect';
    import 'core-js/es7/reflect';
    
    /**
     * Required to support Web Animations `@angular/animation`.
     * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
     **/
    import 'web-animations-js';  // Run `npm install --save web-animations-js`.
    

    Navigation Drawer (Google+ vs. YouTube)

    Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:

    https://github.com/jaredsburrows/RibbonMenu

    What's the Purpose

    • Ease of Access: Allow easy access to a menu that slides in and out
    • Ease of Implementation: Update the same screen using minimal amount of code
    • Independency: Does not require support libraries such as ActionBarSherlock
    • Customization: Easy to change colors and menus

    What's New

    • Changed the sliding animation to match Facebook and Google+ apps
    • Added standard ActionBar (you can chose to use ActionBarSherlock)
    • Used menuitem to open the Menu
    • Added ability to update ListView on main Activity
    • Added 2 ListViews to the Menu, similiar to Facebook and Google+ apps
    • Added a AutoCompleteTextView and a Button as well to show examples of implemenation
    • Added method to allow users to hit the 'back button' to hide the menu when it is open
    • Allows users to interact with background(main ListView) and the menu at the same time unlike the Facebook and Google+ apps!

    ActionBar with Menu out

    ActionBar with Menu out

    ActionBar with Menu out and search selected

    ActionBar with Menu out and search selected

    vertical & horizontal lines in matplotlib

    If you want to add a bounding box, use a rectangle:

    ax = plt.gca()
    r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
    ax.add_artist(r)
    

    Rectangle doc

    How to use shared memory with Linux in C

    Here's a mmap example:

    #include <sys/mman.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    /*
     * pvtmMmapAlloc - creates a memory mapped file area.  
     * The return value is a page-aligned memory value, or NULL if there is a failure.
     * Here's the list of arguments:
     * @mmapFileName - the name of the memory mapped file
     * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
     * @create - determines whether or not the area should be created.
     */
    void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
    {      
      void * retv = NULL;                                                                                              
      if (create)                                                                                         
      {                                                                                                   
        mode_t origMask = umask(0);                                                                       
        int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
        umask(origMask);                                                                                  
        if (mmapFd < 0)                                                                                   
        {                                                                                                 
          perror("open mmapFd failed");                                                                   
          return NULL;                                                                                    
        }                                                                                                 
        if ((ftruncate(mmapFd, size) == 0))               
        {                                                                                                 
          int result = lseek(mmapFd, size - 1, SEEK_SET);               
          if (result == -1)                                                                               
          {                                                                                               
            perror("lseek mmapFd failed");                                                                
            close(mmapFd);                                                                                
            return NULL;                                                                                  
          }                                                                                               
    
          /* Something needs to be written at the end of the file to                                      
           * have the file actually have the new size.                                                    
           * Just writing an empty string at the current file position will do.                           
           * Note:                                                                                        
           *  - The current position in the file is at the end of the stretched                           
           *    file due to the call to lseek().  
                  *  - The current position in the file is at the end of the stretched                    
           *    file due to the call to lseek().                                                          
           *  - An empty string is actually a single '\0' character, so a zero-byte                       
           *    will be written at the last byte of the file.                                             
           */                                                                                             
          result = write(mmapFd, "", 1);                                                                  
          if (result != 1)                                                                                
          {                                                                                               
            perror("write mmapFd failed");                                                                
            close(mmapFd);                                                                                
            return NULL;                                                                                  
          }                                                                                               
          retv  =  mmap(NULL, size,   
                      PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     
    
          if (retv == MAP_FAILED || retv == NULL)                                                         
          {                                                                                               
            perror("mmap");                                                                               
            close(mmapFd);                                                                                
            return NULL;                                                                                  
          }                                                                                               
        }                                                                                                 
      }                                                                                                   
      else                                                                                                
      {                                                                                                   
        int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
        if (mmapFd < 0)                                                                                   
        {                                                                                                 
          return NULL;                                                                                    
        }                                                                                                 
        int result = lseek(mmapFd, 0, SEEK_END);                                                          
        if (result == -1)                                                                                 
        {                                                                                                 
          perror("lseek mmapFd failed");                  
          close(mmapFd);                                                                                  
          return NULL;                                                                                    
        }                                                                                                 
        if (result == 0)                                                                                  
        {                                                                                                 
          perror("The file has 0 bytes");                           
          close(mmapFd);                                                                                  
          return NULL;                                                                                    
        }                                                                                              
        retv  =  mmap(NULL, size,     
                    PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       
    
        if (retv == MAP_FAILED || retv == NULL)                                                           
        {                                                                                                 
          perror("mmap");                                                                                 
          close(mmapFd);                                                                                  
          return NULL;                                                                                    
        }                                                                                                 
    
        close(mmapFd);                                                                                    
    
      }                                                                                                   
      return retv;                                                                                        
    }                                                                                                     
    

    How do I get the value of a textbox using jQuery?

    By Using

    $("#txtEmail").val()
    

    you get the actual value of the element

    How do I make an Event in the Usercontrol and have it handled in the Main Form?

    Try mapping it. Try placing this code in your UserControl:

    public event EventHandler ValueChanged {
      add { numericUpDown1.ValueChanged += value; }
      remove { numericUpDown1.ValueChanged -= value; }
    }
    

    then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

    Add Auto-Increment ID to existing table?

    Just change the ADD to MODIFY and it will works !

    Replace

    ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT
    

    To

    ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT;
    

    How to add element in Python to the end of list using list.insert?

    list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

    Python 3.7.4
    >>>lst=[10,20,30]
    >>>lst.insert(len(lst), 101)
    >>>lst
    [10, 20, 30, 101]
    >>>lst.insert(len(lst)+50, 202)
    >>>lst
    [10, 20, 30, 101, 202]
    

    Time complexity, append O(1), insert O(n)

    map vs. hash_map in C++

    map is implemented from balanced binary search tree(usually a rb_tree), since all the member in balanced binary search tree is sorted so is map;

    hash_map is implemented from hashtable.Since all the member in hashtable is unsorted so the members in hash_map(unordered_map) is not sorted.

    hash_map is not a c++ standard library, but now it renamed to unordered_map(you can think of it renamed) and becomes c++ standard library since c++11 see this question Difference between hash_map and unordered_map? for more detail.

    Below i will give some core interface from source code of how the two type map is implemented.

    map:

    The below code is just to show that, map is just a wrapper of an balanced binary search tree, almost all it's function is just invoke the balanced binary search tree function.

    template <typename Key, typename Value, class Compare = std::less<Key>>
    class map{
        // used for rb_tree to sort
        typedef Key    key_type;
    
        // rb_tree node value
        typedef std::pair<key_type, value_type> value_type;
    
        typedef Compare key_compare;
    
        // as to map, Key is used for sort, Value used for store value
        typedef rb_tree<key_type, value_type, key_compare> rep_type;
    
        // the only member value of map (it's  rb_tree)
        rep_type t;
    };
    
    // one construct function
    template<typename InputIterator>
    map(InputIterator first, InputIterator last):t(Compare()){
            // use rb_tree to insert value(just insert unique value)
            t.insert_unique(first, last);
    }
    
    // insert function, just use tb_tree insert_unique function
    //and only insert unique value
    //rb_tree insertion time is : log(n)+rebalance
    // so map's  insertion time is also : log(n)+rebalance 
    typedef typename rep_type::const_iterator iterator;
    std::pair<iterator, bool> insert(const value_type& v){
        return t.insert_unique(v);
    };
    

    hash_map:

    hash_map is implemented from hashtable whose structure is somewhat like this:

    enter image description here

    In the below code, i will give the main part of hashtable, and then gives hash_map.

    // used for node list
    template<typename T>
    struct __hashtable_node{
        T val;
        __hashtable_node* next;
    };
    
    template<typename Key, typename Value, typename HashFun>
    class hashtable{
        public:
            typedef size_t   size_type;
            typedef HashFun  hasher;
            typedef Value    value_type;
            typedef Key      key_type;
        public:
            typedef __hashtable_node<value_type> node;
    
            // member data is buckets array(node* array)
            std::vector<node*> buckets;
            size_type num_elements;
    
            public:
                // insert only unique value
                std::pair<iterator, bool> insert_unique(const value_type& obj);
    
    };
    

    Like map's only member is rb_tree, the hash_map's only member is hashtable. It's main code as below:

    template<typename Key, typename Value, class HashFun = std::hash<Key>>
    class hash_map{
        private:
            typedef hashtable<Key, Value, HashFun> ht;
    
            // member data is hash_table
            ht rep;
    
        public:
            // 100 buckets by default
            // it may not be 100(in this just for simplify)
            hash_map():rep(100){};
    
            // like the above map's insert function just invoke rb_tree unique function
            // hash_map, insert function just invoke hashtable's unique insert function
            std::pair<iterator, bool> insert(const Value& v){
                    return t.insert_unique(v);
            };
    
    };
    

    Below image shows when a hash_map have 53 buckets, and insert some values, it's internal structure.

    enter image description here

    The below image shows some difference between map and hash_map(unordered_map), the image comes from How to choose between map and unordered_map?:

    enter image description here

    Problems using Maven and SSL behind proxy

    I ran into this problem in the same situation, and I wrote up a detailed answer to a related question on stack overflow explaining how to more easily modify the system's cacerts using a GUI tool. I think it's a little bit better than using a one-off keystore for a specific project or modifying the settings for maven (which may cause trouble down the road).

    How to retrieve SQL result column value using column name in Python?

    Of course there is. In Python 2.7.2+...

    import MySQLdb as mdb
    con =  mdb.connect('localhost', 'user', 'password', 'db');
    cur = con.cursor()
    cur.execute('SELECT Foo, Bar FROM Table')
    for i in range(int(cur.numrows)):
        foo, bar = cur.fetchone()
        print 'foo = %s' % foo
        print 'bar = %s' % bar
    

    Getting "conflicting types for function" in C, why?

    When you don't give a prototype for the function before using it, C assumes that it takes any number of parameters and returns an int. So when you first try to use do_something, that's the type of function the compiler is looking for. Doing this should produce a warning about an "implicit function declaration".

    So in your case, when you actually do declare the function later on, C doesn't allow function overloading, so it gets pissy because to it you've declared two functions with different prototypes but with the same name.

    Short answer: declare the function before trying to use it.

    jQuery Event : Detect changes to the html/text of a div

    Try the MutationObserver:

    browser support: http://caniuse.com/#feat=mutationobserver

    _x000D_
    _x000D_
    <html>_x000D_
      <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->_x000D_
    _x000D_
      <head>_x000D_
        </head>_x000D_
      <body>_x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <script type="text/javascript">_x000D_
          // Inspect the array of MutationRecord objects to identify the nature of the change_x000D_
    function mutationObjectCallback(mutationRecordsList) {_x000D_
      console.log("mutationObjectCallback invoked.");_x000D_
    _x000D_
      mutationRecordsList.forEach(function(mutationRecord) {_x000D_
        console.log("Type of mutation: " + mutationRecord.type);_x000D_
        if ("attributes" === mutationRecord.type) {_x000D_
          console.log("Old attribute value: " + mutationRecord.oldValue);_x000D_
        }_x000D_
      });_x000D_
    }_x000D_
          _x000D_
    // Create an observer object and assign a callback function_x000D_
    var observerObject = new MutationObserver(mutationObjectCallback);_x000D_
    _x000D_
          // the target to watch, this could be #yourUniqueDiv _x000D_
          // we use the body to watch for changes_x000D_
    var targetObject = document.body; _x000D_
          _x000D_
    // Register the target node to observe and specify which DOM changes to watch_x000D_
          _x000D_
          _x000D_
    observerObject.observe(targetObject, { _x000D_
      attributes: true,_x000D_
      attributeFilter: ["id", "dir"],_x000D_
      attributeOldValue: true,_x000D_
      childList: true_x000D_
    });_x000D_
    _x000D_
    // This will invoke the mutationObjectCallback function (but only after all script in this_x000D_
    // scope has run). For now, it simply queues a MutationRecord object with the change information_x000D_
    targetObject.appendChild(document.createElement('div'));_x000D_
    _x000D_
    // Now a second MutationRecord object will be added, this time for an attribute change_x000D_
    targetObject.dir = 'rtl';_x000D_
    _x000D_
    _x000D_
          </script>_x000D_
        </body>_x000D_
      </html>
    _x000D_
    _x000D_
    _x000D_

    Implode an array with JavaScript?

    For future reference, if you want to mimic the behaviour of PHP's implode() when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join() otherwise it defaults to using commas as delimiters:

    var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
    alert(bits.join());    // H,e,l,l,o, ,W,o,r,l,d
    alert(bits.join(''));  // Hello World
    

    How to show/hide if variable is null

    To clarify, the above example does work, my code in the example did not work for unrelated reasons.

    If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

    The following will cause the div to show:

    $scope.myvar = "Hello World";
    

    or

    $scope.myvar = true;
    

    The following will hide the div:

    $scope.myvar = null;
    

    or

    $scope.myvar = false;
    

    is of a type that is invalid for use as a key column in an index

    A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

    create table [misc_info]
    ( 
        [id] INTEGER PRIMARY KEY IDENTITY NOT NULL, 
        [key] nvarchar(450) UNIQUE NOT NULL, 
        [value] nvarchar(max) NOT NULL
    )
    

    i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

    Test if characters are in a string

    Use this function from stringi package:

    > stri_detect_fixed("test",c("et","es"))
    [1] FALSE  TRUE
    

    Some benchmarks:

    library(stringi)
    set.seed(123L)
    value <- stri_rand_strings(10000, ceiling(runif(10000, 1, 100))) # 10000 random ASCII strings
    head(value)
    
    chars <- "es"
    library(microbenchmark)
    microbenchmark(
       grepl(chars, value),
       grepl(chars, value, fixed=TRUE),
       grepl(chars, value, perl=TRUE),
       stri_detect_fixed(value, chars),
       stri_detect_regex(value, chars)
    )
    ## Unit: milliseconds
    ##                               expr       min        lq    median        uq       max neval
    ##                grepl(chars, value) 13.682876 13.943184 14.057991 14.295423 15.443530   100
    ##  grepl(chars, value, fixed = TRUE)  5.071617  5.110779  5.281498  5.523421 45.243791   100
    ##   grepl(chars, value, perl = TRUE)  1.835558  1.873280  1.956974  2.259203  3.506741   100
    ##    stri_detect_fixed(value, chars)  1.191403  1.233287  1.309720  1.510677  2.821284   100
    ##    stri_detect_regex(value, chars)  6.043537  6.154198  6.273506  6.447714  7.884380   100
    

    Difference between UTF-8 and UTF-16?

    Security: Use only UTF-8

    Difference between UTF-8 and UTF-16? Why do we need these?

    There have been at least a couple of security vulnerabilities in implementations of UTF-16. See Wikipedia for details.

    WHATWG and W3C have now declared that only UTF-8 is to be used on the Web.

    The [security] problems outlined here go away when exclusively using UTF-8, which is one of the many reasons that is now the mandatory encoding for all things.

    Other groups are saying the same.

    So while UTF-16 may continue being used internally by some systems such as Java and Windows, what little use of UTF-16 you may have seen in the past for data files, data exchange, and such, will likely fade away entirely.

    Put request with simple string as request body

    This works for me (code called from node js repl):

    const axios = require("axios");
    
    axios
        .put(
            "http://localhost:4000/api/token", 
            "mytoken", 
            {headers: {"Content-Type": "text/plain"}}
        )
        .then(r => console.log(r.status))
        .catch(e => console.log(e));
    

    Logs: 200

    And this is my request handler (I am using restify):

    function handleToken(req, res) {
        if(typeof req.body === "string" && req.body.length > 3) {
            res.send(200);
        } else {
            res.send(400);
        }
    }
    

    Content-Type header is important here.

    Replace only text inside a div using jquery

    Text shouldn't be on its own. Put it into a span element.

    Change it to this:

    <div id="one">
           <div class="first"></div>
           <span>"Hi I am text"</span>
           <div class="second"></div>
           <div class="third"></div>
    </div>
    
    $('#one span').text('Hi I am replace');
    

    Difference between <context:annotation-config> and <context:component-scan>

    <context:annotation-config>:

    This tells Spring that I am going to use Annotated beans as spring bean and those would be wired through @Autowired annotation, instead of declaring in spring config xml file.

    <context:component-scan base-package="com.test..."> :

    This tells Spring container, where to start searching those annotated beans. Here spring will search all sub packages of the base package.

    Python: Select subset from list based on index set

    Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

    from numpy import *
    property_a = array([545., 656., 5.4, 33.])
    property_b = array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    

    Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

    how to prevent "directory already exists error" in a makefile when using mkdir

    Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:

      %/.d:
              mkdir -p $(@D)
              touch $@
    

    Then make all files that go into the directory dependent on the .d file in that directory:

     obj/%.o: %.c obj/.d
        $(CC) $(CFLAGS) -c -o $@ $<
    

    Note use of $< instead of $^.

    Finally prevent the .d files from being removed automatically:

     .PRECIOUS: %/.d
    

    Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.

    Swift performSelector:withObject:afterDelay: is unavailable

    Swift 4

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        // your function here
    }
    

    Swift 3

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
        // your function here
    }
    

    Swift 2

    let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
    dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
        // your function here 
    })
    

    Get element from within an iFrame

    Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:

    <iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
    
    <script>
    function access() {
       var iframe = document.getElementById("iframe");
       var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
       console.log(innerDoc.body);
    }
    </script>
    

    How can I access a hover state in reactjs?

    I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

    onMouseOver={() => this.onMouseOver(someId)}
    onMouseOut={() => this.onMouseOut(someId)
    

    And implement the map as follows:

    onMouseOver(listId: string) {
      this.setState({
        ... // whatever
      });
    
      const handle = setTimeout(() => {
        scrollPreviewToComponentId(listId);
      }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
      this.hoverHandleMap[listId] = handle;
    }
    
    onMouseOut(listId: string) {
      this.setState({
        ... // whatever
      });
    
      const handle = this.hoverHandleMap[listId];
      clearTimeout(handle);
      delete this.hoverHandleMap[listId];
    }
    

    And the map is like so,

    hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};
    

    I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

    ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

    Though it is an old question, I am adding my answer in it, because the solution that worked for me on Windows 7 as an admin user, is missing in the answers' list. Though my solution is for installed MySQL, I am putting it for those who search for a solution for this error message. Here it is:

    1. Click on the Windows 7 start button and type taskmgr in the search bar
    2. Right click on the taskmgr program icon and select Run as administrator
    3. In the Task Manager window, go to the Services tab
    4. Right click on the MySQL service and click Start Service
    Step 1 and 2Step 3 and 4

    What Java ORM do you prefer, and why?

    I had a really good experience with Avaje Ebean when I was writing a medium sized JavaSE application.

    It uses standard JPA annotations to define entities, but exposes a much simpler API (No EntityManager or any of that attached/detached entities crap). It also lets you easily use SQL queries or event plain JDBC calls when necessary.

    It also has a very nice fluid and type-safe API for queries. You can write things like:

    List<Person> boys = Ebean.find(Person.class)
                                      .where()
                                           .eq("gender", "M")
                                           .le("age", 18)
                                      .orderBy("firstName")
                                      .findList();
    

    Format certain floating dataframe columns into percentage in pandas

    As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:

    You can apply conditional formatting, the visual styling of a DataFrame depending on the data within, by using the DataFrame.style property. This is a property that returns a pandas.Styler object, which has useful methods for formatting and displaying DataFrames.

    For your example, that would be (the usual table will show up in Jupyter):

    df.style.format({
        'var1': '{:,.2f}'.format,
        'var2': '{:,.2f}'.format,
        'var3': '{:,.2%}'.format,
    })
    

    Specifying number of decimal places in Python

    There's a few ways to do this depending on how you want to hold the value.

    You can use basic string formatting, e.g

    'Your Meal Price is %.2f' %  mealPrice
    

    You can modify the 2 to whatever precision you need.

    However, since you're dealing with money you should look into the decimal module which has a cool method named quantize which is exactly for working with monetary applications. You can use it like so:

    from decimal import Decimal, ROUND_DOWN
    mealPrice = Decimal(str(mealPrice)).quantize(Decimal('.01'), rounding=ROUND_DOWN)
    

    Note that the rounding attribute is purely optional as well.

    How to find the Git commit that introduced a string in any branch?

    Messing around with the same answers:

    $ git config --global alias.find '!git log --color -p -S '
    
    • ! is needed because other way, git do not pass argument correctly to -S. See this response
    • --color and -p helps to show exactly "whatchanged"

    Now you can do

    $ git find <whatever>
    

    or

    $ git find <whatever> --all
    $ git find <whatever> master develop
    

    If else embedding inside html

     <?php if (date("H") < "12" && date("H")>"6") { ?>
       src="<?php bloginfo('template_url'); ?>/images/img/morning.gif" 
     <?php } elseif (date("H") > "12" && date("H")<"17") { ?>
     src="<?php bloginfo('template_url'); ?>/images/img/noon.gif" 
      <?php } elseif (date("H") > "17" && date("H")<"21") { ?>
       src="<?php bloginfo('template_url'); ?>/images/img/evening.gif" 
      <?php } elseif (date("H") > "21" && date("H")<"24") { ?>
      src="<?php bloginfo('template_url'); ?>/images/img/night.gif" 
      <?php }else { ?>
      src="<?php bloginfo('template_url'); ?>/images/img/mid_night.gif" 
      <?php } ?>
    

    How to add property to object in PHP >= 5.3 strict mode without generating error

    If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass objects (I believe) is when you cast an array as an object or when you create a new stdClass object from scratch (and of course when you json_decode() something - silly me for forgetting!).

    Instead of:

    $foo = new StdClass();
    $foo->bar = '1234';
    

    You'd do:

    $foo = array('bar' => '1234');
    $foo = (object)$foo;
    

    Or if you already had an existing stdClass object:

    $foo = (array)$foo;
    $foo['bar'] = '1234';
    $foo = (object)$foo;
    

    Also as a 1 liner:

    $foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
    

    How to stop process from .BAT file?

    When you start a process from a batch file, it starts as a separate process with no hint towards the batch file that started it (since this would have finished running in the meantime, things like the parent process ID won't help you).

    If you know the process name, and it is unique among all running processes, you can use taskkill, like @IVlad suggests in a comment.

    If it is not unique, you might want to look into jobs. These terminate all spawned child processes when they are terminated.

    How to add new line in Markdown presentation?

    See the original markdown specification (bold mine):

    The implication of the “one or more consecutive lines of text” rule is that Markdown supports “hard-wrapped” text paragraphs. This differs significantly from most other text-to-HTML formatters (including Movable Type’s “Convert Line Breaks” option) which translate every line break character in a paragraph into a <br /> tag.

    When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return.

    How to search for rows containing a substring?

    Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

    http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

    Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

    If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

    What does file:///android_asset/www/index.html mean?

    file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

    It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

    That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

    Consider the code example:

    WebView webViewer = (WebView) findViewById(R.id.webViewer);
    webView.loadUrl("file:///android_asset/www/index.html");
    

    A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

    Best way to do multi-row insert in Oracle?

    If you have the values that you want to insert in another table already, then you can Insert from a select statement.

    INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;
    

    Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.

    @Espo's solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.

    Is right click a Javascript event?

    Handle event using jQuery library

    $(window).on("contextmenu", function(e)
    {
       alert("Right click");
    })
    

    Trying to fire the onload event on script tag

    You should set the src attribute after the onload event, f.ex:

    el.onload = function() { //...
    el.src = script;
    

    You should also append the script to the DOM before attaching the onload event:

    $body.append(el);
    el.onload = function() { //...
    el.src = script;
    

    Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

    What is an application binary interface (ABI)?

    In short and in philosophy, only things of a kind can get along well, and the ABI could be seen as the kind of which software stuff work together.

    Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

    @Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

    @InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
    @Mock MyInterface myInterface
    

    But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

    Split Java String by New Line

    There are three different conventions (it could be said that those are de facto standards) to set and display a line break:

    • carriage return + line feed
    • line feed
    • carriage return

    In some text editors, it is possible to exchange one for the other:

    Notepad++

    The simplest thing is to normalize to line feedand then split.

    final String[] lines = contents.replace("\r\n", "\n")
                                   .replace("\r", "\n")
                                   .split("\n", -1);
    

    Performance of FOR vs FOREACH in PHP

    One thing to watch out for in benchmarks (especially phpbench.com), is even though the numbers are sound, the tests are not. Alot of the tests on phpbench.com are doing things at are trivial and abuse PHP's ability to cache array lookups to skew benchmarks or in the case of iterating over an array doesn't actually test it in real world cases (no one writes empty for loops). I've done my own benchmarks that I've found are fairly reflective of the real world results and they always show the language's native iterating syntax foreach coming out on top (surprise, surprise).

    //make a nicely random array
    $aHash1 = range( 0, 999999 );
    $aHash2 = range( 0, 999999 );
    shuffle( $aHash1 );
    shuffle( $aHash2 );
    $aHash = array_combine( $aHash1, $aHash2 );
    
    
    $start1 = microtime(true);
    foreach($aHash as $key=>$val) $aHash[$key]++;
    $end1 = microtime(true);
    
    $start2 = microtime(true);
    while(list($key) = each($aHash)) $aHash[$key]++;
    $end2 = microtime(true);
    
    
    $start3 = microtime(true);
    $key = array_keys($aHash);
    $size = sizeOf($key);
    for ($i=0; $i<$size; $i++) $aHash[$key[$i]]++;
    $end3 = microtime(true);
    
    $start4 = microtime(true);
    foreach($aHash as &$val) $val++;
    $end4 = microtime(true);
    
    echo "foreach ".($end1 - $start1)."\n"; //foreach 0.947947025299
    echo "while ".($end2 - $start2)."\n"; //while 0.847212076187
    echo "for ".($end3 - $start3)."\n"; //for 0.439476966858
    echo "foreach ref ".($end4 - $start4)."\n"; //foreach ref 0.0886030197144
    
    //For these tests we MUST do an array lookup,
    //since that is normally the *point* of iteration
    //i'm also calling noop on it so that PHP doesn't
    //optimize out the loopup.
    function noop( $value ) {}
    
    //Create an array of increasing indexes, w/ random values
    $bHash = range( 0, 999999 );
    shuffle( $bHash );
    
    $bstart1 = microtime(true);
    for($i = 0; $i < 1000000; ++$i) noop( $bHash[$i] );
    $bend1 = microtime(true);
    
    $bstart2 = microtime(true);
    $i = 0; while($i < 1000000) { noop( $bHash[$i] ); ++$i; }
    $bend2 = microtime(true);
    
    
    $bstart3 = microtime(true);
    foreach( $bHash as $value ) { noop( $value ); }
    $bend3 = microtime(true);
    
    echo "for ".($bend1 - $bstart1)."\n"; //for 0.397135972977
    echo "while ".($bend2 - $bstart2)."\n"; //while 0.364789962769
    echo "foreach ".($bend3 - $bstart3)."\n"; //foreach 0.346374034882