Programs & Examples On #Microsoft ajax minifier

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had a working setup (for NUnit2 and NUnit3 depending on the solution, and multiple versions of Visual Studio between 2012 and 2017), and it suddenly stopped working one day: no tests detected in any solution or version of VS.

In my case, it helped to delete %localappdata%\Temp\VisualStudioTestExplorerExtensions. After a restart of VS, everything worked as before.

SyntaxError: Use of const in strict mode?

For me it was more simple to solve, just going to the Node web site, get and install the LTS version.

How can I count the number of elements with same class?

document.getElementsByClassName("classstringhere").length

The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.

Node.js connect only works on localhost

On your app, makes it reachable from any device in the network:

app.listen(3000, "0.0.0.0");

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS

Find the nth occurrence of substring in a string

Here's another re + itertools version that should work when searching for either a str or a RegexpObject. I will freely admit that this is likely over-engineered, but for some reason it entertained me.

import itertools
import re

def find_nth(haystack, needle, n = 1):
    """
    Find the starting index of the nth occurrence of ``needle`` in \
    ``haystack``.

    If ``needle`` is a ``str``, this will perform an exact substring
    match; if it is a ``RegexpObject``, this will perform a regex
    search.

    If ``needle`` doesn't appear in ``haystack``, return ``-1``. If
    ``needle`` doesn't appear in ``haystack`` ``n`` times,
    return ``-1``.

    Arguments
    ---------
    * ``needle`` the substring (or a ``RegexpObject``) to find
    * ``haystack`` is a ``str``
    * an ``int`` indicating which occurrence to find; defaults to ``1``

    >>> find_nth("foo", "o", 1)
    1
    >>> find_nth("foo", "o", 2)
    2
    >>> find_nth("foo", "o", 3)
    -1
    >>> find_nth("foo", "b")
    -1
    >>> import re
    >>> either_o = re.compile("[oO]")
    >>> find_nth("foo", either_o, 1)
    1
    >>> find_nth("FOO", either_o, 1)
    1
    """
    if (hasattr(needle, 'finditer')):
        matches = needle.finditer(haystack)
    else:
        matches = re.finditer(re.escape(needle), haystack)
    start_here = itertools.dropwhile(lambda x: x[0] < n, enumerate(matches, 1))
    try:
        return next(start_here)[1].start()
    except StopIteration:
        return -1

"Parse Error : There is a problem parsing the package" while installing Android application

As a couple of the other answers have mentioned, there can be problems when installing from the SD card. In my case I was distributing my app via email attachment, and it usually worked fine. Just open the email and download the attachment (it apparently goes to the SD card) and click on it again and it gets installed.

But then one day it didn't work, and it turned out it was because I had the phone connected to my development PC via USB, and that placed the SD card in a different mode or something. So the solution was simply to disconnect the phone from the PC and then send the e-mail again and download the attachment again. Or else place the USB connection in "charging only" mode so the SD card is not "connected" to the PC.

Making a mocked method return an argument that was passed to it

I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:

public class RoomService {
    public Room findByName(String roomName) {...}
    public void persist(Room room) {...}
}

The service mock uses a map to store the Room instances.

RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();

// mock for method persist
doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            Room room = (Room) arguments[0];
            roomMap.put(room.getName(), room);
        }
        return null;
    }
}).when(roomService).persist(any(Room.class));

// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
    @Override
    public Room answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            String key = (String) arguments[0];
            if (roomMap.containsKey(key)) {
                return roomMap.get(key);
            }
        }
        return null;
    }
});

We can now run our tests on this mock. For example:

String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));

Get Locale Short Date Format using javascript

I believe you can use this one:

new Date().toLocaleDateString();

Which can accept parameters for the locale:

new Date().toLocaleDateString("en-us");
new Date().toLocaleDateString("he-il");

I see it is supported by chrome, IE, edge, although results may vary it does a pretty good job for me.

Percentage Height HTML 5/CSS

You need to set the height on the <html> and <body> elements as well; otherwise, they will only be large enough to fit the content. For example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<title>Example of 100% width and height</title>_x000D_
<style>_x000D_
html, body { height: 100%; margin: 0; }_x000D_
div { height: 100%; width: 100%; background: red; }_x000D_
</style>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

List directory tree structure in python?

This solution will only work if you have tree installed on your system. However I'm leaving this solution here just in case it helps someone else out.

You can tell tree to output the tree structure as XML (tree -X) or JSON (tree -J). JSON of course can be parsed directly with python and XML can easily be read with lxml.

With the following directory structure as an example:

[sri@localhost Projects]$ tree --charset=ascii bands
bands
|-- DreamTroll
|   |-- MattBaldwinson
|   |-- members.txt
|   |-- PaulCarter
|   |-- SimonBlakelock
|   `-- Rob Stringer
|-- KingsX
|   |-- DougPinnick
|   |-- JerryGaskill
|   |-- members.txt
|   `-- TyTabor
|-- Megadeth
|   |-- DaveMustaine
|   |-- DavidEllefson
|   |-- DirkVerbeuren
|   |-- KikoLoureiro
|   `-- members.txt
|-- Nightwish
|   |-- EmppuVuorinen
|   |-- FloorJansen
|   |-- JukkaNevalainen
|   |-- MarcoHietala
|   |-- members.txt
|   |-- TroyDonockley
|   `-- TuomasHolopainen
`-- Rush
    |-- AlexLifeson
    |-- GeddyLee
    `-- NeilPeart

5 directories, 25 files

XML

<?xml version="1.0" encoding="UTF-8"?>
<tree>
  <directory name="bands">
    <directory name="DreamTroll">
      <file name="MattBaldwinson"></file>
      <file name="members.txt"></file>
      <file name="PaulCarter"></file>
      <file name="RobStringer"></file>
      <file name="SimonBlakelock"></file>
    </directory>
    <directory name="KingsX">
      <file name="DougPinnick"></file>
      <file name="JerryGaskill"></file>
      <file name="members.txt"></file>
      <file name="TyTabor"></file>
    </directory>
    <directory name="Megadeth">
      <file name="DaveMustaine"></file>
      <file name="DavidEllefson"></file>
      <file name="DirkVerbeuren"></file>
      <file name="KikoLoureiro"></file>
      <file name="members.txt"></file>
    </directory>
    <directory name="Nightwish">
      <file name="EmppuVuorinen"></file>
      <file name="FloorJansen"></file>
      <file name="JukkaNevalainen"></file>
      <file name="MarcoHietala"></file>
      <file name="members.txt"></file>
      <file name="TroyDonockley"></file>
      <file name="TuomasHolopainen"></file>
    </directory>
    <directory name="Rush">
      <file name="AlexLifeson"></file>
      <file name="GeddyLee"></file>
      <file name="NeilPeart"></file>
    </directory>
  </directory>
  <report>
    <directories>5</directories>
    <files>25</files>
  </report>
</tree>

JSON

[sri@localhost Projects]$ tree -J bands
[
  {"type":"directory","name":"bands","contents":[
    {"type":"directory","name":"DreamTroll","contents":[
      {"type":"file","name":"MattBaldwinson"},
      {"type":"file","name":"members.txt"},
      {"type":"file","name":"PaulCarter"},
      {"type":"file","name":"RobStringer"},
      {"type":"file","name":"SimonBlakelock"}
    ]},
    {"type":"directory","name":"KingsX","contents":[
      {"type":"file","name":"DougPinnick"},
      {"type":"file","name":"JerryGaskill"},
      {"type":"file","name":"members.txt"},
      {"type":"file","name":"TyTabor"}
    ]},
    {"type":"directory","name":"Megadeth","contents":[
      {"type":"file","name":"DaveMustaine"},
      {"type":"file","name":"DavidEllefson"},
      {"type":"file","name":"DirkVerbeuren"},
      {"type":"file","name":"KikoLoureiro"},
      {"type":"file","name":"members.txt"}
    ]},
    {"type":"directory","name":"Nightwish","contents":[
      {"type":"file","name":"EmppuVuorinen"},
      {"type":"file","name":"FloorJansen"},
      {"type":"file","name":"JukkaNevalainen"},
      {"type":"file","name":"MarcoHietala"},
      {"type":"file","name":"members.txt"},
      {"type":"file","name":"TroyDonockley"},
      {"type":"file","name":"TuomasHolopainen"}
    ]},
    {"type":"directory","name":"Rush","contents":[
      {"type":"file","name":"AlexLifeson"},
      {"type":"file","name":"GeddyLee"},
      {"type":"file","name":"NeilPeart"}
    ]}
  ]},
  {"type":"report","directories":5,"files":25}
]

PHP __get and __set magic methods

Best use magic set/get methods with predefined custom set/get Methods as in example below. This way you can combine best of two worlds. In terms of speed I agree that they are a bit slower but can you even feel the difference. Example below also validate the data array against predefined setters.

"The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error."

This is why we should use both.

CLASS ITEM EXAMPLE

    /*
    * Item class
    */
class Item{
    private $data = array();

    function __construct($options=""){ //set default to none
        $this->setNewDataClass($options); //calling function
    }

    private function setNewDataClass($options){
        foreach ($options as $key => $value) {
            $method = 'set'.ucfirst($key); //capitalize first letter of the key to preserve camel case convention naming
            if(is_callable(array($this, $method))){  //use seters setMethod() to set value for this data[key];      
                $this->$method($value); //execute the setters function
            }else{
                $this->data[$key] = $value; //create new set data[key] = value without seeters;
            }   
        }
    }

    private function setNameOfTheItem($value){ // no filter
        $this->data['name'] = strtoupper($value); //assign the value
        return $this->data['name']; // return the value - optional
    }

