Programs & Examples On #Memory fences

Mixing a PHP variable with a string literal

echo "{$test}y";

You can use braces to remove ambiguity when interpolating variables directly in strings.

Also, this doesn't work with single quotes. So:

echo '{$test}y';

will output

{$test}y

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

How to create a drop shadow only on one side of an element?

If you have a fixed color on the background, you can hide the side-shadow effect with two masking shadows having the same color of the background and blur = 0, example:

box-shadow: 
    -6px 0 white,         /*Left masking shadow*/
    6px 0 white,          /*Right masking shadow*/
    0 7px 4px -3px black; /*The real (slim) shadow*/

Note that the black shadow must be the last, and has a negative spread (-3px) in order to prevent it from extendig beyond the corners.

Here the fiddle (change the color of the masking shadows to see how it really works).

_x000D_
_x000D_
div{_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    border: 1px solid pink;_x000D_
    box-shadow: -6px 0 white, 6px 0 white, 0 7px 5px -2px black;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

enter image description here

How to check if a character in a string is a digit or letter

char charInt=character.charAt(0);   
if(charInt>=48 && charInt<=57){
    System.out.println("not character");
}
else
    System.out.println("Character");

Look for ASCII table to see how the int value are hardcoded .

Cannot make file java.io.IOException: No such file or directory

File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.

How to delete an SMS from the inbox in Android programmatically?

Use one of this method to select the last received SMS and delete it, here in this case i am getting the top most sms and going to delete using thread and id value of sms,

try {
    Uri uri = Uri.parse("content://sms/inbox");
    Cursor c = v.getContext().getContentResolver().query(uri, null, null, null, null);
    int i = c.getCount();

    if (c.moveToFirst()) {
    }
} catch (CursorIndexOutOfBoundsException ee) {
    Toast.makeText(v.getContext(), "Error :" + ee.getMessage(), Toast.LENGTH_LONG).show();
}

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

One command to convert date time to Unix format and then to string

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

Example:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

I think this will work for int, long and string values.

List<int> list = new List<int>(new int[]{ 2, 3, 7 });


var animals = new List<string>() { "bird", "dog" };

Node.js: How to read a stream into a buffer?

I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers

Set default format of datetimepicker as dd-MM-yyyy

Ammending as "optional Answer". If you don't need to programmatically solve the problem, here goes the "visual way" in VS2012.

In Visual Studio, you can set custom format directly from the properties Panel: enter image description here

First Set the "Format" property to: "Custom"; Secondly, set your custom format to: "dd-MM-yyyy";

Truncating a table in a stored procedure

You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.

You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.

1) Execute immediate

2) DBMS_SQL package

3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);

Hope this answers your question with explanation.

How do I get git to default to ssh and not https for new repositories

You may have accidentally cloned the repository in https instead of ssh. I've made this mistake numerous times on github. Make sure that you copy the ssh link in the first place when cloning, instead of the https link.

Cannot find name 'require' after upgrading to Angular4

The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

- npm install --save @types/node
- yarn add @types/node -D

Step 2: Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

If I've missed anything, jot a comment and I'll edit my answer.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Grep only the first match and stop

My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.

How do I update a Mongo document after inserting it?

I will use collection.save(the_changed_dict) this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.:

save(to_save[, manipulate=True[, safe=False[, **kwargs]]])

Save a document in this collection.

If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

VIM Disable Automatic Newline At End Of File

Try to add in .vimrc

set binary

How to Extract Year from DATE in POSTGRESQL

answer is;

select date_part('year', timestamp '2001-02-16 20:38:40') as year,
       date_part('month', timestamp '2001-02-16 20:38:40') as month,
       date_part('day', timestamp '2001-02-16 20:38:40') as day,
       date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
       date_part('minute', timestamp '2001-02-16 20:38:40') as minute

Pythonic way to check if a list is sorted or not

Actually we are not giving the answer anijhaw is looking for. Here is the one liner:

all(l[i] <= l[i+1] for i in xrange(len(l)-1))

For Python 3:

all(l[i] <= l[i+1] for i in range(len(l)-1))

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

With Eclipse Collections, the method removeIf defined on MutableCollection will work:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.lessThan(3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

With Java 8 Lambda syntax this can be written as follows:

MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);
list.removeIf(Predicates.cast(integer -> integer < 3));
Assert.assertEquals(Lists.mutable.of(3, 4, 5), list);

The call to Predicates.cast() is necessary here because a default removeIf method was added on the java.util.Collection interface in Java 8.

Note: I am a committer for Eclipse Collections.

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

How to connect to a secure website using SSL in Java with a pkcs12 file?

The following steps will help you to sort your problem out.

Steps: developer_identity.cer <= download from Apple mykey.p12 <= Your private key

Commands to follow:

    openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM

    openssl pkcs12 -nocerts -in mykey.p12 -out mykey.pem

    openssl pkcs12 -export -inkey mykey.pem -in developer_identity.pem -out iphone_dev.p12

Final p12 that we will require is iphone_dev.p12 file and the passphrase.

use this file as your p12 and then try. This indeed is the solution.:)

EventListener Enter Key

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

How do I download a binary file over HTTP?

The simplest way is the platform-specific solution:

 #!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`

Probably you are searching for:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

Edit: Changed. Thank You.

Edit2: The solution which saves part of a file while downloading:

# instead of http.get
f = open('sample.flv')
begin
    http.request_get('/sample.flv') do |resp|
        resp.read_body do |segment|
            f.write(segment)
        end
    end
ensure
    f.close()
end

How to check if a double is null?

How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().

Get User's Current Location / Coordinates

you should do those steps:

  1. add CoreLocation.framework to BuildPhases -> Link Binary With Libraries (no longer necessary as of XCode 7.2.1)
  2. import CoreLocation to your class - most likely ViewController.swift
  3. add CLLocationManagerDelegate to your class declaration
  4. add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to plist
  5. init location manager:

    locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
    
  6. get User Location By:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
    

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

Remove a specific string from an array of string

import java.util.*;

class Array {
    public static void main(String args[]) {
        ArrayList al = new ArrayList();
        al.add("google");
        al.add("microsoft");
        al.add("apple");
        System.out.println(al);
        //i only remove the apple//
        al.remove(2);
        System.out.println(al);
    }
}

C/C++ switch case with string

Just use a if() { } else if () { } chain. Using a hash value is going to be a maintenance nightmare. switch is intended to be a low-level statement which would not be appropriate for string comparisons.

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

Read/Write 'Extended' file properties (C#)

This sample in VB.NET reads all extended properties:

Sub Main()
        Dim arrHeaders(35)

        Dim shell As New Shell32.Shell
        Dim objFolder As Shell32.Folder

        objFolder = shell.NameSpace("C:\tmp")

        For i = 0 To 34
            arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
        Next
        For Each strFileName In objfolder.Items
            For i = 0 To 34
                Console.WriteLine(i & vbTab & arrHeaders(i) & ": " & objfolder.GetDetailsOf(strFileName, i))
            Next
        Next

    End Sub

You have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

Convert laravel object to array

It's also possible to typecast an object to an array. That worked for me here.

(array) $object;

will convert

stdClass Object
(
    [id] => 4
)

to

Array(
    [id] => 4
)

Had the same problem when trying to pass data from query builder to a view. Since data comes as object. So you can do:

$view = view('template', (array) $object);

And in your view you use variables like

{{ $id }}

Can't check signature: public key not found

There is a similar problem.it is a tomcat digital signature.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows- 
x64.zip
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key

but then I use the RSA key it provided to receive the public key to verify.

$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1

Then successfully.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987  5A51 10C0 1C5A 2F60 59E7

illegal character in path

You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?

This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.

You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a @):

  string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";

Or:

  string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";

Java associative-array

Actually Java does support associative arrays they are called dictionaries!

How to replace � in a string

You are asking to replace the character "?" but for me that is coming through as three characters 'ï', '¿' and '½'. This might be your problem... If you are using Java prior to Java 1.5 then you only get the UCS-2 characters, that is only the first 65K UTF-8 characters. Based on other comments, it is most likely that the character that you are looking for is '?', that is the Unicode replacement character. This is the character that is "used to replace an incoming character whose value is unknown or unrepresentable in Unicode".

Actually, looking at the comment from Kathy, the other issue that you might be having is that javac is not interpreting your .java file as UTF-8, assuming that you are writing it in UTF-8. Try using:

javac -encoding UTF-8 xx.java

Or, modify your source code to do:

String.replaceAll("\uFFFD", "");

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

How to convert a String into an ArrayList?

 String s1="[a,b,c,d]";
 String replace = s1.replace("[","");
 System.out.println(replace);
 String replace1 = replace.replace("]","");
 System.out.println(replace1);
 List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
 System.out.println(myList.toString());

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

How do I correctly clone a JavaScript object?

In my code I frequently define a function (_) to handle copies so that I can pass by value to functions. This code creates a deep copy but maintains inheritance. It also keeps track of sub-copies so that self-referential objects can be copied without an infinite loop. Feel free to use it.

It might not be the most elegant, but it hasn't failed me yet.

_ = function(oReferance) {
  var aReferances = new Array();
  var getPrototypeOf = function(oObject) {
    if(typeof(Object.getPrototypeOf)!=="undefined") return Object.getPrototypeOf(oObject);
    var oTest = new Object();
    if(typeof(oObject.__proto__)!=="undefined"&&typeof(oTest.__proto__)!=="undefined"&&oTest.__proto__===Object.prototype) return oObject.__proto__;
    if(typeof(oObject.constructor)!=="undefined"&&typeof(oTest.constructor)!=="undefined"&&oTest.constructor===Object&&typeof(oObject.constructor.prototype)!=="undefined") return oObject.constructor.prototype;
    return Object.prototype;
  };
  var recursiveCopy = function(oSource) {
    if(typeof(oSource)!=="object") return oSource;
    if(oSource===null) return null;
    for(var i=0;i<aReferances.length;i++) if(aReferances[i][0]===oSource) return aReferances[i][1];
    var Copy = new Function();
    Copy.prototype = getPrototypeOf(oSource);
    var oCopy = new Copy();
    aReferances.push([oSource,oCopy]);
    for(sPropertyName in oSource) if(oSource.hasOwnProperty(sPropertyName)) oCopy[sPropertyName] = recursiveCopy(oSource[sPropertyName]);
    return oCopy;
  };
  return recursiveCopy(oReferance);
};

// Examples:
Wigit = function(){};
Wigit.prototype.bInThePrototype = true;
A = new Wigit();
A.nCoolNumber = 7;
B = _(A);
B.nCoolNumber = 8; // A.nCoolNumber is still 7
B.bInThePrototype // true
B instanceof Wigit // true

Include PHP file into HTML file

In order to get the PHP output into the HTML file you need to either

  • Change the extension of the HTML to file to PHP and include the PHP from there (simple)
  • Load your HTML file into your PHP as a kind of template (a lot of work)
  • Change your environment so it deals with HTML as if it was PHP (bad idea)

Should a function have only one return statement?

I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.

There is no law requiring only one exit point for a method in all programming languages. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research.

More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and try..finally blocks (and using blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation.

There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.

Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.

I have talked about this at greater length on my blog.

Switching between GCC and Clang/LLVM using CMake

You can use the toolchain file mechanism of cmake for this purpose, see e.g. here. You write a toolchain file for each compiler containing the corresponding definitions. At config time, you run e.g

 cmake -DCMAKE_TOOLCHAIN_FILE=/path/to/clang-toolchain.cmake ..

and all the compiler information will be set during the project() call from the toolchain file. Though in the documentation is mentionend only in the context of cross-compiling, it works as well for different compilers on the same system.

How to create cross-domain request?

In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

  • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
  • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

200 OK HTTP/1.1
(...)
Access-Control-Allow-Origin: *

To debug such issues, you can use developer tools within browsers (Network tab).

Regarding Angular2, simply use the Http object like any other requests (same domain for example):

return this.http.get('https://angular2.apispark.net/v1/companies/')
           .map(res => res.json()).subscribe(
  ...
);

ADB Android Device Unauthorized

it's not may work for all situations but because i used a long cable my device doesnt connect properly and the message wont pop up change the cable may solve the problem

ExecutorService that interrupts tasks after a timeout

How about using the ExecutorService.shutDownNow() method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.

Should switch statements always contain a default clause?

Switch cases should almost always have a default case.

Reasons to use a default

1.To 'catch' an unexpected value

switch(type)
{
    case 1:
        //something
    case 2:
        //something else
    default:
        // unknown type! based on the language,
        // there should probably be some error-handling
        // here, maybe an exception
}

2. To handle 'default' actions, where the cases are for special behavior.

You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.

3. To show someone reading your code that you've covered that case.

variable = (variable == "value") ? 1 : 2;
switch(variable)
{
    case 1:
        // something
    case 2:
        // something else
    default:
        // will NOT execute because of the line preceding the switch.
}

This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable cannot be something other than 1 or 2.


The only case I can think of to NOT use default is when the switch is checking something where its rather obvious every other alternative can be happily ignored

switch(keystroke)
{
    case 'w':
        // move up
    case 'a':
        // move left
    case 's':
        // move down
    case 'd':
        // move right
    // no default really required here
}

C compile error: Id returned 1 exit status

1d returned 1 exit status error

First of all you have to create a project by clicking file new and then project and give project name select the language c or c++ and select empty also. Then your program is under that project... And then give a program name save it.... Ensure that your under some project to compile and run a program...

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

BYTE *str1 = "Hello World";
std::string str2((char *)str1);  /* construct on the stack */

Alternatively:

std::string *str3 = new std::string((char *)str1); /* construct on the heap */
cout << &str3;
delete str3;

Keeping ASP.NET Session Open / Alive

I spent a few days trying to figure out how to prolong a users session in WebForms via a popup dialog giving the user the option to renew the session or to allow it to expire. The #1 thing that you need to know is that you don't need any of this fancy 'HttpContext' stuff going on in some of the other answers. All you need is jQuery's $.post(); method. For example, while debugging I used:

$.post("http://localhost:5562/Members/Location/Default.aspx");

and on your live site you would use something like:

$.post("http://mysite/Members/Location/Default.aspx");

It's as easy as that. Furthermore, if you'd like to prompt the user with the option to renew their session do something similar to the following:

    <script type="text/javascript">
    $(function () { 
        var t = 9;
        var prolongBool = false;
        var originURL = document.location.origin;
        var expireTime = <%= FormsAuthentication.Timeout.TotalMinutes %>;

        // Dialog Counter
        var dialogCounter = function() {
            setTimeout( function() {
                $('#tickVar').text(t);
                    t--;
                    if(t <= 0 && prolongBool == false) {
                        var originURL = document.location.origin;
                        window.location.replace(originURL + "/timeout.aspx");
                        return;
                    }
                    else if(t <= 0) {
                        return;
                    }
                    dialogCounter();
            }, 1000);
        }

        var refreshDialogTimer = function() {
            setTimeout(function() { 
                $('#timeoutDialog').dialog('open');
            }, (expireTime * 1000 * 60 - (10 * 1000)) );
        };

        refreshDialogTimer();

        $('#timeoutDialog').dialog({
            title: "Session Expiring!",
            autoOpen: false,
            height: 170,
            width: 350,
            modal: true,
            buttons: {
                'Yes': function () {
                    prolongBool = true;
                    $.post("http://localhost:5562/Members/Location/Default.aspx"); 
                    refreshDialogTimer();
                    $(this).dialog("close");
                },
                Cancel: function () {
                    var originURL = document.location.origin;
                    window.location.replace(originURL + "/timeout.aspx");
                }
            },
            open: function() {
                prolongBool = false;
                $('#tickVar').text(10);
                t = 9;
                dialogCounter();
            }
        }); // end timeoutDialog
    }); //End page load
</script>

Don't forget to add the Dialog to your html:

        <div id="timeoutDialog" class='modal'>
            <form>
                <fieldset>
                    <label for="timeoutDialog">Your session will expire in</label>
                    <label for="timeoutDialog" id="tickVar">10</label>
                    <label for="timeoutDialog">seconds, would you like to renew your session?</label>
                </fieldset>
            </form>
        </div>

How to get only the date value from a Windows Forms DateTimePicker control?

I'm assuming you mean a datetime picker in a winforms application.

in your code, you can do the following:

string theDate = dateTimePicker1.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

Escape single quote character for use in an SQLite query

Try doubling up the single quotes (many databases expect it that way), so it would be :

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');

Relevant quote from the documentation:

A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. BLOB literals are string literals containing hexadecimal data and preceded by a single "x" or "X" character. ... A literal value can also be the token "NULL".

How to display Oracle schema size with SQL query?

select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc

See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options

How to retrieve field names from temporary table (SQL Server 2008)

The temporary tables are defined in "tempdb", and the table names are "mangled".

This query should do the trick:

select c.*
from tempdb.sys.columns c
inner join tempdb.sys.tables t ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

Marc

JS search in object values

MAKE SIMPLE

const objects = [
     {
     "foo" : "bar",
     "bar" : "sit",
     "date":"2020-12-20"
     },
     {
     "foo" : "lorem",
     "bar" : "ipsum",
     "date":"2018-07-02"
     },
     {
     "foo" : "dolor",
     "bar" : "amet",
     "date":"2003-10-08"
     },
     {
     "foo" : "lolor",
     "bar" : "amet",
     "date":"2003-10-08"
     }
     ];
     
     
     
     const filter = objects.filter(item => {
     const obj = Object.values(item)
     return obj.join("").indexOf('2003') !== -1
     })
     
     console.log(filter)

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

binning data in python with scipy/numpy

I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data

import numpy as np
from scipy.stats import binned_statistic_2d

x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic

the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Create a rounded button / button with border-radius in Flutter

You can simply use RaisedButton or you can use InkWell to get custom button and also properties like onDoubleTap, onLongPress and etc.:

new InkWell(
  onTap: () => print('hello'),
  child: new Container(
    //width: 100.0,
    height: 50.0,
    decoration: new BoxDecoration(
      color: Colors.blueAccent,
      border: new Border.all(color: Colors.white, width: 2.0),
      borderRadius: new BorderRadius.circular(10.0),
    ),
    child: new Center(child: new Text('Click Me', style: new TextStyle(fontSize: 18.0, color: Colors.white),),),
  ),
),

enter image description here

If you want to use splashColor, highlightColor properties in InkWell widget, use Material widget as the parent of InkWell widget instead of decorating the container(deleting decoration property). Read why? here.

Is header('Content-Type:text/plain'); necessary at all?

Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.

Is there a function to round a float in C or do I need to write my own?

#include <math.h>

double round(double x);
float roundf(float x);

Don't forget to link with -lm. See also ceil(), floor() and trunc().

Imply bit with constant 1 or 0 in SQL Server

cast (
  case
    when FC.CourseId is not null then 1 else 0
  end
as bit)

The CAST spec is "CAST (expression AS type)". The CASE is an expression in this context.

If you have multiple such expressions, I'd declare bit vars @true and @false and use them. Or use UDFs if you really wanted...

DECLARE @True bit, @False bit;
SELECT @True = 1, @False = 0;  --can be combined with declare in SQL 2008

SELECT
    case when FC.CourseId is not null then @True ELSE @False END AS ...

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

Copy struct to struct in C

Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).

When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp; see How do you compare structs for equality in C?

Git Server Like GitHub?

You might consider Gitblit, an open-source, integrated, pure Java Git server, viewer, and repository manager for small workgroups.

How do you align left / right a div without using float?

It is dirty better use the overflow: hidden; hack:

<div class="container">
  <div style="float: left;">Left Div</div>
  <div style="float: right;">Right Div</div>
</div>

.container { overflow: hidden; }

Or if you are going to do some fancy CSS3 drop-shadow stuff and you get in trouble with the above solution:

http://web.archive.org/web/20120414135722/http://fordinteractive.com/2009/12/goodbye-overflow-clearing-hack

PS

If you want to go for clean I would rather worry about that inline javascript rather than the overflow: hidden; hack :)

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

Fail during installation of Pillow (Python module) in Linux

brew install zlib

on OS X doesn't work anymore and instead prompts to install lzlib. Installing that doesn't help.

Instead you install XCode Command line tools and that should install zlib

xcode-select --install

Partly JSON unmarshal into a map in Go

Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

C++ Structure Initialization

I might be missing something here, by why not:

#include <cstdio>    
struct Group {
    int x;
    int y;
    const char* s;
};

int main() 
{  
  Group group {
    .x = 1, 
    .y = 2, 
    .s = "Hello it works"
  };
  printf("%d, %d, %s", group.x, group.y, group.s);
}

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

How do I programmatically "restart" an Android app?

There is a really nice trick. My problem was that some really old C++ jni library leaked resources. At some point, it stopped functioning. The user tried to exit the app and launch it again -- with no result, because finishing an activity is not the same as finishing (or killing) the process. (By the way, the user could go to the list of the running applications and stop it from there -- this would work, but the users just do not know how to terminate applications.)

If you want to observe the effect of this feature, add a static variable to your activity and increment it each, say, button press. If you exit the application activity and then invoke the application again, this static variable will keep its value. (If the application really was exited, the variable would be assigned the initial value.)

(And I have to comment on why I did not want to fix the bug instead. The library was written decades ago and leaked resources ever since. The management believes it always worked. The cost of providing a fix instead of a workaround... I think, you get the idea.)

Now, how could I reset a jni shared (a.k.a. dynamic, .so) library to the initial state? I chose to restart application as a new process.

The trick is that System.exit() closes the current activity and Android recreates the application with one activity less.

So the code is:

/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
    // Do not forget to add it to AndroidManifest.xml
    // <activity android:name="your.package.name.MagicAppRestart"/>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.exit(0);
    }
    public static void doRestart(Activity anyActivity) {
        anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
    }
}

The calling activity just executes the code MagicAppRestart.doRestart(this);, the calling activity's onPause() is executed, and then the process is re-created. And do not forget to mention this activity in AndroidManifest.xml

The advantage of this method is that there is no delays.

UPD: it worked in Android 2.x, but in Android 4 something has changed.

Quickest way to compare two generic lists for differences

I have used this code to compare two list which has million of records.

This method will not take much time

    //Method to compare two list of string
    private List<string> Contains(List<string> list1, List<string> list2)
    {
        List<string> result = new List<string>();

        result.AddRange(list1.Except(list2, StringComparer.OrdinalIgnoreCase));
        result.AddRange(list2.Except(list1, StringComparer.OrdinalIgnoreCase));

        return result;
    }

Can't use method return value in write context

I usually create a global function called is_empty() just to get around this issue

function is_empty($var)
{ 
 return empty($var);
}

Then anywhere I would normally have used empty() I just use is_empty()

Difference between agile and iterative and incremental development

Incremental development means that different parts of a software project are continuously integrated into the whole, instead of a monolithic approach where all the different parts are assembled in one or a few milestones of the project.

Iterative means that once a first version of a component is complete it is tested, reviewed and the results are almost immediately transformed into a new version (iteration) of this component.

So as a first result: iterative development doesn't need to be incremental and vice versa, but these methods are a good fit.

Agile development aims to reduce massive planing overhead in software projects to allow fast reactions to change e.g. in customer wishes. Incremental and iterative development are almost always part of an agile development strategy. There are several approaches to Agile development (e.g. scrum).

How to overcome "'aclocal-1.15' is missing on your system" warning?

The whole point of Autotools is to provide an arcane M4-macro-based language which ultimately compiles to a shell script called ./configure. You can ship this compiled shell script with the source code and that script should do everything to detect the environment and prepare the program for building. Autotools should only be required by someone who wants to tweak the tests and refresh that shell script.

It defeats the point of Autotools if GNU This and GNU That has to be installed on the system for it to work. Originally, it was invented to simplify the porting of programs to various Unix systems, which could not be counted on to have anything on them. Even the constructs used by the generated shell code in ./configure had to be very carefully selected to make sure they would work on every broken old shell just about everywhere.

The problem you're running into is due to some broken Makefile steps invented by people who simply don't understand what Autotools is for and the role of the final ./configure script.

As a workaround, you can go into the Makefile and make some changes to get this out of the way. As an example, I'm building the Git head of GNU Awk and running into this same problem. I applied this patch to Makefile.in, however, and I can sucessfully make gawk:

diff --git a/Makefile.in b/Makefile.in

index 5585046..b8b8588 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -312,12 +312,12 @@ distcleancheck_listfiles = find . -type f -print

 # Directory for gawk's data files. Automake supplies datadir.
 pkgdatadir = $(datadir)/awk
-ACLOCAL = @ACLOCAL@
+ACLOCAL = true
 AMTAR = @AMTAR@
 AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
+AUTOCONF = true
+AUTOHEADER = true
+AUTOMAKE = true
 AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@

Basically, I changed things so that the harmless true shell command is substituted for all the Auto-stuff programs.

The actual build steps for Gawk don't need the Auto-stuff! It's only involved in some rules that get invoked if parts of the Auto-stuff have changed and need to be re-processed. However, the Makefile is structured in such a way that it fails if the tools aren't present.

Before the above patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /home/kaz/gawk/missing aclocal-1.15 -I m4
/home/kaz/gawk/missing: line 81: aclocal-1.15: command not found
WARNING: 'aclocal-1.15' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127

After the patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && true -I m4
CDPATH="${ZSH_VERSION+.}:" && cd . && true
gcc -std=gnu99 -DDEFPATH='".:/usr/local/share/awk"' -DDEFLIBPATH="\"/usr/local/lib/gawk\"" -DSHLIBEXT="\"so"\" -DHAVE_CONFIG_H -DGAWK -DLOCALEDIR='"/usr/local/share/locale"' -I.     -g -O2 -DNDEBUG -MT array.o -MD -MP -MF .deps/array.Tpo -c -o array.o array.c 
[...]
gcc -std=gnu99  -g -O2 -DNDEBUG  -Wl,-export-dynamic -o gawk array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o      -ldl -lm
$ ./gawk --version
GNU Awk 4.1.60, API: 1.2
Copyright (C) 1989, 1991-2015 Free Software Foundation.
[...]

There we go. As you can see, the CDPATH= command lines there are where the Auto-stuff was being invoked, where you see the true commands. These report successful termination, and so it just falls through that junk to do the darned build, which is perfectly configured.

I did make gawk because there are some subdirectories that get built which fail; the trick has to be repeated for their respective Makefiles.

If you're running into this kind of thing with a pristine, official tarball of the program from its developers, then complain. It should just unpack, ./configure and make without you having to patch anything or install any Automake or Autoconf materials.

Ideally, a pull of their Git head should also behave that way.

How do I restore a dump file from mysqldump?

If the database you want to restore doesn't already exist, you need to create it first.

On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions):

C:\> mysql -u root -p

mysql> create database mydb;
mysql> use mydb;
mysql> source db_backup.dump;

How can I change my Cygwin home folder after installation?

Cygwin mount now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab, then restart your shell:

c:/Users /home none bind 0 0

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

Get Specific Columns Using “With()” Function in Laravel Eloquent

Try with conditions.

$id = 1;
Post::with(array('user'=>function($query) use ($id){
    $query->where('id','=',$id);
    $query->select('id','username');
}))->get();

Modify property value of the objects in list using Java 8 streams

You can use peek to do that.

List<Fruit> newList = fruits.stream()
    .peek(f -> f.setName(f.getName() + "s"))
    .collect(Collectors.toList());

How to display request headers with command line curl

A popular answer for displaying response headers, but OP asked about request headers.

curl -s -D - -o /dev/null http://example.com
  • -s : Avoid showing progress bar
  • -D - : Dump headers to a file, but - sends it to stdout
  • -o /dev/null : Ignore response body

This is better than -I as it doesn't send a HEAD request, which can produce different results.

It's better than -v because you don't need so many hacks to un-verbose it.

How to get a value from a cell of a dataframe?

Converting it to integer worked for me:

int(sub_df.iloc[0])

How do I convert an object to an array?

Careful:

$array = (array) $object;

does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.

If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }

    return $new;
}

How to specify a multi-line shell variable?

read does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.

I use it like this

export LS_COLORS=$(printf %s    \
    ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33'   \
    ...
    ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')

in a file sourced from both my .bashrc and .zshrc.

Get JavaScript object from array of objects by value of property

How about using _.find(collection, [predicate=_.identity], [fromIndex=0]) of lo-dash to get object from array of objects by object property value. You could do something like this:

var o = _.find(jsObjects, {'b': 6});

Arguments:

collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.

Returns

(*): Returns the matched element (in your case, {a: 5, b: 6}), else undefined.

In terms of performance, _.find() is faster as it only pulls the first object with property {'b': 6}, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using _.filter() method. So in your case, as your array has a single object with this property, I would use _.find().

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

How to check command line parameter in ".bat" file?

You are comparing strings. If an arguments are omitted, %1 expands to a blank so the commands become IF =="-b" GOTO SPECIFIC for example (which is a syntax error). Wrap your strings in quotes (or square brackets).

REM this is ok
IF [%1]==[/?] GOTO BLANK

REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC

IF NOT "%1"=="-b" GOTO UNKNOWN

AngularJS HTTP post to PHP and undefined

This is the best solution (IMO) as it requires no jQuery and no JSON decode:

Source: https://wordpress.stackexchange.com/a/179373 and: https://stackoverflow.com/a/1714899/196507

Summary:

//Replacement of jQuery.param
var serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
};

//Your AngularJS application:
var app = angular.module('foo', []);

app.config(function ($httpProvider) {
    // send all requests payload as query string
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return serialize(data);
    };

    // set all post requests content type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Example:

...
   var data = { id: 'some_id', name : 'some_name' };
   $http.post(my_php_url,data).success(function(data){
        // It works!
   }).error(function() {
        // :(
   });

PHP code:

<?php
    $id = $_POST["id"];
?>

How do I get hour and minutes from NSDate?

With iOS 8, Apple introduced a helper method to retrieve the hour, minute, second and nanosecond from an NSDate object.

Objective-C

NSDate *date = [NSDate currentDate];
NSInteger hour = 0;
NSInteger minute = 0;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
[currentCalendar getHour:&hour minute:&minute second:NULL nanosecond:NULL fromDate:date];
NSLog(@"the hour is %ld and minute is %ld", (long)hour, (long)minute);

Swift

let date = NSDate()
var hour = 0
var minute = 0
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
    calendar.getHour(&hour, minute: &minute, second: nil, nanosecond: nil, fromDate: date)
    print("the hour is \(hour) and minute is \(minute)")
}

php exec command (or similar) to not wait for result

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');

Convert UNIX epoch to Date object

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.

Where can I find error log files?

For unix cli users:

Most probably the error_log ini entry isn't set. To verify:

php -i | grep error_log
// error_log => no value => no value

You can either set it in your php.ini cli file, or just simply quickly pipe all STDERR yourself to a file:

./myprog 2> myerror.log

Then quickly:

tail -f myerror.log

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

You need to first enable query logging

DB::enableQueryLog();

Then you can get query logs by simply:

dd(DB::getQueryLog());

It would be better if you enable query logging before application starts, which you can do in a BeforeMiddleware and then retrieve the executed queries in AfterMiddleware.

Using sessions & session variables in a PHP Login Script

You need to begin the session at the top of a page or before you call session code

session_start(); 

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

How to save user input into a variable in html and js

Like I use on PHP and JavaScript:

<input type="hidden" id="CatId" value="<?php echo $categoryId; ?>">

Update the JavaScript:

var categoryId = document.getElementById('CatId').value;

Find files in a folder using Java

  • Matcher.find and Files.walk methods could be an option to search files in more flexible way
  • String.format combines regular expressions to create search restrictions
  • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

Usage:

//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                       stream().forEach(System.out::println);

Source:

public final class PathUtils {

    private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
    private static final String endsWithRegex = "(?=[\\.\\n])";
    private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";

    public static List<Path> searchRegularFilesStartsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
    }

    public static List<Path> searchRegularFilesEndsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
    }

    public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
        return searchRegularFiles(initialPath, "", "");
    }

    public static List<Path> searchRegularFiles(final Path initialPath,
                             final String fileName, final String fileExt)
            throws IOException {
        final String regex = String.format(containsRegex, fileName, fileExt);
        final Pattern pattern = Pattern.compile(regex);
        try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
            return walk.filter(path -> Files.isRegularFile(path) &&
                                       pattern.matcher(path.toString()).find())
                    .collect(Collectors.toList());
        }
    }

    private PathUtils() {
    }
}

Try startsWith regex for \txt\temp\tempZERO0.txt:

(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try endsWith regex for \txt\temp\ZERO0temp.txt:

temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Required attribute HTML5

Safari 7.0.5 still does not support notification for validation of input fields.

To overcome it is possible to write fallback script like this: http://codepen.io/ashblue/pen/KyvmA

To see what HTML5 / CSS3 features are supported by browsers check: http://caniuse.com/form-validation

function hasHtml5Validation () {
  //Check if validation supported && not safari
  return (typeof document.createElement('input').checkValidity === 'function') && 
    !(navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0);
}

$('form').submit(function(){
    if(!hasHtml5Validation())
    {
        var isValid = true;
        var $inputs = $(this).find('[required]');
        $inputs.each(function(){
            var $input = $(this);
            $input.removeClass('invalid');
            if(!$.trim($input.val()).length)
            {
                isValid = false;
                $input.addClass('invalid');                 
            }
        });
        if(!isValid)
        {
            return false;
        }
    }
});

SASS / LESS:

input, select, textarea {
    @include appearance(none);
    border-radius: 0px;

    &.invalid {
        border-color: red !important;
    }
}

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

Symfony - generate url with parameter in controller

If you want absolute urls, you have the third parameter.

$product_url = $this->generateUrl('product_detail', 
    array(
        'slug' => 'slug'
    ),
    UrlGeneratorInterface::ABSOLUTE_URL
);

Remember to include UrlGeneratorInterface.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

"CSV file does not exist" for a filename with embedded quotes

I also experienced the same problem I solved as follows:

dataset = pd.read_csv('C:\\Users\\path\\to\\file.csv')

Swift - how to make custom header for UITableView?

If you are willing to use custom table header as table header, try the followings....

Updated for swift 3.0

Step 1

Create UITableViewHeaderFooterView for custom header..

import UIKit

class MapTableHeaderView: UITableViewHeaderFooterView {

    @IBOutlet weak var testView: UIView!

}

Step 2

Add custom header to UITableView

    override func viewDidLoad() {
            super.viewDidLoad()

            tableView.delegate = self
            tableView.dataSource = self

            //register the header view

            let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
            self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")


    }

    extension BranchViewController : UITableViewDelegate{

    }

    extension BranchViewController : UITableViewDataSource{

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 200
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView

            return headerView
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: 

    Int) -> Int {
            // retuen no of rows in sections
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
            // retuen your custom cells    
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        }

        func numberOfSections(in tableView: UITableView) -> Int {
            // retuen no of sections
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            // retuen height of row
        }


    }

Get Number of Rows returned by ResultSet in Java

Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery("select * from emp where deptno=31");
rs.last();
System.out.println("NoOfRows: "+rs.getRow());

first line of code says that we can move anywhere in the resultset( either to first row or last row or before first row without the need to traverse row by row starting from first row which is time taking).second line of code fetches the records matching the query here i am assuming (25 records), third line of code moves cursor to last row and final line of code gets the current row number which is 25 in my case. if there are no records, rs.last returns 0 and getrow moves cursor to before first row hence returning negative value indicates no records in db

Create unique constraint with null columns

You could create a unique index with a coalesce on the MenuId:

CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);

You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):

alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')

PHP array delete by value (not key)

As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

Input:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

How to assign a select result to a variable?

Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.

UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey 
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'

Hibernate: best practice to pull all lazy collections

Not the best solution, but here is what I got:

1) Annotate getter you want to initialize with this annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {

}

2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:

    public <T> void forceLoadLazyCollections(T entity) {

    Session session = getSession().openSession();
    Transaction tx = null;
    try {

        tx = session.beginTransaction();
        session.refresh(entity);
        if (entity == null) {
            throw new RuntimeException("Entity is null!");
        }
        for (Method m : entityClass.getMethods()) {

            Lazy annotation = m.getAnnotation(Lazy.class);
            if (annotation != null) {
                m.setAccessible(true);
                logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
                try {
                    Hibernate.initialize(m.invoke(entity));
                }
                catch (Exception e) {
                    logger.warn("initialization exception", e);
                }
            }
        }

    }
    finally {
        session.close();
    }
}

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

In my case, I could not even open "References" in the Visual Basic window. I even tried reinstalling Office 365 and that didn't work. Finally, I tried disabling macros in the "Trust Center" settings. When I restarted Excel, I got the warning message that macros were disabled, and when I clicked on "enable" I no longer got the error message.

Later I re-enabled all macros in the "Trust Center" settings, and the error message didn't show up!

Hey, if nothing else works for you, try the above; it worked for me! :)

Update: The issue returned, and this is how I "fixed" it the second time:

I opened my workbook in Excel online (Office 365, in the browser, which doesn't support macros anyway), saved it with a new file name (still using .xlsm file extension), and reopened in the desktop software. It worked.

RegEx - Match Numbers of Variable Length

{[0-9]+:[0-9]+}

try adding plus(es)

Redirect all output to file using Bash on Linux?

If the server is started on the same terminal, then it's the server's stderr that is presumably being written to the terminal and which you are not capturing.

The best way to capture everything would be to run:

script output.txt

before starting up either the server or the client. This will launch a new shell with all terminal output redirected out output.txt as well as the terminal. Then start the server from within that new shell, and then the client. Everything that you see on the screen (both your input and the output of everything writing to the terminal from within that shell) will be written to the file.

When you are done, type "exit" to exit the shell run by the script command.

how to make password textbox value visible when hover an icon

1 minute googling gave me this result. See the DEMO!

HTML

<form>
    <label for="username">Username:</label>
    <input id="username" name="username" type="text" placeholder="Username" />
    <label for="password">Password:</label>
    <input id="password" name="password" type="password" placeholder="Password" />
    <input id="submit" name="submit" type="submit" value="Login" />
</form>

jQuery

// ----- Setup: Add dummy text field for password and add toggle link to form; "offPage" class moves element off-screen
$('input[type=password]').each(function () {
    var el = $(this),
        elPH = el.attr("placeholder");
    el.addClass("offPage").after('<input class="passText" placeholder="' + elPH + '" type="text" />');
});
$('form').append('<small><a class="togglePassText" href="#">Toggle Password Visibility</a></small>');

// ----- keep password field and dummy text field in sync
$('input[type=password]').keyup(function () {
    var elText = $(this).val();
    $('.passText').val(elText);
});
$('.passText').keyup(function () {
    var elText = $(this).val();
    $('input[type=password]').val(elText);
});

// ----- Toggle link functionality - turn on/off "offPage" class on fields
$('a.togglePassText').click(function (e) {
    $('input[type=password], .passText').toggleClass("offPage");
    e.preventDefault(); // <-- prevent any default actions
});

CSS

.offPage {
    position: absolute;
    bottom: 100%;
    right: 100%;
}

How do I mock a REST template exchange?

This work on my side.

ResourceBean resourceBean = initResourceBean();
ResponseEntity<ResourceBean> responseEntity  
    = new ResponseEntity<ResourceBean>(resourceBean, HttpStatus.ACCEPTED);
when(restTemplate.exchange(
    Matchers.anyObject(), 
    Matchers.any(HttpMethod.class),
    Matchers.<HttpEntity> any(), 
    Matchers.<Class<ResourceBean>> any())
 ).thenReturn(responseEntity);

How do I fix PyDev "Undefined variable from import" errors?

The post marked as answer gives a workaround, not a solution.

This solution works for me:

  • Go to Window - Preferences - PyDev - Interpreters - Python Interpreter
  • Go to the Forced builtins tab
  • Click on New...
  • Type the name of the module (multiprocessing in my case) and click OK

Not only will the error messages disappear, the module members will also be recognized.

In a Dockerfile, How to update PATH environment variable?

[I mentioned this in response to the selected answer, but it was suggested to make it more prominent as an answer of its own]

It should be noted that

ENV PATH="/opt/gtk/bin:${PATH}" 

may not be the same as

ENV PATH="/opt/gtk/bin:$PATH" 

The former, with curly brackets, might provide you with the host's PATH. The documentation doesn't suggest this would be the case, but I have observed that it is. This is simple to check just do RUN echo $PATH and compare it to RUN echo ${PATH}

What is the most efficient string concatenation method in python?

I ran into a situation where I needed to have an appendable string of unknown size. These are the benchmark results (python 2.7.3):

$ python -m timeit -s 's=""' 's+="a"'
10000000 loops, best of 3: 0.176 usec per loop
$ python -m timeit -s 's=[]' 's.append("a")'
10000000 loops, best of 3: 0.196 usec per loop
$ python -m timeit -s 's=""' 's="".join((s,"a"))'
100000 loops, best of 3: 16.9 usec per loop
$ python -m timeit -s 's=""' 's="%s%s"%(s,"a")'
100000 loops, best of 3: 19.4 usec per loop

This seems to show that '+=' is the fastest. The results from the skymind link are a bit out of date.

(I realize that the second example is not complete, the final list would need to be joined. This does show, however, that simply preparing the list takes longer than the string concat.)

How to make a hyperlink in telegram without using bots?

As of Telegram Desktop 1.3 you can format your messages and add links.

[Ctrl+K] = create link (https://my.website)

Other useful hotkeys are:

[Ctrl+B] = bold
[Ctrl+I] = italic
[Ctrl+Shift+M] = monospace
[Ctrl+Shift+N] = clear formatting

What is the difference between "px", "dip", "dp" and "sp"?

You can see the difference between px and dp from the below picture, and you can also find that the px and dp could not guarantee the same physical sizes on the different screens.

enter image description here

Iterating over Typescript Map

On Typescript 3.5 and Angular 8 LTS, it was required to cast the type as follows:

for (let [k, v] of Object.entries(someMap)) {
    console.log(k, v)
}

How can I make my own event in C#?

Here's an example of creating and using an event with C#

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

How can I test an AngularJS service from the console?

First of all, a modified version of your service.

a )

var app = angular.module('app',[]);

app.factory('ExampleService',function(){
    return {
        f1 : function(world){
            return 'Hello' + world;
        }
    };
});

This returns an object, nothing to new here.

Now the way to get this from the console is

b )

var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");

c )

One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

app.factory('ExampleService',function(){
        return function(){
            this.f1 = function(world){
                return 'Hello' + world;
            }
        };
    });

This returns an ExampleService constructor which you will next have to do a 'new' on.

Or alternatively,

app.service('ExampleService',function(){
            this.f1 = function(world){
                return 'Hello' + world;
            };
    });

This returns new ExampleService() on injection.

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception - but only while running in debug mode, this is how I solved the problem (after 3 whole days): in the build.gradle i had : "multiDexEnabled true" set in the defaultConfig section.

        defaultConfig {
    applicationId "com.xxx.yyy"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 5123
    versionName "5123"
    // Enabling multidex support.
    multiDexEnabled true
}

but apparently this wasn't enough. but when i changed:

public class MyAppClass  extends Application 

to:

public class MyAppClass  extends MultiDexApplication 

this solved it. hope this will help someone

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

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

It's been awhile since I've done anything with batch files but I think that the following works:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done

This is really a proof of concept; clean up as it suits your needs. The key is that find returns an errorlevel of 1 if string is not in file. We branch to notfound in this case otherwise we handle the found case.

C# binary literals

Adding to @StriplingWarrior's answer about bit flags in enums, there's an easy convention you can use in hexadecimal for counting upwards through the bit shifts. Use the sequence 1-2-4-8, move one column to the left, and repeat.

[Flags]
enum Scenery
{
  Trees   = 0x001, // 000000000001
  Grass   = 0x002, // 000000000010
  Flowers = 0x004, // 000000000100
  Cactus  = 0x008, // 000000001000
  Birds   = 0x010, // 000000010000
  Bushes  = 0x020, // 000000100000
  Shrubs  = 0x040, // 000001000000
  Trails  = 0x080, // 000010000000
  Ferns   = 0x100, // 000100000000
  Rocks   = 0x200, // 001000000000
  Animals = 0x400, // 010000000000
  Moss    = 0x800, // 100000000000
}

Scan down starting with the right column and notice the pattern 1-2-4-8 (shift) 1-2-4-8 (shift) ...


To answer the original question, I second @Sahuagin's suggestion to use hexadecimal literals. If you're working with binary numbers often enough for this to be a concern, it's worth your while to get the hang of hexadecimal.

If you need to see binary numbers in source code, I suggest adding comments with binary literals like I have above.

Create parameterized VIEW in SQL Server 2008

no. You can use UDF in which you can pass parameters.

How To Include CSS and jQuery in my WordPress plugin?

For styles wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );

Then use: wp_enqueue_style('namespace'); wherever you want the css to load.

Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery');

Unless of course you want to use the google repository for jquery.

You can also conditionally load the jquery library that your script is dependent on:

wp_enqueue_script('namespaceformyscript', 'http://locationofscript.com/myscript.js', array('jquery'));

Update Sept. 2017

I wrote this answer a while ago. I should clarify that the best place to enqueue your scripts and styles is within the wp_enqueue_scripts hook. So for example:

add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts() {
    wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
    wp_enqueue_style( 'namespace' );
    wp_enqueue_script( 'namespaceformyscript', 'http://locationofscript.com/myscript.js', array( 'jquery' ) );
}

The wp_enqueue_scripts action will set things up for the "frontend". You can use the admin_enqueue_scripts action for the backend (anywhere within wp-admin) and the login_enqueue_scripts action for the login page.

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

You need to store the returned function and call it to unsubscribe from the event.

var deregisterListener = $scope.$on("onViewUpdated", callMe);
deregisterListener (); // this will deregister that listener

This is found in the source code :) at least in 1.0.4. I'll just post the full code since it's short

/**
  * @param {string} name Event name to listen on.
  * @param {function(event)} listener Function to call when the event is emitted.
  * @returns {function()} Returns a deregistration function for this listener.
  */
$on: function(name, listener) {
    var namedListeners = this.$$listeners[name];
    if (!namedListeners) {
      this.$$listeners[name] = namedListeners = [];
    }
    namedListeners.push(listener);

    return function() {
      namedListeners[indexOf(namedListeners, listener)] = null;
    };
},

Also, see the docs.

Rethrowing exceptions in Java without losing the stack trace

catch (WhateverException e) {
    throw e;
}

will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Spark Dataframe distinguish columns with duplicated name

if only the key column is the same in both tables then try using the following way (Approach 1):

left. join(right , 'key', 'inner')

rather than below(approach 2):

left. join(right , left.key == right.key, 'inner')

Pros of using approach 1:

  • the 'key' will show only once in the final dataframe
  • easy to use the syntax

Cons of using approach 1:

  • only help with the key column
  • Scenarios, wherein case of left join, if planning to use the right key null count, this will not work. In that case, one has to rename one of the key as mentioned above.

How do I determine height and scrolling position of window in jQuery?

Pure JS

window.innerHeight
window.scrollY

is more than 10x faster than jquery (and code has similar size):

enter image description here

Here you can perform test on your machine: https://jsperf.com/window-height-width

Beamer: How to show images as step-by-step images

This is a sample code I used to counter the problem.

\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

Jenkins Git Plugin: How to build specific tag?

I was able to do that by using the "branches to build" parameter:

Branch Specifier (blank for default): tags/[tag-name]

Replace [tag-name] by the name of your tag.

How to add pandas data to an existing csv file?

with open(filename, 'a') as f:
    df.to_csv(f, header=f.tell()==0)
  • Create file unless exists, otherwise append
  • Add header if file is being created, otherwise skip it

How do you add swap to an EC2 instance?

A fix for this problem is to add swap (i.e. paging) space to the instance.

Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however much more of it is available.

To add this extra space to your instance you type:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1

If you need more than 1024 then change that to something higher.

To enable it by default after reboot, add this line to /etc/fstab:

/var/swap.1   swap    swap    defaults        0   0

What is the difference between public, protected, package-private and private in Java?

The difference can be found in the links already provided but which one to use usually comes down to the "Principle of Least Knowledge". Only allow the least visibility that is needed.

How to pick just one item from a generator?

For picking just one element of a generator use break in a for statement, or list(itertools.islice(gen, 1))

According to your example (literally) you can do something like:

while True:
  ...
  if something:
      for my_element in myfunct():
          dostuff(my_element)
          break
      else:
          do_generator_empty()

If you want "get just one element from the [once generated] generator whenever I like" (I suppose 50% thats the original intention, and the most common intention) then:

gen = myfunct()
while True:
  ...
  if something:
      for my_element in gen:
          dostuff(my_element)
          break
      else:
          do_generator_empty()

This way explicit use of generator.next() can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration exception handling or extra default value comparisons.

The else: of for statement section is only needed if you want do something special in case of end-of-generator.

Note on next() / .next():

In Python3 the .next() method was renamed to .__next__() for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next() did not exist. And it was even discussed to move next() to the operator module (which would have been wise), because of its rare need and questionable inflation of builtin names.

Using next() without default is still very low-level practice - throwing the cryptic StopIteration like a bolt out of the blue in normal application code openly. And using next() with default sentinel - which best should be the only option for a next() directly in builtins - is limited and often gives reason to odd non-pythonic logic/readablity.

Bottom line: Using next() should be very rare - like using functions of operator module. Using for x in iterator , islice, list(iterator) and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next() is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break in for is conventional.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

function timeformat(date1) {
  var date=new Date(date1);
  var month = date.toLocaleString('en-us', { month: 'long' });
  var mdate  =date.getDate();
  var year  =date.getFullYear();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = mdate+"-"+month+"-"+year+" "+hours + ':' + minutes + ' ' + ampm;
  return strTime;
}
var ampm=timeformat("2019-01-11 12:26:43");
console.log(ampm);

Here the Function to Convert time into am or pm with Date,it may be help Someone.

Last Run Date on a Stored Procedure in SQL Server

If you enable Query Store on SQL Server 2016 or newer you can use the following query to get last SP execution. The history depends on the Query Store Configuration.

SELECT 
      ObjectName = '[' + s.name + '].[' + o.Name  + ']'
    , LastModificationDate  = MAX(o.modify_date)
    , LastExecutionTime     = MAX(q.last_execution_time)
FROM sys.query_store_query q 
    INNER JOIN sys.objects o
        ON q.object_id = o.object_id
    INNER JOIN sys.schemas s
        ON o.schema_id = s.schema_id
WHERE o.type IN ('P')
GROUP BY o.name , + s.name 

How to set UITextField height?

In Swift 3 use:

yourTextField.frame.size.height = 30

Purpose of Unions in C and C++

You could use unions to create structs like the following, which contains a field that tells us which component of the union is actually used:

struct VAROBJECT
{
    enum o_t { Int, Double, String } objectType;

    union
    {
        int intValue;
        double dblValue;
        char *strValue;
    } value;
} object;

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

CSS text-overflow: ellipsis; not working?

In bootstrap 4, you can add a .text-truncate class to truncate the text with an ellipsis.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Inline level -->_x000D_
<span class="d-inline-block text-truncate" style="max-width: 250px;">_x000D_
  The quick brown fox jumps over the lazy dog._x000D_
</span>
_x000D_
_x000D_
_x000D_

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

In my case, I just had to put the element one line down:

This throws an error:

_x000D_
_x000D_
export function DismissKeyboard(props: IProps) {
  return <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}> {props.children}
  </TouchableWithoutFeedback>;
}
_x000D_
_x000D_
_x000D_

While this does not throw an error:

_x000D_
_x000D_
export function DismissKeyboard(props: IProps) {
  return <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}>
    {props.children}
  </TouchableWithoutFeedback>;
}
_x000D_
_x000D_
_x000D_

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Check build.gradle(Module: Android) fixed problem for me.

Modify it to workable version.

android {
    buildToolsVersion '23.0.1'
}

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

If table exists drop table then create it, if it does not exist just create it

I needed to drop a table and re-create with a data from a view. I was creating a table out of a view and this is what I did:

DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;

The above worked for me using MySQL MariaDb.

How to generate a random number between a and b in Ruby?

rand(3..10)

Kernel#rand

When max is a Range, rand returns a random number where range.member?(number) == true.

Location of WSDL.exe

In case anyone using VS 2008 (.NET 3.5) is also looking for the wsdl.exe. I found it here:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\wsdl.exe

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Convert String to equivalent Enum value

Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

How to make a round button?

You can use google's FloatingActionButton

XMl:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_dialog_email" />

Java:

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

    FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
    bold.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Do Stuff
        }
    });
}

Gradle:

    compile 'com.android.support:design:23.4.0'

How to have a transparent ImageButton: Android

in run time, you can use following code

btn.setBackgroundDrawable(null);

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

How to create a generic array?

Problem is that while runtime generic type is erased so new E[10] would be equivalent to new Object[10].

This would be dangerous because it would be possible to put in array other data than of E type. That is why you need to explicitly say that type you want by either

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Using this attribute is definitely unsafe.

One particular thing it breaks is the ability of a union which contains two or more structs to write one member and read another if the structs have a common initial sequence of members. Section 6.5.2.3 of the C11 standard states:

6 One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Tw o structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

...

9 EXAMPLE 3 The following is a valid fragment:

union {
    struct {
        int    alltypes;
    }n;
    struct {
        int    type;
        int    intnode;
    } ni;
    struct {
        int    type;
        double doublenode;
    } nf;
}u;
u.nf.type = 1;
u.nf.doublenode = 3.14;
/*
...
*/
if (u.n.alltypes == 1)
if (sin(u.nf.doublenode) == 0.0)
/*
...
*/

When __attribute__((packed)) is introduced it breaks this. The following example was run on Ubuntu 16.04 x64 using gcc 5.4.0 with optimizations disabled:

#include <stdio.h>
#include <stdlib.h>

struct s1
{
    short a;
    int b;
} __attribute__((packed));

struct s2
{
    short a;
    int b;
};

union su {
    struct s1 x;
    struct s2 y;
};

int main()
{
    union su s;
    s.x.a = 0x1234;
    s.x.b = 0x56789abc;

    printf("sizeof s1 = %zu, sizeof s2 = %zu\n", sizeof(struct s1), sizeof(struct s2));
    printf("s.y.a=%hx, s.y.b=%x\n", s.y.a, s.y.b);
    return 0;
}

Output:

sizeof s1 = 6, sizeof s2 = 8
s.y.a=1234, s.y.b=5678

Even though struct s1 and struct s2 have a "common initial sequence", the packing applied to the former means that the corresponding members don't live at the same byte offset. The result is the value written to member x.b is not the same as the value read from member y.b, even though the standard says they should be the same.

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

Loading another html page from javascript

You can include a .js file which has the script to set the

window.location.href = url;

Where url would be the url you wish to load.

How does @synchronized lock/unlock in Objective-C?

In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.

Basically, @synchronized (...) is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.

Android - how to replace part of a string by another string?

In kotlin there is no replaceAll, so I created this loop to replace repeated values ??in a string or any variable.

 var someValue = "https://www.google.com.br/"
    while (someValue.contains(".")) {
        someValue = someValue.replace(".", "")
    }
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/

Select Pandas rows based on list index

There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.

index_list = [1,3]

df.take(pos)

#or

df.query('index in @index_list')

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

How to write a switch statement in Ruby

I prefer to use case + than

number = 10

case number
when 1...8 then # ...
when 8...15 then # ...
when 15.. then # ...
end

Error when testing on iOS simulator: Couldn't register with the bootstrap server

This error happens a lot to me, almost every time I test the app in the Simulator, forcing me to restart.

Here's a workaround if you want to get some work done:

  • Click your project in the Project navigator
  • Go Target -> Info
  • Add a key for Application does not run in background and set to YES.

This will mean that when you press the home button in the simulator or quit the simulator, the app doesn't hang.

Don't forget to change this setting back before distribution! Put it on your release checklist :)

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

android start activity from service

From inside the Service class:

Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);

Homebrew install specific version of formula?

TLDR: brew install [email protected] See answer below for more details.


*(I’ve re-edited my answer to give a more thorough workflow for installing/using older software versions with homebrew. Feel free to add a note if you found the old version better.)

Let’s start with the simplest case:

1) Check, whether the version is already installed (but not activated)

When homebrew installs a new formula, it puts it in a versioned directory like /usr/local/Cellar/postgresql/9.3.1. Only symbolic links to this folder are then installed globally. In principle, this makes it pretty easy to switch between two installed versions. (*)

If you have been using homebrew for longer and never removed older versions (using, for example brew cleanup), chances are that some older version of your program may still be around. If you want to simply activate that previous version, brew switch is the easiest way to do this.

Check with brew info postgresql (or brew switch postgresql <TAB>) whether the older version is installed:

$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M)
  Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more

We see that some older version is already installed. We may activate it using brew switch:

$ brew switch postgresql 9.1.5
Cleaning /usr/local/Cellar/postgresql/9.1.5
Cleaning /usr/local/Cellar/postgresql/9.3.2
384 links created for /usr/local/Cellar/postgresql/9.1.5

Let’s double-check what is activated:

$ brew info postgresql
postgresql: stable 9.3.2 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M) *
  Built from source
/usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M)
  Poured from bottle
From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
# … and some more

Note that the star * has moved to the newly activated version

(*) Please note that brew switch only works as long as all dependencies of the older version are still around. In some cases, a rebuild of the older version may become necessary. Therefore, using brew switch is mostly useful when one wants to switch between two versions not too far apart.

2) Check, whether the version is available as a tap

Especially for larger software projects, it is very probably that there is a high enough demand for several (potentially API incompatible) major versions of a certain piece of software. As of March 2012, Homebrew 0.9 provides a mechanism for this: brew tap & the homebrew versions repository.

That versions repository may include backports of older versions for several formulae. (Mostly only the large and famous ones, but of course they’ll also have several formulae for postgresql.)

brew search postgresql will show you where to look:

$ brew search postgresql
postgresql
homebrew/versions/postgresql8    homebrew/versions/postgresql91
homebrew/versions/postgresql9    homebrew/versions/postgresql92

We can simply install it by typing

$ brew install homebrew/versions/postgresql8
Cloning into '/usr/local/Library/Taps/homebrew-versions'...
remote: Counting objects: 1563, done.
remote: Compressing objects: 100% (943/943), done.
remote: Total 1563 (delta 864), reused 1272 (delta 620)
Receiving objects: 100% (1563/1563), 422.83 KiB | 339.00 KiB/s, done.
Resolving deltas: 100% (864/864), done.
Checking connectivity... done.
Tapped 125 formula
==> Downloading http://ftp.postgresql.org/pub/source/v8.4.19/postgresql-8.4.19.tar.bz2
# …

Note that this has automatically tapped the homebrew/versions tap. (Check with brew tap, remove with brew untap homebrew/versions.) The following would have been equivalent:

$ brew tap homebrew/versions
$ brew install postgresql8

As long as the backported version formulae stay up-to-date, this approach is probably the best way to deal with older software.

3) Try some formula from the past

The following approaches are listed mostly for completeness. Both try to resurrect some undead formula from the brew repository. Due to changed dependencies, API changes in the formula spec or simply a change in the download URL, things may or may not work.

Since the whole formula directory is a git repository, one can install specific versions using plain git commands. However, we need to find a way to get to a commit where the old version was available.

a) historic times

Between August 2011 and October 2014, homebrew had a brew versions command, which spat out all available versions with their respective SHA hashes. As of October 2014, you have to do a brew tap homebrew/boneyard before you can use it. As the name of the tap suggests, you should probably only do this as a last resort.

E.g.

$ brew versions postgresql
Warning: brew-versions is unsupported and may be removed soon.
Please use the homebrew-versions tap instead:
  https://github.com/Homebrew/homebrew-versions
9.3.2    git checkout 3c86d2b Library/Formula/postgresql.rb
9.3.1    git checkout a267a3e Library/Formula/postgresql.rb
9.3.0    git checkout ae59e09 Library/Formula/postgresql.rb
9.2.4    git checkout e3ac215 Library/Formula/postgresql.rb
9.2.3    git checkout c80b37c Library/Formula/postgresql.rb
9.2.2    git checkout 9076baa Library/Formula/postgresql.rb
9.2.1    git checkout 5825f62 Library/Formula/postgresql.rb
9.2.0    git checkout 2f6cbc6 Library/Formula/postgresql.rb
9.1.5    git checkout 6b8d25f Library/Formula/postgresql.rb
9.1.4    git checkout c40c7bf Library/Formula/postgresql.rb
9.1.3    git checkout 05c7954 Library/Formula/postgresql.rb
9.1.2    git checkout dfcc838 Library/Formula/postgresql.rb
9.1.1    git checkout 4ef8fb0 Library/Formula/postgresql.rb
9.0.4    git checkout 2accac4 Library/Formula/postgresql.rb
9.0.3    git checkout b782d9d Library/Formula/postgresql.rb

As you can see, it advises against using it. Homebrew spits out all versions it can find with its internal heuristic and shows you a way to retrieve the old formulae. Let’s try it.

# First, go to the homebrew base directory
$ cd $( brew --prefix )
# Checkout some old formula
$ git checkout 6b8d25f Library/Formula/postgresql.rb
$ brew install postgresql
# … installing

Now that the older postgresql version is installed, we can re-install the latest formula in order to keep our repository clean:

$ git checkout -- Library/Formula/postgresql.rb

brew switch is your friend to change between the old and the new.

b) prehistoric times

For special needs, we may also try our own digging through the homebrew repo.

$ cd Library/Taps/homebrew/homebrew-core && git log -S'8.4.4' -- Formula/postgresql.rb

git log -S looks for all commits in which the string '8.4.4' was either added or removed in the file Library/Taps/homebrew/homebrew-core/Formula/postgresql.rb. We get two commits as a result.

commit 7dc7ccef9e1ab7d2fc351d7935c96a0e0b031552
Author: Aku Kotkavuo
Date:   Sun Sep 19 18:03:41 2010 +0300

    Update PostgreSQL to 9.0.0.

    Signed-off-by: Adam Vandenberg

commit fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
Author: David Höppner
Date:   Sun May 16 12:35:18 2010 +0200

    postgresql: update version to 8.4.4

Obviously, fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422 is the commit we’re interested in. As this commit is pretty old, we’ll try to downgrade the complete homebrew installation (that way, the formula API is more or less guaranteed to be valid):

$ git checkout -b postgresql-8.4.4 fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
$ brew install postgresql
$ git checkout master
$ git branch -d postgresql-8.4.4

You may skip the last command to keep the reference in your git repository.

One note: When checking out the older commit, you temporarily downgrade your homebrew installation. So, you should be careful as some commands in homebrew might be different to the most recent version.

4) Manually write a formula

It’s not too hard and you may then upload it to your own repository. Used to be Homebrew-Versions, but that is now discontinued.

A.) Bonus: Pinning

If you want to keep a certain version of, say postgresql, around and stop it from being updated when you do the natural brew update; brew upgrade procedure, you can pin a formula:

$ brew pin postgresql

Pinned formulae are listed in /usr/local/Library/PinnedKegs/ and once you want to bring in the latest changes and updates, you can unpin it again:

$ brew unpin postgresql

How to horizontally center an unordered list of unknown width?

Use the below css to solve your issue

#footer{ text-align:center; height:58px;}
#footer ul {  font-size:11px;}
#footer ul li {display:inline-block;}

Note: Don't use float:left in li. it will make your li to align left.

Make a dictionary in Python from input values

n = int(input("enter a n value:"))
d = {}

for i in range(n):
    keys = input() # here i have taken keys as strings
    values = int(input()) # here i have taken values as integers
    d[keys] = values
print(d)

Animation fade in and out

FOR FADE add this first line with your animation's object.

.animate().alpha(1).setDuration(2000);

FOR EXAMPLEI USED LottieAnimation

Powershell Execute remote exe with command line arguments on remote computer

$sb = ScriptBlock::Create("$command")
Invoke-Command -ScriptBlock $sb

This should work and avoid misleading the beginners.

Nesting optgroups in a dropdownlist/select

The HTML spec here is really broken. It should allow nested optgroups and recommend user agents render them as nested menus. Instead, only one optgroup level is allowed. However, they do have to say the following on the subject:

Note. Implementors are advised that future versions of HTML may extend the grouping mechanism to allow for nested groups (i.e., OPTGROUP elements may nest). This will allow authors to represent a richer hierarchy of choices.

And user agents could start using submenus to render optgoups instead of displaying titles before the first option element in an optgroup as they do now.

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

How to rearrange Pandas column sequence?

There may be an elegant built-in function (but I haven't found it yet). You could write one:

# reorder columns
def set_column_sequence(dataframe, seq, front=True):
    '''Takes a dataframe and a subsequence of its columns,
       returns dataframe with seq as first columns if "front" is True,
       and seq as last columns if "front" is False.
    '''
    cols = seq[:] # copy so we don't mutate seq
    for x in dataframe.columns:
        if x not in cols:
            if front: #we want "seq" to be in the front
                #so append current column to the end of the list
                cols.append(x)
            else:
                #we want "seq" to be last, so insert this
                #column in the front of the new column list
                #"cols" we are building:
                cols.insert(0, x)
return dataframe[cols]

For your example: set_column_sequence(df, ['x','y']) would return the desired output.

If you want the seq at the end of the DataFrame instead simply pass in "front=False".

What's the best UI for entering date of birth?

I would also recommend the combination of DatePicker and fields

See this demo, where the date picker does reflect the date entered in the fields by the user.
It is based however on a DatePicker using Prototype and Scriptaculous though. I mention it for illustration purpose.