    private function setWeight($value){ //use some kind of filter
        if($value >= "100"){ 
            $value = "this item is too heavy - sorry - exceeded weight of maximum 99 kg [setters filter]";
        }
        $this->data['weight'] = strtoupper($value); //asign the value
        return $this->data['weight']; // return the value - optional
    }

    function __set($key, $value){
        $method = 'set'.ucfirst($key); //capitalize first letter of the key to preserv camell case convention naming
        if(is_callable(array($this, $method))){  //use seters setMethod() to set value for this data[key];      
            $this->$method($value); //execute the seeter function
        }else{
            $this->data[$key] = $value; //create new set data[key] = value without seeters;
        }
    }

    function __get($key){
        return $this->data[$key];
    }

    function dump(){
        var_dump($this);
    }
}

INDEX.PHP

$data = array(
    'nameOfTheItem' => 'tv',
    'weight' => '1000',
    'size' => '10x20x30'
);

$item = new Item($data);
$item->dump();

$item->somethingThatDoNotExists = 0; // this key (key, value) will trigger magic function __set() without any control or check of the input,
$item->weight = 99; // this key will trigger predefined setter function of a class - setWeight($value) - value is valid,
$item->dump();

$item->weight = 111; // this key will trigger predefined setter function of a class - setWeight($value) - value invalid - will generate warning.
$item->dump(); // display object info

OUTPUT

object(Item)[1]
  private 'data' => 
    array (size=3)
      'name' => string 'TV' (length=2)
      'weight' => string 'THIS ITEM IS TOO HEAVY - SORRY - EXIDED WEIGHT OF MAXIMUM 99 KG [SETTERS FILTER]' (length=80)
      'size' => string '10x20x30' (length=8)
object(Item)[1]
  private 'data' => 
    array (size=4)
      'name' => string 'TV' (length=2)
      'weight' => string '99' (length=2)
      'size' => string '10x20x30' (length=8)
      'somethingThatDoNotExists' => int 0
object(Item)[1]
  private 'data' => 
    array (size=4)
      'name' => string 'TV' (length=2)
      'weight' => string 'THIS ITEM IS TOO HEAVY - SORRY - EXIDED WEIGHT OF MAXIMUM 99 KG [SETTERS FILTER]' (length=80)
      'size' => string '10x20x30' (length=8)
      'somethingThatDoNotExists' => int 0

How to use ? : if statements with Razor and inline code blocks

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

Integer value in TextView

Consider using String#format with proper format specifications (%d or %f) instead.

int value = 10;

textView.setText(String.format("%d",value));

This will handle fraction separator and locale specific digits properly

Is nested function a good approach when required by only one function?

It's actually fine to declare one function inside another one. This is specially useful creating decorators.

However, as a rule of thumb, if the function is complex (more than 10 lines) it might be a better idea to declare it on the module level.

What is the difference between `new Object()` and object literal notation?

There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

Literal way:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.

Using ffmpeg to change framerate

You can use this command and the video duration is still unaltered.

ffmpeg -i input.mp4 -r 24 output.mp4

Java Project: Failed to load ApplicationContext

I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.

Random number c++ in some range

Use the rand function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

How to configure CORS in a Spring Boot + Spring Security application?

Spring Security can now leverage Spring MVC CORS support described in this blog post I wrote.

To make it work, you need to explicitly enable CORS support at Spring Security level as following, otherwise CORS enabled requests may be blocked by Spring Security before reaching Spring MVC.

If you are using controller level @CrossOrigin annotations, you just have to enable Spring Security CORS support and it will leverage Spring MVC configuration:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

If you prefer using CORS global configuration, you can declare a CorsConfigurationSource bean as following:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

This approach supersedes the filter-based approach previously recommended.

You can find more details in the dedicated CORS section of Spring Security documentation.

Is there a better jQuery solution to this.form.submit();?

Similar to Matthew's answer, I just found that you can do the following:

$(this).closest('form').submit();

Wrong: The problem with using the parent functionality is that the field needs to be immediately within the form to work (not inside tds, labels, etc).

I stand corrected: parents (with an s) also works. Thxs Paolo for pointing that out.

Breaking out of a for loop in Java

How about

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

    System.out.println(k);
}

The other way is a labelled loop

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

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

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

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

For an even better explanation you can check here

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

XAMPP Apache Webserver localhost not working on MAC OS

This is what helped me:

sudo apachectl stop

This command killed Apache server that was pre-installed on MAC OS X.

How to count number of files in each directory?

You could arrange to find all the files, remove the file names, leaving you a line containing just the directory name for each file, and then count the number of times each directory appears:

find . -type f |
sed 's%/[^/]*$%%' |
sort |
uniq -c

The only gotcha in this is if you have any file names or directory names containing a newline character, which is fairly unlikely. If you really have to worry about newlines in file names or directory names, I suggest you find them, and fix them so they don't contain newlines (and quietly persuade the guilty party of the error of their ways).


If you're interested in the count of the files in each sub-directory of the current directory, counting any files in any sub-directories along with the files in the immediate sub-directory, then I'd adapt the sed command to print only the top-level directory:

find . -type f |
sed -e 's%^\(\./[^/]*/\).*$%\1%' -e 's%^\.\/[^/]*$%./%' |
sort |
uniq -c

The first pattern captures the start of the name, the dot, the slash, the name up to the next slash and the slash, and replaces the line with just the first part, so:

./dir1/dir2/file1

is replaced by

./dir1/

The second replace captures the files directly in the current directory; they don't have a slash at the end, and those are replace by ./. The sort and count then works on just the number of names.

Writing a pandas DataFrame to CSV file

Example of export in file with full path on Windows and in case your file has headers:

df.to_csv (r'C:\Users\John\Desktop\export_dataframe.csv', index = None, header=True) 

For example, if you want to store the file in same directory where your script is, with utf-8 encoding and tab as separator:

df.to_csv(r'./export/dftocsv.csv', sep='\t', encoding='utf-8', header='true')

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

In the first place consider the Small grid, see: http://getbootstrap.com/css/#grid-options. A max container width of 750 px will maybe to small for you (also read: Why does Bootstrap 3 force the container width to certain sizes?)

When using the Small grid use media queries to set the max-container width:

@media (min-width: 768px) { .container { max-width: 750px; } }

Second also read this question: Bootstrap 3 - 940px width grid?, possible duplicate?

12 x 60 = 720px for the columns and 11 x 20 = 220px

there will also a gutter of 20px on both sides of the grid so 220 + 720 + 40 makes 980px

there is 'no' @ColumnWidth

You colums width will be calculated dynamically based on your settings in variables.less. you could set @grid-columns and @grid-gutter-width. The width of a column will be set as a percentage via grid.less in mixins.less:

.calc-grid(@index, @class, @type) when (@type = width) {
  .col-@{class}-@{index} {
    width: percentage((@index / @grid-columns));
  }
}

update Set @grid-gutter-width to 20px;, @container-desktop: 940px;, @container-large-desktop: @container-desktop and recompile bootstrap.

How do you transfer or export SQL Server 2005 data to Excel

Check this.

Query -> Query Options.

Results -> Grid -> Include column headers when copying or saving the results

How do you add an action to a button programmatically in xcode

try this:

first write this in your .h file of viewcontroller

UIButton *btn;

Now write this in your .m file of viewcontrollers viewDidLoad.

btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

write this outside viewDidLoad method in .m file of your view controller

- (IBAction)btnClicked:(id)sender
{
   //Write a code you want to execute on buttons click event
}

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

How to increase Bootstrap Modal Width?

go to the modal-dialog div and add

 style="width:70%"

depending on the size you want

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

What is the use of "assert"?

Watch out for the parentheses. As has been pointed out above, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is important because:

assert(2 + 2 == 5, "Houston we've got a problem")

won't work, unlike

assert 2 + 2 == 5, "Houston we've got a problem"

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

Does it matter what extension is used for SQLite database files?

Pretty much down to personal choice. It may make sense to use an extension based on the database scheme you are storing; treat your database schema as a file format, with SQLite simply being an encoding used for that file format. So, you might use .bookmarks if it's storing bookmarks, or .index if it's being used as an index.

If you want to use a generic extension, I'd use .sqlite3 since that is most descriptive of what version of SQLite is needed to work with the database.

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

Fixing Segmentation faults in C++

Sometimes the crash itself isn't the real cause of the problem-- perhaps the memory got smashed at an earlier point but it took a while for the corruption to show itself. Check out valgrind, which has lots of checks for pointer problems (including array bounds checking). It'll tell you where the problem starts, not just the line where the crash occurs.

The tilde operator in Python

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

Exit Shell Script Based on Process Exit Code

In Bash this is easy. Just tie them together with &&:

command1 && command2 && command3

You can also use the nested if construct:

if command1
   then
       if command2
           then
               do_something
           else
               exit
       fi
   else
       exit
fi

String, StringBuffer, and StringBuilder

Also, StringBuffer is thread-safe, which StringBuilder is not.

So in a real-time situation when different threads are accessing it, StringBuilder could have an undeterministic result.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

Okay just copy and paste these codes: This should be done in the terminal, inside a server, when your mysql database is not properly installed, and when you are getting this error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'.

Stop MySql

sudo /etc/init.d/mysqld stop

Restart it or start it

sudo /etc/init.d/mysqld restart or sudo /etc/init.d/mysqld start

Make a link like this and give it to the system

ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

Run a secure installation which guides all the process you need to do to configure mysql

/usr/bin/mysql_secure_installation

Can I use Homebrew on Ubuntu?

as of august 2020 (works for kali linux as well)

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

export brew=/home/linuxbrew/.linuxbrew/bin

test -d ~/.linuxbrew && eval $(~/.linuxbrew/bin/brew shellenv)

test -d /home/linuxbrew/.linuxbrew && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

test -r ~/.profile && echo "eval \$($(brew --prefix)/bin/brew shellenv)" >>~/.profile     // for ubuntu and debian

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

Count specific character occurrences in a string

    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

Loginto your gmail account https://myaccount.google.com/u/4/security-checkup/4

enter image description here

(See photo) review all locations Google may have blocked for "unknown" or suspicious activity.

How to convert webpage into PDF by using Python

This solution worked for me using PyQt5 version 5.15.0

import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loader = QtWebEngineWidgets.QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QPageSize.A4Extra))
    layout.setOrientation(QPageLayout.Portrait)
    loader.load(QUrl('https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python'))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())

    def emit_pdf(finished):
        loader.page().printToPdf("test.pdf", pageLayout=layout)

    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec_())

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

How can I change all input values to uppercase using Jquery?

Use css text-transform to display text in all input type text. In Jquery you can then transform the value to uppercase on blur event.

Css:

input[type=text] {
    text-transform: uppercase;
}

Jquery:

$(document).on('blur', "input[type=text]", function () {
    $(this).val(function (_, val) {
        return val.toUpperCase();
    });
});

How to recursively find and list the latest modified files in a directory with subdirectories and times

I have this alias in my .profile that I use quite often:

$ alias | grep xlogs
xlogs='sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R'

So it does what you are looking for (with exception it doesn't traverse change date/time multiple levels) - looks for latest files (*.log and *.trc files in this case); also it only finds files modified in the last day, and then sorts by time and pipes the output through less:

sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R

PS.: Notice I don't have root on some of the servers, but always have sudo, so you may not need that part.

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

In Visual Basic how do you create a block comment

Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.

http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment

http://forums.asp.net/t/1011404.aspx/1

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

Sorting a DropDownList? - C#, ASP.NET

Try it

-------Store Procedure-----(SQL)

USE [Your Database]
GO


CRATE PROC [dbo].[GetAllDataByID]

@ID int


AS
BEGIN
        SELECT * FROM Your_Table
        WHERE ID=@ID
        ORDER BY Your_ColumnName 
END

----------Default.aspx---------

<asp:DropDownList ID="ddlYourTable" runat="server"></asp:DropDownList>

---------Default.aspx.cs-------

protected void Page_Load(object sender, EventArgs e)

{

      if (!IsPostBack)
            {
                List<YourTable> table= new List<YourTable>();

                YourtableRepository tableRepo = new YourtableRepository();

                int conuntryInfoID=1;

                table= tableRepo.GetAllDataByID(ID);

                ddlYourTable.DataSource = stateInfo;
                ddlYourTable.DataTextField = "Your_ColumnName";
                ddlYourTable.DataValueField = "ID";
                ddlYourTable.DataBind();

            }
        }

-------LINQ Helper Class----

public class TableRepository

   {

        string connstr;

        public TableRepository() 
        {
            connstr = Settings.Default.YourTableConnectionString.ToString();
        }

        public List<YourTable> GetAllDataByID(int ID)
        {
            List<YourTable> table= new List<YourTable>();
            using (YourTableDBDataContext dc = new YourTableDBDataContext ())
            {
                table= dc.GetAllDataByID(ID).ToList();
            }
            return table;
        }
    }

Add placeholder text inside UITextView in Swift?

_x000D_
_x000D_
func setPlaceholder(){_x000D_
var placeholderLabel = UILabel()_x000D_
        placeholderLabel.text = "Describe your need..."_x000D_
        placeholderLabel.font = UIFont.init(name: "Lato-Regular", size: 15.0) ?? UIFont.boldSystemFont(ofSize: 14.0)_x000D_
        placeholderLabel.sizeToFit()_x000D_
        descriptionTextView.addSubview(placeholderLabel)_x000D_
        placeholderLabel.frame.origin = CGPoint(x: 5, y: (descriptionTextView.font?.pointSize)! / 2)_x000D_
        placeholderLabel.textColor = UIColor.lightGray_x000D_
        placeholderLabel.isHidden = !descriptionTextView.text.isEmpty_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
//Delegate Method._x000D_
_x000D_
func textViewDidChange(_ textView: UITextView) {_x000D_
        placeholderLabel.isHidden = !textView.text.isEmpty_x000D_
    }_x000D_
 
_x000D_
_x000D_
_x000D_

How to validate an Email in PHP?

User data is very important for a good developer, so don't ask again and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>

Testing the type of a DOM element in JavaScript

I have another way of testing the same.

_x000D_
_x000D_
Element.prototype.typeof = "element";_x000D_
var element = document.body; // any dom element_x000D_
if (element && element.typeof == "element"){_x000D_
   return true; _x000D_
   // this is a dom element_x000D_
}_x000D_
else{_x000D_
  return false; _x000D_
  // this isn't a dom element_x000D_
}
_x000D_
_x000D_
_x000D_

When should one use a spinlock instead of mutex?

The Theory

In theory, when a thread tries to lock a mutex and it does not succeed, because the mutex is already locked, it will go to sleep, immediately allowing another thread to run. It will continue to sleep until being woken up, which will be the case once the mutex is being unlocked by whatever thread was holding the lock before. When a thread tries to lock a spinlock and it does not succeed, it will continuously re-try locking it, until it finally succeeds; thus it will not allow another thread to take its place (however, the operating system will forcefully switch to another thread, once the CPU runtime quantum of the current thread has been exceeded, of course).

The Problem

The problem with mutexes is that putting threads to sleep and waking them up again are both rather expensive operations, they'll need quite a lot of CPU instructions and thus also take some time. If now the mutex was only locked for a very short amount of time, the time spent in putting a thread to sleep and waking it up again might exceed the time the thread has actually slept by far and it might even exceed the time the thread would have wasted by constantly polling on a spinlock. On the other hand, polling on a spinlock will constantly waste CPU time and if the lock is held for a longer amount of time, this will waste a lot more CPU time and it would have been much better if the thread was sleeping instead.

The Solution

Using spinlocks on a single-core/single-CPU system makes usually no sense, since as long as the spinlock polling is blocking the only available CPU core, no other thread can run and since no other thread can run, the lock won't be unlocked either. IOW, a spinlock wastes only CPU time on those systems for no real benefit. If the thread was put to sleep instead, another thread could have ran at once, possibly unlocking the lock and then allowing the first thread to continue processing, once it woke up again.

On a multi-core/multi-CPU systems, with plenty of locks that are held for a very short amount of time only, the time wasted for constantly putting threads to sleep and waking them up again might decrease runtime performance noticeably. When using spinlocks instead, threads get the chance to take advantage of their full runtime quantum (always only blocking for a very short time period, but then immediately continue their work), leading to much higher processing throughput.

The Practice

Since very often programmers cannot know in advance if mutexes or spinlocks will be better (e.g. because the number of CPU cores of the target architecture is unknown), nor can operating systems know if a certain piece of code has been optimized for single-core or multi-core environments, most systems don't strictly distinguish between mutexes and spinlocks. In fact, most modern operating systems have hybrid mutexes and hybrid spinlocks. What does that actually mean?

A hybrid mutex behaves like a spinlock at first on a multi-core system. If a thread cannot lock the mutex, it won't be put to sleep immediately, since the mutex might get unlocked pretty soon, so instead the mutex will first behave exactly like a spinlock. Only if the lock has still not been obtained after a certain amount of time (or retries or any other measuring factor), the thread is really put to sleep. If the same code runs on a system with only a single core, the mutex will not spinlock, though, as, see above, that would not be beneficial.

A hybrid spinlock behaves like a normal spinlock at first, but to avoid wasting too much CPU time, it may have a back-off strategy. It will usually not put the thread to sleep (since you don't want that to happen when using a spinlock), but it may decide to stop the thread (either immediately or after a certain amount of time) and allow another thread to run, thus increasing chances that the spinlock is unlocked (a pure thread switch is usually less expensive than one that involves putting a thread to sleep and waking it up again later on, though not by far).

Summary

If in doubt, use mutexes, they are usually the better choice and most modern systems will allow them to spinlock for a very short amount of time, if this seems beneficial. Using spinlocks can sometimes improve performance, but only under certain conditions and the fact that you are in doubt rather tells me, that you are not working on any project currently where a spinlock might be beneficial. You might consider using your own "lock object", that can either use a spinlock or a mutex internally (e.g. this behavior could be configurable when creating such an object), initially use mutexes everywhere and if you think that using a spinlock somewhere might really help, give it a try and compare the results (e.g. using a profiler), but be sure to test both cases, a single-core and a multi-core system before you jump to conclusions (and possibly different operating systems, if your code will be cross-platform).

Update: A Warning for iOS

Actually not iOS specific but iOS is the platform where most developers may face that problem: If your system has a thread scheduler, that does not guarantee that any thread, no matter how low its priority may be, will eventually get a chance to run, then spinlocks can lead to permanent deadlocks. The iOS scheduler distinguishes different classes of threads and threads on a lower class will only run if no thread in a higher class wants to run as well. There is no back-off strategy for this, so if you permanently have high class threads available, low class threads will never get any CPU time and thus never any chance to perform any work.

The problem appears as follow: Your code obtains a spinlock in a low prio class thread and while it is in the middle of that lock, the time quantum has exceeded and the thread stops running. The only way how this spinlock can be released again is if that low prio class thread gets CPU time again but this is not guaranteed to happen. You may have a couple of high prio class threads that constantly want to run and the task scheduler will always prioritize those. One of them may run across the spinlock and try to obtain it, which isn't possible of course, and the system will make it yield. The problem is: A thread that yielded is immediately available for running again! Having a higher prio than the thread holding the lock, the thread holding the lock has no chance to get CPU runtime. Either some other thread will get runtime or the thread that just yielded.

Why does this problem not occur with mutexes? When the high prio thread cannot obtain the mutex, it won't yield, it may spin a bit but will eventually be sent to sleep. A sleeping thread is not available for running until it is woken up by an event, e.g. an event like the mutex being unlocked it has been waiting for. Apple is aware of that problem and has thus deprecated OSSpinLock as a result. The new lock is called os_unfair_lock. This lock avoids the situation mentioned above as it is aware of the different thread priority classes. If you are sure that using spinlocks is a good idea in your iOS project, use that one. Stay away from OSSpinLock! And under no circumstances implement your own spinlocks in iOS! If in doubt, use a mutex! macOS is not affected by this issue as it has a different thread scheduler that won't allow any thread (even low prio threads) to "run dry" on CPU time, still the same situation can arise there and will then lead to very poor performance, thus OSSpinLock is deprecated on macOS as well.

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

Read specific columns from a csv file with csv module?

With pandas you can use read_csv with usecols parameter:

df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

Example:

import pandas as pd
import io

s = '''
total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
'''

df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])
print(df)

   total_bill  day  size
0       16.99  Sun     2
1       10.34  Sun     3
2       21.01  Sun     3

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

You can wrap the inputs in col-* classes

<form name="registration_form" id="registration_form" class="form-horizontal">
     <div class="form-group">
           <div class="col-sm-6">
             <label for="firstname" class="sr-only"></label>
             <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
           </div>       
           <div class="col-sm-6">
             <label for="lastname" class="sr-only"></label>
             <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
           </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
          <label for="username" class="sr-only"></label>
          <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
        </div>
    </div><!--/form-group-->

    <div class="form-group">
        <div class="col-sm-12">
        <label for="password" class="sr-only"></label>
        <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
        </div>
    </div><!--/form-group-->
 </form>

http://bootply.com/127825

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

Include headers when using SELECT INTO OUTFILE?

I had no luck with any of these, so after finding a solution, I wanted to add it to the prior answers. Python==3.8.6 MySQL==8.0.19

(Forgive my lack of SO formatting foo. Somebody please clean up.)

Note a couple of things:

First, the query to return column names is unforgiving of punctuation. Using ` backticks or leaving out ' quote around the 'schema_name' and 'table_name' will throw an "unknown column" error.

WHERE TABLE_SCHEMA = 'schema' AND TABLE_NAME = 'table'

Second, the column header names return as a single-entity tuple with all the column names concatenated in one quoted string. Convert to quoted list was easy, but not intuitive (for me at least).

headers_list = headers_result[0].split(",")

Third, cursor must be buffered or the "lazy" thing will not fetch your results as you need them. For very large tables, memory could be an issue. Perhaps chunking would solve that problem.

cur = db.cursor(buffered=True)

Last, all types of UNION attempts yielded errors for me. By zipping the whole mess into a list of dicts, it became trivial to write to a csv, using csv.DictWriter.

headers_sql = """   
SELECT 
GROUP_CONCAT(CONCAT(COLUMN_NAME) ORDER BY ORDINAL_POSITION)   
FROM INFORMATION_SCHEMA.COLUMNS   
WHERE TABLE_SCHEMA = 'schema' AND TABLE_NAME = 'table';   
"""" 

cur = db.cursor(buffered=True) 
cur.execute(header_sql) 
headers_result = cur.fetchone() 
headers_list = headers_result[0].split(",")

rows_sql = """   SELECT * FROM schema.table;   """" 

data = cur.execute(rows_sql) 
data_rows = cur.fetchall() 
data_as_list_of_dicts = [dict(zip(headers_list, row)) for row in data_rows]

with open(csv_destination_file, 'w', encoding='utf-8') as destination_file_opened: 
    dict_writer = csv.DictWriter(destination_file_opened, fieldnames=headers_list) 
    dict_writer.writeheader()   for dict in dict_list:
        dict_writer.writerow(dict)

How to empty the content of a div

you can .remove() each child:

const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()

Why is January month 0 in Java Calendar?

C based languages copy C to some degree. The tm structure (defined in time.h) has an integer field tm_mon with the (commented) range of 0-11.

C based languages start arrays at index 0. So this was convenient for outputting a string in an array of month names, with tm_mon as the index.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Everything is correct above, but one of facts simple explanation LAZY----There are cases when you want to delay the creation of an instance of your object until its first usage. This technique is known as lazy initialization or lazy instantiation. The main purpose of lazy initialization is to boost performance and reduce your memory footprint. If instantiating an instance of your type carries a large computational cost and the program might end up not actually using it, you would want to delay or even avoid wasting CPU cycles.

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

What is the HTML unicode character for a "tall" right chevron?

I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.

Custom seekbar (thumb size, color and background)

  • First at all, use android:splitTrack="false" for the transparency problem of your thumb.

  • For the seekbar.png, you have to use a 9 patch. It would be good for the rounded border and the shadow of your image.

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

Get the system date and split day, month and year

Here is what you are looking for:

String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));

String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();

OR

Alternatively, you can use split function to split string date into day, month and year here.

Hope, it will helps you... Cheers. !!

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

Make sure your ~/.aws/credentials file in Unix looks like this:

[MyProfile1]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

[MyProfile2]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

Your Python script should look like this, and it'll work:

from __future__ import print_function
import boto3
import os

os.environ['AWS_PROFILE'] = "MyProfile1"
os.environ['AWS_DEFAULT_REGION'] = "us-east-1"

ec2 = boto3.client('ec2')

# Retrieves all regions/endpoints that work with EC2
response = ec2.describe_regions()
print('Regions:', response['Regions'])

Source: https://boto3.readthedocs.io/en/latest/guide/configuration.html#interactive-configuration.

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

DECLARE @t TABLE (ID UNIQUEIDENTIFIER DEFAULT NEWID(),myid UNIQUEIDENTIFIER
                , friendid UNIQUEIDENTIFIER, time1 Datetime, time2 Datetime)
insert into @t (myid,friendid,time1,time2) 
values
 ( CONVERT(uniqueidentifier,'0C6A36BA-10E4-438F-BA86-0D5B68A2BB15'),
   CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E'),
   '2014-01-05 02:04:41.953','2014-01-05 12:04:41.953')

SELECT * FROM @t

Result Set With out any errors

+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
¦                  ID                  ¦                 myid                 ¦               friendid               ¦          time1          ¦          time2          ¦
¦--------------------------------------+--------------------------------------+--------------------------------------+-------------------------+-------------------------¦
¦ CF628202-33F3-49CF-8828-CB2D93C69675 ¦ 0C6A36BA-10E4-438F-BA86-0D5B68A2BB15 ¦ DF215E10-8BD4-4401-B2DC-99BB03135F2E ¦ 2014-01-05 02:04:41.953 ¦ 2014-01-05 12:04:41.953 ¦
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

Run a PHP file in a cron job using CPanel

This works fine and also sends email:

/usr/bin/php /home/xxYourUserNamexx/public_html/xxYourFolderxx/xxcronfile.php

The following two commands also work fine but do not send email:

/usr/bin/php -f /home/Same As Above

php -f /home/Same As Above

jQuery textbox change event

There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.

function InitPageControls() {
        CheckIfChanged();
    }

    function CheckIfChanged() {
        // do logic

        setTimeout(function () {
            CheckIfChanged();
        }, 1000);
    }

Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...

How can I listen for keypress event on the whole page?

I would use @HostListener decorator within your component:

import { HostListener } from '@angular/core';

@Component({
  ...
})
export class AppComponent {

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}

There are also other options like:

host property within @Component decorator

Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03

@Component({
  ...
  host: {
    '(document:keypress)': 'handleKeyboardEvent($event)'
  }
})
export class AppComponent {
  handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
  }
}

renderer.listen

import { Component, Renderer2 } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  globalListenFunc: Function;

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
      console.log(e);
    });
  }

  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}

Observable.fromEvent

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';

@Component({
  ...
})
export class AppComponent {
  subscription: Subscription;

  ngOnInit() {
    this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
      console.log(e);
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Check if all checkboxes are selected

I think the easiest way is checking for this condition:

$('.abc:checked').length == $('.abc').length

You could do it every time a new checkbox is checked:

$(".abc").change(function(){
    if ($('.abc:checked').length == $('.abc').length) {
       //do something
    }
});

AttributeError: Module Pip has no attribute 'main'

python3 -m pip install --user --upgrade pip==9.0.3

pip issue: rollback

rbenv not changing ruby version

I forgot to delete rvm before installing rbenv. I deleted rvm and re-installed rbenv, but system still wasn't using the version of Ruby being designated as global by rbenv. I tried shutting Terminal, but it only worked once I restarted the whole machine.

shell script to remove a file if it already exist

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f "$file" ] ; then
    rm "$file"
fi

RuntimeWarning: DateTimeField received a naive datetime

make sure settings.py has USE_TZ = True

In your python file:

from django.utils import timezone

timezone.now() # use its value in model field

LINQ orderby on date field in descending order

I don't believe that Distinct() is guaranteed to maintain the order of the set.

Try pulling out an anonymous type first and distinct/sort on that before you convert to string:

var ud = env.Select(d => new 
                         {
                             d.ReportDate.Year,
                             d.ReportDate.Month,
                             FormattedDate = d.ReportDate.ToString("yyyy-MMM")
                         })
            .Distinct()
            .OrderByDescending(d => d.Year)
            .ThenByDescending(d => d.Month)
            .Select(d => d.FormattedDate);

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How can I pass a Bitmap object from one activity to another

All of the above solutions doesn't work for me, Sending bitmap as parceableByteArray also generates error android.os.TransactionTooLargeException: data parcel size.

Solution

  1. Saved the bitmap in internal storage as:
public String saveBitmap(Bitmap bitmap) {
        String fileName = "ImageName";//no .png or .jpg needed
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            // remember close file output
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        return fileName;
    }
  1. and send in putExtra(String) as
Intent intent = new Intent(ActivitySketcher.this,ActivityEditor.class);
intent.putExtra("KEY", saveBitmap(bmp));
startActivity(intent);
  1. and Receive it in other activity as:
if(getIntent() != null){
  try {
           src = BitmapFactory.decodeStream(openFileInput("myImage"));
       } catch (FileNotFoundException e) {
            e.printStackTrace();
      }

 }


Openssl : error "self signed certificate in certificate chain"

The solution for the error is to add this line at the top of the code:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Android new Bottom Navigation bar or BottomNavigationView

You can create the layouts according to the above-mentioned answers If anyone wants to use this in kotlin:-

 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.images -> {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
       R.id.videos ->
         {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

then in oncreate you can set the above listener to your view

   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I haven't checked the maths, but I suspect that computing S(n^2) in the same pass as we compute S(n) would provide enough info to get two missing numbers, Do S(n^3) as well if there are three, and so on.

How to list the size of each file and directory and sort by descending size in Bash?

du -s -- * | sort -n

(this willnot show hidden (.dotfiles) files)

Use du -sm for Mb units etc. I always use

du -smc -- * | sort -n

because the total line (-c) will end up at the bottom for obvious reasons :)

PS:

  • See comments for handling dotfiles
  • I frequently use e.g. 'du -smc /home// | sort -n |tail' to get a feel of where exactly the large bits are sitting

Oracle sqlldr TRAILING NULLCOLS required, but why?

You have defined 5 fields in your control file. Your fields are terminated by a comma, so you need 5 commas in each record for the 5 fields unless TRAILING NULLCOLS is specified, even though you are loading the ID field with a sequence value via the SQL String.

RE: Comment by OP

That's not my experience with a brief test. With the following control file:

load data
infile *
into table T_new
fields terminated by "," optionally enclosed by '"'
( A,
  B,
  C,
  D,
  ID "ID_SEQ.NEXTVAL"
)
BEGINDATA
1,1,,,
2,2,2,,
3,3,3,3,
4,4,4,4,,
,,,,,

Produced the following output:

Table T_NEW, loaded from every logical record.
Insert option in effect for this table: INSERT

   Column Name                  Position   Len  Term Encl Datatype
------------------------------ ---------- ----- ---- ---- ---------------------
A                                   FIRST     *   ,  O(") CHARACTER            
B                                    NEXT     *   ,  O(") CHARACTER            
C                                    NEXT     *   ,  O(") CHARACTER            
D                                    NEXT     *   ,  O(") CHARACTER            
ID                                   NEXT     *   ,  O(") CHARACTER            
    SQL string for column : "ID_SEQ.NEXTVAL"

Record 1: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 2: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 3: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 5: Discarded - all columns null.

Table T_NEW:
  1 Row successfully loaded.
  3 Rows not loaded due to data errors.
  0 Rows not loaded because all WHEN clauses were failed.
  1 Row not loaded because all fields were null.

Note that the only row that loaded correctly had 5 commas. Even the 3rd row, with all data values present except ID, the data does not load. Unless I'm missing something...

I'm using 10gR2.

set option "selected" attribute from dynamic created option

Make option defaultSelected

HTMLOptionElement.defaultSelected = true;     // JS
$('selector').prop({defaultSelected: true});  // jQuery  

HTMLOptionElement MDN

If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:

_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
EL_country.value = 'ID';   // Set SELECT value to 'ID' ("Indonesia")_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country">_x000D_
    <option value="AF">Afghanistan</option>_x000D_
    <option value="AL">Albania</option>_x000D_
    <option value="HR">Croatia</option>_x000D_
    <option value="ID">Indonesia</option>_x000D_
    <option value="ZW">Zimbabwe</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
_x000D_
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)_x000D_
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, ''); _x000D_
_x000D_
EL_country.value = 'ID';_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true;_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Option gets Attribute selected by using defaultSelected

Make option defaultSelected while dynamically creating options

To make an option selected while populating the SELECT Element, use the Option() constructor MDN

var optionElementReference = new Option(text, value, defaultSelected, selected);

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',     // <<< make this one defaultSelected_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
const DF_options = document.createDocumentFragment();_x000D_
_x000D_
Object.keys(countries).forEach(key => {_x000D_
  const isIndonesia = key === 'ID';  // Boolean_x000D_
  DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))_x000D_
});_x000D_
_x000D_
EL_country.appendChild(DF_options);_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.


SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected

Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness

one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.


Comparison test of the different methods

_x000D_
_x000D_
const EL_select = document.querySelector('#country');_x000D_
const TPL_options = `_x000D_
  <option value="AF">Afghanistan</option>_x000D_
  <option value="AL">Albania</option>_x000D_
  <option value="HR">Croatia</option>_x000D_
  <option value="ID">Indonesia</option>_x000D_
  <option value="ZW">Zimbabwe</option>_x000D_
`;_x000D_
_x000D_
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver_x000D_
const mutationCB = (mutationsList, observer) => {_x000D_
  mutationsList.forEach(mu => {_x000D_
    const EL = mu.target;_x000D_
    if (mu.type === 'attributes') {_x000D_
      return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);_x000D_
    }_x000D_
  });_x000D_
};_x000D_
_x000D_
// (PREPARE SOME TEST FUNCTIONS)_x000D_
_x000D_
const testOptionsSelectedByProperty = () => {_x000D_
  const test = 'OPTION with Property selected:';_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.selected);_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testOptionsSelectedByAttribute = () => {_x000D_
  const test = 'OPTION with Attribute selected:'_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testSelect = () => {_x000D_
  console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);_x000D_
}_x000D_
_x000D_
const formReset = () => {_x000D_
  EL_select.value = '';_x000D_
  EL_select.innerHTML = TPL_options;_x000D_
  // Attach MutationObserver to every Option to track if Attribute will change_x000D_
  [...EL_select.options].forEach(EL_option => {_x000D_
    const observer = new MutationObserver(mutationCB);_x000D_
    observer.observe(EL_option, {attributes: true});_x000D_
  });_x000D_
}_x000D_
_x000D_
// -----------_x000D_
// LET'S TEST! _x000D_
_x000D_
console.log('\n1. Set SELECT value');_x000D_
formReset();_x000D_
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n2. Set HTMLElement.setAttribute()');_x000D_
formReset();_x000D_
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n3. Set HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.options[3].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.value = 'ZW'_x000D_
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
/* END */_x000D_
console.log('\n*. Getting MutationObservers out from call-stack...');
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:

EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!

will actually make the option selected

Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?

Instead test 3. (and 4.) using defaultSelected gives the expected results:

  • Attribute selected as a named Selectedness state.
  • Property selected on the Element Object, with a Boolean value.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

For me, when i wanted to clone from my repository, i had the same message noticed before "Permission denied (publickey) fatal: Could not read from remote repository". The solution for my case is to not use sudo before clone That's it.

Inserting the same value multiple times when formatting a string

incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}

You may like to have a read of this to get an understanding: String Formatting Operations.

What is the difference between <p> and <div>?

DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).

Find size of Git repository

You could use git-sizer. In the --verbose setting, the example output is (below). Look for the Total size of files line.

$ git-sizer --verbose
Processing blobs: 1652370
Processing trees: 3396199
Processing commits: 722647
Matching commits to trees: 722647
Processing annotated tags: 534
Processing references: 539
| Name                         | Value     | Level of concern               |
| ---------------------------- | --------- | ------------------------------ |
| Overall repository size      |           |                                |
| * Commits                    |           |                                |
|   * Count                    |   723 k   | *                              |
|   * Total size               |   525 MiB | **                             |
| * Trees                      |           |                                |
|   * Count                    |  3.40 M   | **                             |
|   * Total size               |  9.00 GiB | ****                           |
|   * Total tree entries       |   264 M   | *****                          |
| * Blobs                      |           |                                |
|   * Count                    |  1.65 M   | *                              |
|   * Total size               |  55.8 GiB | *****                          |
| * Annotated tags             |           |                                |
|   * Count                    |   534     |                                |
| * References                 |           |                                |
|   * Count                    |   539     |                                |
|                              |           |                                |
| Biggest objects              |           |                                |
| * Commits                    |           |                                |
|   * Maximum size         [1] |  72.7 KiB | *                              |
|   * Maximum parents      [2] |    66     | ******                         |
| * Trees                      |           |                                |
|   * Maximum entries      [3] |  1.68 k   | *                              |
| * Blobs                      |           |                                |
|   * Maximum size         [4] |  13.5 MiB | *                              |
|                              |           |                                |
| History structure            |           |                                |
| * Maximum history depth      |   136 k   |                                |
| * Maximum tag depth      [5] |     1     |                                |
|                              |           |                                |
| Biggest checkouts            |           |                                |
| * Number of directories  [6] |  4.38 k   | **                             |
| * Maximum path depth     [7] |    13     | *                              |
| * Maximum path length    [8] |   134 B   | *                              |
| * Number of files        [9] |  62.3 k   | *                              |
| * Total size of files    [9] |   747 MiB |                                |
| * Number of symlinks    [10] |    40     |                                |
| * Number of submodules       |     0     |                                |

[1]  91cc53b0c78596a73fa708cceb7313e7168bb146
[2]  2cde51fbd0f310c8a2c5f977e665c0ac3945b46d
[3]  4f86eed5893207aca2c2da86b35b38f2e1ec1fc8 (refs/heads/master:arch/arm/boot/dts)
[4]  a02b6794337286bc12c907c33d5d75537c240bd0 (refs/heads/master:drivers/gpu/drm/amd/include/asic_reg/vega10/NBIO/nbio_6_1_sh_mask.h)
[5]  5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c (refs/tags/v2.6.11)
[6]  1459754b9d9acc2ffac8525bed6691e15913c6e2 (589b754df3f37ca0a1f96fccde7f91c59266f38a^{tree})
[7]  78a269635e76ed927e17d7883f2d90313570fdbc (dae09011115133666e47c35673c0564b0a702db7^{tree})
[8]  ce5f2e31d3bdc1186041fdfd27a5ac96e728f2c5 (refs/heads/master^{tree})
[9]  532bdadc08402b7a72a4b45a2e02e5c710b7d626 (e9ef1fe312b533592e39cddc1327463c30b0ed8d^{tree})
[10] f29a5ea76884ac37e1197bef1941f62fda3f7b99 (f5308d1b83eba20e69df5e0926ba7257c8dd9074^{tree})

What is the difference between String and string in C#?

Both are same. But from coding guidelines perspective it's better to use string instead of String. This is what generally developers use. e.g. instead of using Int32 we use int as int is alias to Int32

FYI “The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

PySpark: multiple conditions in when clause

when in pyspark multiple conditions can be built using &(for and) and | (for or).

Note:In pyspark t is important to enclose every expressions within parenthesis () that combine to form the condition

%pyspark
dataDF = spark.createDataFrame([(66, "a", "4"), 
                                (67, "a", "0"), 
                                (70, "b", "4"), 
                                (71, "d", "4")],
                                ("id", "code", "amt"))
dataDF.withColumn("new_column",
       when((col("code") == "a") | (col("code") == "d"), "A")
      .when((col("code") == "b") & (col("amt") == "4"), "B")
      .otherwise("A1")).show()

In Spark Scala code (&&) or (||) conditions can be used within when function

//scala
val dataDF = Seq(
      (66, "a", "4"), (67, "a", "0"), (70, "b", "4"), (71, "d", "4"
      )).toDF("id", "code", "amt")
dataDF.withColumn("new_column",
       when(col("code") === "a" || col("code") === "d", "A")
      .when(col("code") === "b" && col("amt") === "4", "B")
      .otherwise("A1")).show()

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

Output:
+---+----+---+----------+
| id|code|amt|new_column|
+---+----+---+----------+
| 66|   a|  4|         A|
| 67|   a|  0|         A|
| 70|   b|  4|         B|
| 71|   d|  4|         A|
+---+----+---+----------+

This code snippet is copied from sparkbyexamples.com

How to fix ReferenceError: primordials is not defined in node

I faced the same issue. What I tried and worked for me:

  1. Check the version of NODE and GULP (combination of node v12 and gulp less than v4 doesn't work)

  2. I downgrade NPM version by:

    • sudo NPM install -g n
    • sudo n 10.16.0

It worked fine, then just follow instruction of your console.

C# - Print dictionary

Just to close this

foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
    //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

Changes to this

foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
    //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

How do I close an open port from the terminal on the Mac?

very simple find port 5900:

sudo lsof -i :5900

then considering 59553 as PID

sudo kill 59553

How to disable/enable a button with a checkbox if checked

I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.

$('input:checkbox').click(function () {
  if ($(this).is(':checked')) {
    $('#sendNewSms').click(function () {
      return false;
    });
  } else {
    $('#sendNewSms').unbind('click');
  }
});

The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.

var clickEvent = function () {
  return false;
};
document.getElementById('#checkbox').onclick(function () {
  if (document.getElementById('#checkbox').checked) {
    document
      .getElementById('#sendNewSms')
      .onclick(clickEvent);
  } else {
    document
      .getElementById('#sendNewSms')
      .removeEventListener('click', clickEvent, false);
  }
});

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

How to check if multiple array keys exists

Surprisingly array_keys_exist doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.

Note: each of the following solutions use concise […] array declaration syntax available in php 5.4+

array_diff + array_keys

if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
  // all keys found
} else {
  // not all
}

(hat tip to Kim Stacks)

This approach is the most brief I've found. array_diff() returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…) to be simply empty(…).

array_reduce + unset

if (0 === count(array_reduce(array_keys($source), 
    function($in, $key){ unset($in[array_search($key, $in)]); return $in; }, 
    ['story', 'message', '…'])))
{
  // all keys found
} else {
  // not all
}

Harder to read, easy to change. array_reduce() uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initial value of $in and then removing keys found in source we can expect to end with 0 elements if all keys were found.

The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.

array_filter & in_array

if (2 === count(array_filter(array_keys($source), function($key) { 
        return in_array($key, ['story', 'message']); }
    )))
{
  // all keys found
} else {
  // not all
}

Simpler to write than the array_reduce solution but slightly tricker to edit. array_filter is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2 to the number of items you expect.

This can be made more durable but verge's on preposterous readability:

$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
  // all keys found
} else {
  // not all
}

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

Ansible - Save registered variable to file

A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.

- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file

If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)

- hosts: web_servers
  serial: 1
  tasks:
  - local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file

Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs

How to download source in ZIP format from GitHub?

In chrome, if you hover your cursor on Download ZIP it will give you the link at the bottom of the browser

enter image description here

How to fix a Div to top of page with CSS only

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
height: 300px;
overflow: scroll; }

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

Google maps API V3 - multiple markers on exact same spot

@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    // BEGIN MODIFICATION (around line 715)
    MarkerClusterer.prototype.onClick = function() { 
        return true; 
    };
    // END MODIFICATION
    
  2. In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:

    // EXISTING CODE (around line 143)
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
    
    // BEGIN MODIFICATION
    var zoom = mc.getMap().getZoom();
    // Trying to pull this dynamically made the more zoomed in clusters not render
    // when then kind of made this useless. -NNC @ BNB
    // var maxZoom = mc.getMaxZoom();
    var maxZoom = 15;
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
        return mc.onClick(cClusterIcon);
    }
    // END MODIFICATION
    
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClick OVERRIDE
    markerCluster.onClick = function(clickedClusterIcon) { 
      return multiChoice(clickedClusterIcon.cluster_); 
    }
    

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(clickedCluster) {
      if (clickedCluster.getMarkers().length > 1)
      {
        // var markers = clickedCluster.getMarkers();
        // do something creative!
        return false;
      }
      return true;
    };
    

dereferencing pointer to incomplete type

I saw a question the other day where someone inadvertently used an incomplete type by specifying something like

struct a {
    int q; 
}; 
struct A *x; 
x->q = 3;

The compiler knew that struct A was a struct, despite A being totally undefined, by virtue of the struct keyword.

That was in C++, where such usage of struct is atypical (and, it turns out, can lead to foot-shooting). In C if you do

typedef struct a {
    ...
} a;

then you can use a as the typename and omit the struct later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try putting the e.Row.Cells[0].Visible = false; inside the RowCreated event of your grid.

protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Visible = false; // hides the first column
}

This way it auto-hides the whole column.

You don't have access to the generated columns through grid.Columns[i] in your gridview's DataBound event.

How can I convert a long to int in Java?

In Spring, there is a rigorous way to convert a long to int

not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);

convert long to int

PostgreSQL return result set as JSON array?

TL;DR

SELECT json_agg(t) FROM t

for a JSON array of objects, and

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:

[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]

9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.

9.2

9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )::jsonb
FROM t

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

or

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)

9.2

In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Documentation

Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.

Design

If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.

Nulls

Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t

Or

SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

How to compare two JSON have the same properties without order?

This question reminds of how to determine equality for two JavaScript objects. So, I would choose this general function

Compares JS objects:

function objectEquals(x, y) {
    // if both are function
    if (x instanceof Function) {
        if (y instanceof Function) {
            return x.toString() === y.toString();
        }
        return false;
    }
    if (x === null || x === undefined || y === null || y === undefined) { return x === y; }
    if (x === y || x.valueOf() === y.valueOf()) { return true; }

    // if one of them is date, they must had equal valueOf
    if (x instanceof Date) { return false; }
    if (y instanceof Date) { return false; }

    // if they are not function or strictly equal, they both need to be Objects
    if (!(x instanceof Object)) { return false; }
    if (!(y instanceof Object)) { return false; }

    var p = Object.keys(x);
    return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) ?
            p.every(function (i) { return objectEquals(x[i], y[i]); }) : false;
}

Converting Decimal to Binary Java

Integer.toString(n,8) // decimal to octal

Integer.toString(n,2) // decimal to binary

Integer.toString(n,16) //decimal to Hex

where n = decimal number.

Where do I find the current C or C++ standard documents?

The ISO C and C++ standards are bloody expensive. On the other hand, the INCITS republishes them for a lot less. http://www.techstreet.com/ seems to have the PDF for $30 (search for INCITS/ISO/IEC 14882:2003).

Hardcopy versions are available, too. Look for the British Standards Institute versions, published by Wiley.

OS X Terminal Colors

When I worked on Mac OS X in the lab I was able to get the terminal colors from using Terminal (rather than X11) and then editing the profile (from the Mac menu bar). The interface is a bit odd on the colors, but you have to set the modified theme as default.

Further settings worked by editing .bashrc.

How can I format a number into a string with leading zeros?

Since nobody has yet mentioned this, if you are using C# version 6 or above (i.e. Visual Studio 2015) then you can use string interpolation to simplify your code. So instead of using string.Format(...), you can just do this:

Key = $"{i:D2}";

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

How to remove certain characters from a string in C++?

If you have access to a compiler that supports variadic templates, you can use this:

#include <iostream>
#include <string>
#include <algorithm>

template<char ... CharacterList>
inline bool check_characters(char c) {
    char match_characters[sizeof...(CharacterList)] = { CharacterList... };
    for(int i = 0; i < sizeof...(CharacterList); ++i) {
        if(c == match_characters[i]) {
            return true;
        }
    }
    return false;
}

template<char ... CharacterList>
inline void strip_characters(std::string & str) {
    str.erase(std::remove_if(str.begin(), str.end(), &check_characters<CharacterList...>), str.end());
}

int main()
{
    std::string str("(555) 555-5555");
    strip_characters< '(',')','-' >(str);
    std::cout << str << std::endl;
}

C#: Dynamic runtime cast

Best I got so far:

dynamic DynamicCast(object entity, Type to)
{
    var openCast = this.GetType().GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
    var closeCast = openCast.MakeGenericMethod(to);
    return closeCast.Invoke(entity, new[] { entity });
}
static T Cast<T>(object entity) where T : class
{
    return entity as T;
}

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Here is my tip. Tested with vscode 1.21.1 (on MAC)

Put below config to tsconfig.json

"lib": [
"es2016",
"dom"
]

into compilerOptions

Restart IDE (this action is required :D )

Call static method with reflection

Class that will call the methods:

namespace myNamespace
{
    public class myClass
    {
        public static void voidMethodWithoutParameters()
        {
            // code here
        }
        public static string stringReturnMethodWithParameters(string param1, string param2)
        {
            // code here
            return "output";
        }
    }
}

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
                    
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

How can I get the number of records affected by a stored procedure?

WARNING: @@ROWCOUNT may return bogus data if the table being altered has triggers attached to it!

The @@ROWCOUNT will return the number of records affected by the TRIGGER, not the actual statement!

Darken background image on hover

If you have to use the current image and get a darker image then you need to create a new one. Else you can simply reduce the opacity of the .image class and the in the .image:hover you can put a higher value for opacity. But then the image without hover would look pale.

The best way would be to create two images and add the following :

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.9;   
}
.image:hover{
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook_hover.png');
}
}

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

How to set a Javascript object values dynamically?

simple as this myObj.name = value;

Entity Framework select distinct name

DBContext.TestAddresses.Select(m => m.NAME).Distinct();

if you have multiple column do like this:

DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();

In this example no duplicate CategoryId and no CategoryName i hope this will help you

Adding to an ArrayList Java

Instantiate a new ArrayList:

List<String> myList = new ArrayList<String>();

Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):

myList.add(yourElement);

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

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

Set the display.max_colwidth option to None (or -1 before version 1.0):

pd.set_option('display.max_colwidth', None)

set_option docs

For example, in iPython, we see that the information is truncated to 50 characters. Anything in excess is ellipsized:

Truncated result

If you set the display.max_colwidth option, the information will be displayed fully:

Non-truncated result

How do I make an attributed string using Swift?

Swift 5

    let attrStri = NSMutableAttributedString.init(string:"This is red")
    let nsRange = NSString(string: "This is red").range(of: "red", options: String.CompareOptions.caseInsensitive)
    attrStri.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font: UIFont.init(name: "PTSans-Regular", size: 15.0) as Any], range: nsRange)
    self.label.attributedText = attrStri

enter image description here

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Fan out was clearly what you wanted. fanout

read rabbitMQ tutorial: https://www.rabbitmq.com/tutorials/tutorial-three-javascript.html

here's my example:

Publisher.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create exchange for queues
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      await channel.publish(process.env.EXCHANGE_NAME, '', Buffer.from('msg'))
    } catch(error) {
      console.error(error)
    }
})

Subscriber.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create/Bind a consumer queue for an exchange broker
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      const queue = await channel.assertQueue('', {exclusive: true})
      channel.bindQueue(queue.queue, process.env.EXCHANGE_NAME, '')

      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C");
      channel.consume('', consumeMessage, {noAck: true});
    } catch(error) {
      console.error(error)
    }
});

here is an example i found in the internet. maybe can also help. https://www.codota.com/code/javascript/functions/amqplib/Channel/assertExchange

Change action bar color in android

onclick buttons c2 to fetch and change the color of action bar and notification bar according to button's background, hope this helps

int color = c2.getBackground()).getColor();
int colorlighter = -color * 40 / 100 + color;
getWindow().setNavigationBarColor(colorlighter);
getWindow().setStatusBarColor(colorlighter);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(color));

colorlighter is used to set color of notification bar a little lighter than action bar
color is the background color of button c2, according to which we change our color.

How can I change the thickness of my <hr> tag

For consistency remove any borders and use the height for the <hr> thickness. Adding a background color will style your <hr> with the height and color specified.

In your stylesheet:

hr {
    border: none;
    height: 1px;
    /* Set the hr color */
    color: #333; /* old IE */
    background-color: #333; /* Modern Browsers */
}

Or inline as you have it:

<hr style="height:1px;border:none;color:#333;background-color:#333;" />

Longer explanation here

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

AngularJS: Can't I set a variable value on ng-click?

You can use some thing like this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
    <p>_x000D_
      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
    </p>_x000D_
    <p>_x000D_
      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
    </p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

Set the space between Elements in Row Flutter

Row(
 children: <Widget>[
  Flexible(
   child: TextFormField()),
  Container(width: 20, height: 20),
  Flexible(
   child: TextFormField())
 ])

This works for me, there are 3 widgets inside row: Flexible, Container, Flexible

CSS selector for a checked radio button's label

You could use a bit of jQuery:

$('input:radio').click(function(){
    $('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});

You'd need to make sure your checked radio buttons have the correct class on page load as well.

How to write multiple line string using Bash with variables?

If you do not want variables to be replaced, you need to surround EOL with single quotes.

cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

Previous example:

$ cat /tmp/myconfig.conf 
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Get Folder Size from Windows Command Line

Easiest method to get just the total size is powershell, but still is limited by fact that pathnames longer than 260 characters are not included in the total

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

Eclipse projects not showing up after placing project files in workspace/projects

I had the same problem over and over again the solution that a have found works for now

  1. Close Eclipse.
  2. go to workspace.metadata.plugins
  3. remove org.eclipse.core.resources
  4. Start Eclipse
  5. Do File->Import
  6. General->Existing Projects into Workspace and import all the project from the workspace

Operand type clash: uniqueidentifier is incompatible with int

The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.

The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier

This is a simiple example:

use example
go
create table Test1 (
    id int primary key,
    item uniqueidentifier,
    inserted_at datetime
    )
go
create table Test2 (
    id int primary key,
    inserted_at datetime
    )
go
alter table Test2 add item uniqueidentifier;
go

--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());


insert into Test2 select * from Test1;

select * from Test1;
select * from Test2;


The error message is:

Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime

Get length of array?

If the variant is empty then an error will be thrown. The bullet-proof code is the following:

Public Function GetLength(a As Variant) As Integer
   If IsEmpty(a) Then
      GetLength = 0
   Else
      GetLength = UBound(a) - LBound(a) + 1
   End If
End Function

How to make sure docker's time syncs with that of the host?

Windows users:

The solution is very simple. Simply open a powershell prompt and enter:

docker run --privileged --rm alpine date -s "$(Get-Date ([datetime]::UtcNow) -UFormat "+%Y-%m-%d %H:%M:%S")"

To check that it works, run the command:

docker run --rm -it alpine date


My solution is inspired by something I found in docker forum thread. Anyways, it was the only solution that worked for me on docker desktop, except for restarting my machine (which also works). Here's a link to the original thread: https://forums.docker.com/t/syncing-clock-with-host/10432/23

The difference between the thread answer and mine is that mine converts the time to UTC time, which is necessary for e.g. AWS. Otherwise, the original answer from the forum looks like this:

docker run --privileged --rm alpine date -s "$(date -u "+%Y-%m-%d %H:%M:%S")"

Oracle - How to create a materialized view with FAST REFRESH and JOINS

The key checks for FAST REFRESH includes the following:

1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.

No 3 is easy to miss and worth highlighting here

height: calc(100%) not working correctly in CSS

I was searching why % doesn't seem to work. So, I tested out using 100vh instead of just setting it at 100% it seems that 100vh works really well across almost all browsers/devices.

example: you want to only display the top div to the user before it scrolls, like a hero banner module. But, at the top of the page is a navbar which is 68px in height. The following doesn't work for me at all doing just %

height: calc(100% - 68px); 

There's was no change. The page just stayed the same. However, when swapping this to "vh" instead it works great! The div block you assign it too will stay on the viewer's device hight only. Until they decide to scroll down the page.

height: calc(100vh - 68px); 

Change the +/- to include how big your header is on the top. If your navbar is say 120px in height then change 68px to 120px.

Hope this helps anyone who cannot get this working with using normal height: calc();

How to completely uninstall Android Studio on Mac?

Some of the files individually listed by Simon would also be found with something like the following command, but with some additional assurance about thoroughness, and without the recklessness of using rm -rf with wildcards:

find ~ \
  -path ~/Library/Caches/Metadata/Safari -prune -o \
  -iname \*android\*studio\* -print -prune

Also don't forget about the SDK, which is now separate from the application, and ~/.gradle/ (see vijay's answer).

How can I remove the search bar and footer added by the jQuery DataTables plugin?

var table = $("#datatable").DataTable({
   "paging": false,
   "ordering": false,
   "searching": false
});

Ant task to run an Ant target only if a file exists?

I think its worth referencing this similar answer: https://stackoverflow.com/a/5288804/64313

Here is a another quick solution. There are other variations possible on this using the <available> tag:

# exit with failure if no files are found
<property name="file" value="${some.path}/some.txt" />
<fail message="FILE NOT FOUND: ${file}">
    <condition><not>
        <available file="${file}" />
    </not></condition>
</fail>

Large WCF web service request failing with (400) HTTP Bad Request

For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.

The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.

This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).

Using different Web.config in development and production environment

This is one of the huge benefits of using the machine.config. At my last job, we had development, test and production environments. We could use the machine.config for things like connection strings (to the appropriate, dev/test/prod SQL machine).

This may not be a solution for you if you don't have access to the actual production machine (like, if you were using a hosting company on a shared host).

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

In my experience, this message occurs when the primary file (.mdf) has no space to save the metadata of the database. This file include the system tables and they only save their data into it.

Make some space in the file and the commands works again. That's all, Enjoy

Rails select helper - Default selected value, how?

Rails 3.0.9

select options_for_select([value1, value2, value3], default)

How to pass a null variable to a SQL Stored Procedure from C#.net code

    SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
    If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
        SQLParam.Value = DBNull.Value
    Else
        SQLParam.Value = p_RetailerID
    End If

Python pandas insert list into a cell

Also getting

ValueError: Must have equal len keys and value when setting with an iterable,

using .at rather than .loc did not make any difference in my case, but enforcing the datatype of the dataframe column did the trick:

df['B'] = df['B'].astype(object)

Then I could set lists, numpy array and all sorts of things as single cell values in my dataframes.

$_POST Array from html form

<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>


$id = implode(',',$_POST['id']);
echo $id

you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r.

print_r($_POST['id']);

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

Create an array of integers property in Objective-C

C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:

Supported Types

You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”

POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

If you need an array, you should use NSArray or NSData.

The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.

Force "git push" to overwrite remote files

You should be able to force your local revision to the remote repo by using

git push -f <remote> <branch>

(e.g. git push -f origin master). Leaving off <remote> and <branch> will force push all local branches that have set --set-upstream.

Just be warned, if other people are sharing this repository their revision history will conflict with the new one. And if they have any local commits after the point of change they will become invalid.

Update: Thought I would add a side-note. If you are creating changes that others will review, then it's not uncommon to create a branch with those changes and rebase periodically to keep them up-to-date with the main development branch. Just let other developers know this will happen periodically so they'll know what to expect.

Update 2: Because of the increasing number of viewers I'd like to add some additional information on what to do when your upstream does experience a force push.

Say I've cloned your repo and have added a few commits like so:

            D----E  topic
           /
A----B----C         development

But later the development branch is hit with a rebase, which will cause me to receive an error like so when I run git pull:

Unpacking objects: 100% (3/3), done.
From <repo-location>
 * branch            development     -> FETCH_HEAD
Auto-merging <files>
CONFLICT (content): Merge conflict in <locations>
Automatic merge failed; fix conflicts and then commit the result.

Here I could fix the conflicts and commit, but that would leave me with a really ugly commit history:

       C----D----E----F    topic
      /              /
A----B--------------C'  development

It might look enticing to use git pull --force but be careful because that'll leave you with stranded commits:

            D----E   topic

A----B----C'         development

So probably the best option is to do a git pull --rebase. This will require me to resolve any conflicts like before, but for each step instead of committing I'll use git rebase --continue. In the end the commit history will look much better:

            D'---E'  topic
           /
A----B----C'         development

Update 3: You can also use the --force-with-lease option as a "safer" force push, as mentioned by Cupcake in his answer:

Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:

git push <remote> <branch> --force-with-lease

You can learn more details about how to use --force-with-lease by reading any of the following:

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

Count indexes using "for" in Python

If you have some given list, and want to iterate over its items and indices, you can use enumerate():

for index, item in enumerate(my_list):
    print index, item

If you only need the indices, you can use range():

for i in range(len(my_list)):
    print i

Spring @Transactional - isolation, propagation

You can use like this:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public EventMessage<ModificaOperativitaRapporto> activate(EventMessage<ModificaOperativitaRapporto> eventMessage) {
//here some transaction related code
}

You can use this thing also:

public interface TransactionStatus extends SavepointManager {
    boolean isNewTransaction();
    boolean hasSavepoint();
    void setRollbackOnly();
    boolean isRollbackOnly();
    void flush();
    boolean isCompleted();
}

Remove all values within one list from another list?

>>> a = range(1, 10)
>>> [x for x in a if x not in [2, 3, 7]]
[1, 4, 5, 6, 8, 9]

Disabled UIButton not faded or grey

It looks like the following code works fine. But in some cases, this doesn't work.

sendButton.enabled = NO;
sendButton.alpha = 0.5;

If the above code doesn't work, please wrap it in Main Thread. so

dispatch_async(dispatch_get_main_queue(), ^{
    sendButton.enabled = NO;
    sendButton.alpha = 0.5
});

if you go with swift, like this

DispatchQueue.main.async {
    sendButton.isEnabled = false
    sendButton.alpha = 0.5
}

In addition, if you customized UIButton, add this to the Button class.

override var isEnabled: Bool {
    didSet {
        DispatchQueue.main.async {
            if self.isEnabled {
                self.alpha = 1.0
            }
            else {
                self.alpha = 0.5
            }
        }
    }
}

Thank you and enjoy coding!!!

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

How to yum install Node.JS on Amazon Linux

Official Documentation for EC2-Instance works for me: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html

 1. curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
 2. . ~/.nvm/nvm.sh
 3. nvm ls-remote (=> find your version x.x.x =>) nvm install  x.x.x
 4. node -e "console.log('Running Node.js ' + process.version)"

How to do vlookup and fill down (like in Excel) in R?

You could use mapvalues() from the plyr package.

Initial data:

dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))

> dat
  HouseType
1      Semi
2    Single
3       Row
4    Single
5 Apartment
6 Apartment
7       Row

Lookup / crosswalk table:

lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
  type_text type_num
1      Semi        1
2    Single        2
3       Row        3
4 Apartment        4

Create the new variable:

dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)

Or for simple replacements you can skip creating a long lookup table and do this directly in one step:

dat$house_type_num <- plyr::mapvalues(dat$HouseType,
                                      from = c("Semi", "Single", "Row", "Apartment"),
                                      to = c(1, 2, 3, 4))

Result:

> dat
  HouseType house_type_num
1      Semi              1
2    Single              2
3       Row              3
4    Single              2
5 Apartment              4
6 Apartment              4
7       Row              3

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

Check synchronously if file/directory exists in Node.js

The path module does not provide a synchronous version of path.exists so you have to trick around with the fs module.

Fastest thing I can imagine is using fs.realpathSync which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.

Angularjs prevent form submission when input validation fails

You can do:

<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">

No need for controller checks.

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Merging arrays with the same keys

Try this:

$array_one = ['ratio_type'];
$array_two = ['ratio_type', 'ratio_type'];
$array_three = ['ratio_type'];
$array_four = ['ratio_type'];
$array_five = ['ratio_type', 'ratio_type', 'ratio_type'];
$array_six = ['ratio_type'];
$array_seven = ['ratio_type'];
$array_eight = ['ratio_type'];

$all_array_elements = array_merge_recursive(
    $array_one,
    $array_two,
    $array_three,
    $array_four,
    $array_five,
    $array_six,
    $array_seven,
    $array_eight
);

foreach ($all_array_elements as $key => $value) {
    echo "[$key]" . ' - ' . $value . PHP_EOL;
}

// OR
var_dump($all_array_elements);

Remove whitespaces inside a string in javascript

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

MySql Inner Join with WHERE clause

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1 
   INNER JOIN table2
     ON table2.f_id = table1.f_id
 WHERE table2.f_type = 'InProcess'
   AND f_com_id = '430'
   AND f_status = 'Submitted' 

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

How to get Real IP from Visitor?

If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10)

<?php

$trustProxyIPs = ['151.101.2.10'];

$clientIP  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL;

if (in_array($clientIP, $trustProxyIPs)) {

    $headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'];

    foreach ($headers as $key => $header) {

        if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {

            $clientIP = $_SERVER[$header];

            break;
        }
    }
}

echo $clientIP;

This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.

What is the simplest C# function to parse a JSON string into an object?

You should create a structure that represents JSON keys (in case if you exactly know it) and then you can easily deserialize JSON string into your structure. In my examle I've deserialized a response from Google Cloud Message server:

class templateResponse
{
    public String multicast_id;
    public String success;
    public String failure;
    public String canonical_ids;
    public Result[] results;

    public class Result
    {
        public String message_id;
        public String registration_id;
        public String error;
    };
}

incoming JSON was:

"\"multicast_id\":7400896764380883211,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1351777805148960%39895cf0f9fd7ecd\"}]}"

So, use

templateResponse result = new JavaScriptSerializer().Deserialize<templateResponse>(json);

and you will get deserialized result object

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

What's the quickest way to multiply multiple cells by another number?

Are you asking how to do it in excel or how to do it in a VBA application? If you just want to do it in excel, here is one way.

How to get the file name from a full path using JavaScript?

The following line of JavaScript code will give you the file name.

var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);

.htaccess redirect www to non-www with SSL/HTTPS

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

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

This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy

Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS

Done in this order, it follows logic and no error occurs.

HERE is my FULL version in side htaccess with WordPress:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

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


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress