Programs & Examples On #Client side scripting

Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). It is used to create dynamic web pages, Most popular client side scripting language is JavaScript.

Apple Cover-flow effect using jQuery or other library?

There is an Apple style Gallery Slider over at http://www.jqueryfordesigners.com/slider-gallery/ which uses jQuery and the UI.

Getting query parameters from react-router hash fragment

Simple js solution:

queryStringParse = function(string) {
    let parsed = {}
    if(string != '') {
        string = string.substring(string.indexOf('?')+1)
        let p1 = string.split('&')
        p1.map(function(value) {
            let params = value.split('=')
            parsed[params[0]] = params[1]
        });
    }
    return parsed
}

And you can call it from anywhere using:

var params = this.queryStringParse(this.props.location.search);

Hope this helps.

Site does not exist error for a2ensite

Worked after I added .conf to the configuration file

CSS display:table-row does not expand when width is set to 100%

Tested answer:

In the .view-row css, change:

display:table-row;

to:

display:table

and get rid of "float". Everything will work as expected.

As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.

Working example:

<div class="view">
    <div>Type</div>
    <div>Name</div>                
</div>

with css:

.view {
  width:100%;
  display:table;
}

.view > div {
  width:50%;
  display: table-cell;
}

Output ("echo") a variable to a text file

Note: The answer below is written from the perspective of Windows PowerShell.
However, it applies to the cross-platform PowerShell Core edition (v6+) as well, except that the latter - commendably - consistently defaults to BOM-less UTF-8 character encoding, which is the most widely compatible one across platforms and cultures.
.


To complement bigtv's helpful answer helpful answer with a more concise alternative and background information:

# > $file is effectively the same as | Out-File $file
# Objects are written the same way they display in the console.
# Default character encoding is UTF-16LE (mostly 2 bytes per char.), with BOM.
# Use Out-File -Encoding <name> to change the encoding.
$env:computername > $file

# Set-Content calls .ToString() on each object to output.
# Default character encoding is "ANSI" (culture-specific, single-byte).
# Use Set-Content -Encoding <name> to change the encoding.
# Use Set-Content rather than Add-Content; the latter is for *appending* to a file.
$env:computername | Set-Content $file 

When outputting to a text file, you have 2 fundamental choices that use different object representations and, in Windows PowerShell (as opposed to PowerShell Core), also employ different default character encodings:

  • Out-File (or >) / Out-File -Append (or >>):

    • Suitable for output objects of any type, because PowerShell's default output formatting is applied to the output objects.

      • In other words: you get the same output as when printing to the console.
    • The default encoding, which can be changed with the -Encoding parameter, is Unicode, which is UTF-16LE in which most characters are encoded as 2 bytes. The advantage of a Unicode encoding such as UTF-16LE is that it is a global alphabet, capable of encoding all characters from all human languages.

      • In PSv5.1+, you can change the encoding used by > and >>, via the $PSDefaultParameterValues preference variable, taking advantage of the fact that > and >> are now effectively aliases of Out-File and Out-File -Append. To change to UTF-8, for instance, use:
        $PSDefaultParameterValues['Out-File:Encoding']='UTF8'
  • Set-Content / Add-Content:

    • For writing strings and instances of types known to have meaningful string representations, such as the .NET primitive data types (Booleans, integers, ...).

      • .psobject.ToString() method is called on each output object, which results in meaningless representations for types that don't explicitly implement a meaningful representation; [hashtable] instances are an example:
        @{ one = 1 } | Set-Content t.txt writes literal System.Collections.Hashtable to t.txt, which is the result of @{ one = 1 }.ToString().
    • The default encoding, which can be changed with the -Encoding parameter, is Default, which is the system's "ANSI" code page, a the single-byte culture-specific legacy encoding for non-Unicode applications, most commonly Windows-1252.
      Note that the documentation currently incorrectly claims that ASCII is the default encoding.

    • Note that Add-Content's purpose is to append content to an existing file, and it is only equivalent to Set-Content if the target file doesn't exist yet.
      Furthermore, the default or specified encoding is blindly applied, irrespective of the file's existing contents' encoding.

Out-File / > / Set-Content / Add-Content all act culture-sensitively, i.e., they produce representations suitable for the current culture (locale), if available (though custom formatting data is free to define its own, culture-invariant representation - see Get-Help about_format.ps1xml). This contrasts with PowerShell's string expansion (string interpolation in double-quoted strings), which is culture-invariant - see this answer of mine.

As for performance: Since Set-Content doesn't have to apply default formatting to its input, it performs better.


As for the OP's symptom with Add-Content:

Since $env:COMPUTERNAME cannot contain non-ASCII characters, Add-Content's output, using "ANSI" encoding, should not result in ? characters in the output, and the likeliest explanation is that the ? were part of the preexisting content in output file $file, which Add-Content appended to.

Can we open pdf file using UIWebView on iOS?

use this for open pdf file in webview

NSString *path = [[NSBundle mainBundle] pathForResource:@"mypdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

Look for an email containing something to this effect:

Missing Info.plist key - This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSAppleMusicUsageDescription key with a string value explaining to the user how the app uses this data.

Where the missing key could be any of a range of permissions, and may be something you're not even using. This comes up often for react-native applications especially.

If you get such an email, follow the advice regarding the Info.plist key and then resubmit the app.

Send cookies with curl

if you have Firebug installed on Firefox, just open the url. In the network panel, right-click and select Copy as cURL. You can see all curl parameters for this web call.

How do I set the value property in AngularJS' ng-options?

Like many said before, if I have data something like this:

countries : [
              {
                 "key": 1,
                 "name": "UAE"
             },
              {
                  "key": 2,
                  "name": "India"
              },
              {
                  "key": 3,
                  "name": "OMAN"
              }
         ]

I would use it like:

<select
    ng-model="selectedCountry"
    ng-options="obj.name for obj  in countries">
</select>

In your Controller you need to set an initial value to get rid of the first empty item:

 $scope.selectedCountry = $scope.countries[0];

 // You need to watch changes to get selected value
 $scope.$watchCollection(function() {
   return $scope.selectedCountry
 }, function(newVal, oldVal) {
     if (newVal === oldVal) {
       console.log("nothing has changed " + $scope.selectedCountry)
     } 
     else {
       console.log('new value ' + $scope.selectedCountry)
     }
 }, true)

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

Differences between ConstraintLayout and RelativeLayout

Intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.

Rules remind you of RelativeLayout, for example setting the left to the left of some other view.

app:layout_constraintBottom_toBottomOf="@+id/view1"

Unlike RelativeLayout, ConstraintLayout offers bias value that is used to position a view in terms of 0% and 100% horizontal and vertical offset relative to the handles (marked with circle). These percentages (and fractions) offer seamless positioning of the view across different screen densities and sizes.

app:layout_constraintHorizontal_bias="0.33" <!-- from 0.0 to 1.0 -->
app:layout_constraintVertical_bias="0.53" <!-- from 0.0 to 1.0 -->

Baseline handle (long pipe with rounded corners, below the circle handle) is used to align content of the view with another view reference.

Square handles (on each corner of the view) are used to resize the view in dps.

enter image description here

This is totally opinion based and my impression of ConstraintLayout

Understanding __get__ and __set__ and Python descriptors

I am trying to understand what Python's descriptors are and what they can be useful for.

Descriptors are class attributes (like properties or methods) with any of the following special methods:

  • __get__ (non-data descriptor method, for example on a method/function)
  • __set__ (data descriptor method, for example on a property instance)
  • __delete__ (data descriptor method)

These descriptor objects can be used as attributes on other object class definitions. (That is, they live in the __dict__ of the class object.)

Descriptor objects can be used to programmatically manage the results of a dotted lookup (e.g. foo.descriptor) in a normal expression, an assignment, and even a deletion.

Functions/methods, bound methods, property, classmethod, and staticmethod all use these special methods to control how they are accessed via the dotted lookup.

A data descriptor, like property, can allow for lazy evaluation of attributes based on a simpler state of the object, allowing instances to use less memory than if you precomputed each possible attribute.

Another data descriptor, a member_descriptor, created by __slots__, allow memory savings by allowing the class to store data in a mutable tuple-like datastructure instead of the more flexible but space-consuming __dict__.

Non-data descriptors, usually instance, class, and static methods, get their implicit first arguments (usually named cls and self, respectively) from their non-data descriptor method, __get__.

Most users of Python need to learn only the simple usage, and have no need to learn or understand the implementation of descriptors further.

In Depth: What Are Descriptors?

A descriptor is an object with any of the following methods (__get__, __set__, or __delete__), intended to be used via dotted-lookup as if it were a typical attribute of an instance. For an owner-object, obj_instance, with a descriptor object:

  • obj_instance.descriptor invokes
    descriptor.__get__(self, obj_instance, owner_class) returning a value
    This is how all methods and the get on a property work.

  • obj_instance.descriptor = value invokes
    descriptor.__set__(self, obj_instance, value) returning None
    This is how the setter on a property works.

  • del obj_instance.descriptor invokes
    descriptor.__delete__(self, obj_instance) returning None
    This is how the deleter on a property works.

obj_instance is the instance whose class contains the descriptor object's instance. self is the instance of the descriptor (probably just one for the class of the obj_instance)

To define this with code, an object is a descriptor if the set of its attributes intersects with any of the required attributes:

def has_descriptor_attrs(obj):
    return set(['__get__', '__set__', '__delete__']).intersection(dir(obj))

def is_descriptor(obj):
    """obj can be instance of descriptor or the descriptor class"""
    return bool(has_descriptor_attrs(obj))

A Data Descriptor has a __set__ and/or __delete__.
A Non-Data-Descriptor has neither __set__ nor __delete__.

def has_data_descriptor_attrs(obj):
    return set(['__set__', '__delete__']) & set(dir(obj))

def is_data_descriptor(obj):
    return bool(has_data_descriptor_attrs(obj))

Builtin Descriptor Object Examples:

  • classmethod
  • staticmethod
  • property
  • functions in general

Non-Data Descriptors

We can see that classmethod and staticmethod are Non-Data-Descriptors:

>>> is_descriptor(classmethod), is_data_descriptor(classmethod)
(True, False)
>>> is_descriptor(staticmethod), is_data_descriptor(staticmethod)
(True, False)

Both only have the __get__ method:

>>> has_descriptor_attrs(classmethod), has_descriptor_attrs(staticmethod)
(set(['__get__']), set(['__get__']))

Note that all functions are also Non-Data-Descriptors:

>>> def foo(): pass
... 
>>> is_descriptor(foo), is_data_descriptor(foo)
(True, False)

Data Descriptor, property

However, property is a Data-Descriptor:

>>> is_data_descriptor(property)
True
>>> has_descriptor_attrs(property)
set(['__set__', '__get__', '__delete__'])

Dotted Lookup Order

These are important distinctions, as they affect the lookup order for a dotted lookup.

obj_instance.attribute
  1. First the above looks to see if the attribute is a Data-Descriptor on the class of the instance,
  2. If not, it looks to see if the attribute is in the obj_instance's __dict__, then
  3. it finally falls back to a Non-Data-Descriptor.

The consequence of this lookup order is that Non-Data-Descriptors like functions/methods can be overridden by instances.

Recap and Next Steps

We have learned that descriptors are objects with any of __get__, __set__, or __delete__. These descriptor objects can be used as attributes on other object class definitions. Now we will look at how they are used, using your code as an example.


Analysis of Code from the Question

Here's your code, followed by your questions and answers to each:

class Celsius(object):
    def __init__(self, value=0.0):
        self.value = float(value)
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = float(value)

class Temperature(object):
    celsius = Celsius()
  1. Why do I need the descriptor class?

Your descriptor ensures you always have a float for this class attribute of Temperature, and that you can't use del to delete the attribute:

>>> t1 = Temperature()
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

Otherwise, your descriptors ignore the owner-class and instances of the owner, instead, storing state in the descriptor. You could just as easily share state across all instances with a simple class attribute (so long as you always set it as a float to the class and never delete it, or are comfortable with users of your code doing so):

class Temperature(object):
    celsius = 0.0

This gets you exactly the same behavior as your example (see response to question 3 below), but uses a Pythons builtin (property), and would be considered more idiomatic:

class Temperature(object):
    _celsius = 0.0
    @property
    def celsius(self):
        return type(self)._celsius
    @celsius.setter
    def celsius(self, value):
        type(self)._celsius = float(value)
  1. What is instance and owner here? (in get). What is the purpose of these parameters?

instance is the instance of the owner that is calling the descriptor. The owner is the class in which the descriptor object is used to manage access to the data point. See the descriptions of the special methods that define descriptors next to the first paragraph of this answer for more descriptive variable names.

  1. How would I call/use this example?

Here's a demonstration:

>>> t1 = Temperature()
>>> t1.celsius
0.0
>>> t1.celsius = 1
>>> 
>>> t1.celsius
1.0
>>> t2 = Temperature()
>>> t2.celsius
1.0

You can't delete the attribute:

>>> del t2.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

And you can't assign a variable that can't be converted to a float:

>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __set__
ValueError: invalid literal for float(): 0x02

Otherwise, what you have here is a global state for all instances, that is managed by assigning to any instance.

The expected way that most experienced Python programmers would accomplish this outcome would be to use the property decorator, which makes use of the same descriptors under the hood, but brings the behavior into the implementation of the owner class (again, as defined above):

class Temperature(object):
    _celsius = 0.0
    @property
    def celsius(self):
        return type(self)._celsius
    @celsius.setter
    def celsius(self, value):
        type(self)._celsius = float(value)

Which has the exact same expected behavior of the original piece of code:

>>> t1 = Temperature()
>>> t2 = Temperature()
>>> t1.celsius
0.0
>>> t1.celsius = 1.0
>>> t2.celsius
1.0
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't delete attribute
>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in celsius
ValueError: invalid literal for float(): 0x02

Conclusion

We've covered the attributes that define descriptors, the difference between data- and non-data-descriptors, builtin objects that use them, and specific questions about use.

So again, how would you use the question's example? I hope you wouldn't. I hope you would start with my first suggestion (a simple class attribute) and move on to the second suggestion (the property decorator) if you feel it is necessary.

Does file_get_contents() have a timeout setting?

It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:

$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You need to add dynamically created components to entryComponents inside your @NgModule

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog        
  ],
  entryComponents: [DialogResultExampleDialog]

Note: In some cases entryComponents under lazy loaded modules will not work, as a workaround put them in your app.module (root)

Looping over arrays, printing both index and value

You would find the array keys with "${!foo[@]}" (reference), so:

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How to repeat a char using printf?

#include <stdio.h>
#include <string.h>

void repeat_char(unsigned int cnt, char ch) {
    char buffer[cnt + 1];
    /*assuming you want to repeat the c character 30 times*/
    memset(buffer,ch,cnd); buffer[cnt]='\0';
    printf("%s",buffer)
}

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

In my case, this error started appearing randomly and wouldn't go away even after setting a timeout of 30000. Simply ending the process in the terminal and re-running the tests resolved the issue for me. I have also removed the timeout and tests are still passing again.

Change IPython/Jupyter notebook working directory

If you are using ipython in linux, then follow the steps:
!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py

Just specify the exclamation(!) symbol before your linux commands.

Error in finding last used cell in Excel with VBA

sub last_filled_cell()
msgbox range("A65536").end(xlup).row
end sub

Here, A65536 is the last cell in the Column A this code was tested on excel 2003.

How to check list A contains any value from list B?

I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

What is C# analog of C++ std::pair?

Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

and access values through t.Item1 and t.Item2, you can simply do it like that:

(string message, int count) = ("Hello", 4);

or even:

(var message, var count) = ("Hello", 4);

String concatenation in Ruby

You can concatenate in string definition directly:

nombre_apellido = "#{customer['first_name']} #{customer['last_name']} #{order_id}"

How to merge two json string in Python?

Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.

This was our solution:

from collections import Mapping
import json


original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)

for key, value in addition.iteritems():
    if key in original:
        original_value = original[key]
        if isinstance(value, Mapping) and isinstance(original_value, Mapping):
            merge_dicts(original_value, value)
        elif not (isinstance(value, Mapping) or 
                  isinstance(original_value, Mapping)):
            original[key] = value
        else:
            raise ValueError('Attempting to merge {} with value {}'.format(
                key, original_value))
    else:
        original[key] = value

You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

Why aren't programs written in Assembly more often?

I'm sure there are many reasons, but two quick reasons I can think of are

  1. Assembly code is definitely harder to read (I'm positive its more time-consuming to write as well)
  2. When you have a huge team of developers working on a product, it is helpful to have your code divided into logical blocks and protected by interfaces.

Adding a module (Specifically pymorph) to Spyder (Python IDE)

just use '!' before the pip command in spyder terminal and it will be fine

Eg:

!pip install imutils

Java: Check the date format of current string is according to required format or not

For example, if you want the date format to be "03.11.2017"

 if (String.valueOf(DateEdit.getText()).matches("([1-9]{1}|[0]{1}[1-9]{1}|[1]{1}[0-9]{1}|[2]{1}[0-9]{1}|[3]{1}[0-1]{1})" +
           "([.]{1})" +
           "([0]{1}[1-9]{1}|[1]{1}[0-2]{1}|[1-9]{1})" +
           "([.]{1})" +
           "([20]{2}[0-9]{2})"))
           checkFormat=true;
 else
           checkFormat=false;

 if (!checkFormat) {
 Toast.makeText(getApplicationContext(), "incorrect date format! Ex.23.06.2016", Toast.LENGTH_SHORT).show();
                }

How do I get a list of all the duplicate items using pandas in python?

df[df['ID'].duplicated() == True]

This worked for me

How to change background and text colors in Sublime Text 3

For How do I change the overall colors (background and font)?

For MAC : goto Sublime text -> Preferences -> color scheme

How to break out of while loop in Python?

A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break

Fill an array with random numbers

People don't see the nice cool Stream producers all over the Java libs.

public static double[] list(){
    return new Random().ints().asDoubleStream().toArray();
}

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just do it in the Base, that way any child can be Serialized, less code cleaner code.

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

What is the maximum length of a table name in Oracle?

The maximum name size is 30 characters because of the data dictionary which allows the storage only for 30 bytes

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

Center a popup window on screen?

Source: http://www.nigraphic.com/blog/java-script/how-open-new-window-popup-center-screen

function PopupCenter(pageURL, title,w,h) {
  var left = (screen.width/2)-(w/2);
  var top = (screen.height/2)-(h/2);
  var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
  return targetWin;
} 

java.util.Date to XMLGregorianCalendar

Here is a method for converting from a GregorianCalendar to XMLGregorianCalendar; I'll leave the part of converting from a java.util.Date to GregorianCalendar as an exercise for you:

import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class DateTest {

   public static void main(final String[] args) throws Exception {
      GregorianCalendar gcal = new GregorianCalendar();
      XMLGregorianCalendar xgcal = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gcal);
      System.out.println(xgcal);
   }

}

EDIT: Slooow :-)

Using an HTTP PROXY - Python

Just wanted to mention, that you also may have to set the https_proxy OS environment variable in case https URLs need to be accessed. In my case it was not obvious to me and I tried for hours to discover this.

My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py

How to run Node.js as a background process and never die?

Try this for a simple solution

cmd & exit

HashMap and int as key

If you code in Android, there is SparseArray, mapping integer to object.

Two values from one input in python?

If you need to take two integers say a,b in python you can use map function.
Suppose input is,

1
5 3
1 2 3 4 5

where 1 represent test case, 5 represent number of values and 3 represents a task value and in next line given 5 values, we can take such input using this method in PYTH 2.x Version.

testCases=int(raw_input())
number, taskValue = map(int, raw_input().split())
array = map(int, raw_input().split())

You can replace 'int' in map() with another datatype needed.

How do I find Waldo with Mathematica?

I've found Waldo!

waldo had been found

How I've done it

First, I'm filtering out all colours that aren't red

waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];

Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.

corr = ImageCorrelate[red, 
   Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]], 
   NormalizedSquaredEuclideanDistance];

I use Binarize to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation

pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];

I had to play around a little with the level. If the level is too high, too many false positives are picked out.

Finally I'm combining this result with the original image to get the result above

found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

Does --disable-web-security Work In Chrome Anymore?

If you want to automate this: Kill chrome from task Manager First. In Windows - Right Click (or Shift+right click, in-case of taskbar) on Chrome Icon. Select Properties. In "Target" text-box, add --disable-web-security flag.

So text in text-box should look like

C:\Users\njadhav\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --disable-web-security

Click Ok and launch chrome.

How do I catch a PHP fatal (`E_ERROR`) error?

You can't catch/handle fatal errors, but you can log/report them. For quick debugging I modified one answer to this simple code

function __fatalHandler()
{
    $error = error_get_last();

    // Check if it's a core/fatal error, otherwise it's a normal shutdown
    if ($error !== NULL && in_array($error['type'],
        array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
              E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {

        echo "<pre>fatal error:\n";
        print_r($error);
        echo "</pre>";
        die;
    }
}

register_shutdown_function('__fatalHandler');

Can someone explain __all__ in Python?

__all__ is used to document the public API of a Python module. Although it is optional, __all__ should be used.

Here is the relevant excerpt from the Python language reference:

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__ is absent:

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

[...]

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as os.path or a package's __init__ module that exposes functionality from submodules.

Furthermore, as pointed out in other answers, __all__ is used to enable wildcard importing for packages:

The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

What is the difference between Jupyter Notebook and JupyterLab?

To answer your question directly:

The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:

JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab

But you would also like to also know this:

Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.

A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.

And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:

enter image description here

And now you have these tools at your disposal:

  1. View Files, running kernels, Commands, Notebook Tools, Open Tabs or Extension manager
  2. Run cells using, among other options, Ctrl+Enter
  3. Run single expression, line or highlighted text using menu options or keyboard shortcuts
  4. Run code directly in a console using Shift+Enter
  5. Inspect variables, dataframes or plots quickly and easily in a console without cluttering your notebook output.

Difference between Static methods and Instance methods

The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :) Same is the case with variables.

Passing HTML to template using Flask/Jinja2

When you have a lot of variables that don't need escaping, you can use an autoescape block:

{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

Full path from file input using jQuery

Well, getting full path is not possible but we can have a temporary path.

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
    <br>
<img src="" width="200" style="display:none;" />
        <br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',// leave it for port 3306
    'username' => 'yourUserhere',
    'password' => 'yourPassword',
    'database' => 'yourDatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Or with the default settings:

$db['default'] = array(
        'dsn'   => '',
        'hostname' => '127.0.0.1:8889',// leave it for port 8889
        'username' => 'yourUserhere',
        'password' => 'yourPassword',
        'database' => 'yourDatabase',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
    );

Read XML file into XmlDocument

XmlDocument doc = new XmlDocument();
   doc.Load("MonFichierXML.xml");

    XmlNode node = doc.SelectSingleNode("Magasin");

    XmlNodeList prop = node.SelectNodes("Items");

    foreach (XmlNode item in prop)
    {
        items Temp = new items();
        Temp.AssignInfo(item);
        lstitems.Add(Temp);
    }

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

This is because the LEFT OUTER Join is doing more work than an INNER Join BEFORE sending the results back.

The Inner Join looks for all records where the ON statement is true (So when it creates a new table, it only puts in records that match the m.SubID = a.SubID). Then it compares those results to your WHERE statement (Your last modified time).

The Left Outer Join...Takes all of the records in your first table. If the ON statement is not true (m.SubID does not equal a.SubID), it simply NULLS the values in the second table's column for that recordset.

The reason you get the same number of results at the end is probably coincidence due to the WHERE clause that happens AFTER all of the copying of records.

Join (SQL) Wikipedia

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

Multi-Line Comments in Ruby?

Despite the existence of =begin and =end, the normal and a more correct way to comment is to use #'s on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.

How to control the width and height of the default Alert Dialog in Android?

Only a slight change in Sat Code, set the layout after show() method of AlertDialog.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.

Or you can do it in my way.

alertDialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 150;
lp.height = 500;
lp.x=-170;
lp.y=100;
alertDialog.getWindow().setAttributes(lp);

Fastest way to serialize and deserialize .NET objects

You can try Salar.Bois serializer which has a decent performance. Its focus is on payload size but it also offers good performance.

There are benchmarks in the Github page if you wish to see and compare the results by yourself.

https://github.com/salarcode/Bois

How to break lines at a specific character in Notepad++?

If the text contains \r\n that need to be converted into new lines use the 'Extended' or 'Regular expression' modes and escape the backslash character in 'Find what':

Find what: \\r\\n

Replace with: \r\n

How to use function srand() with time.h?

#include"stdio.h"
#include"conio.h"
#include"time.h"

void main()
{
  time_t t;
  int i;
  srand(time(&t));

  for(i=1;i<=10;i++)
    printf("%c\t",rand()%10);
  getch();
}

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

Get the ID of a drawable in ImageView

Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:

  • Load a drawable into memory and compare ConstantState or bitmap itself to other one.
  • Set a tag with drawable id into a view and compare tags when you need that.

Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.

So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView

If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:

TagViewUtils.getTag(view, ViewTag.IMAGEVIEW_SRC.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_LEFT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_TOP.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_RIGHT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_BOTTOM.id)
TagViewUtils.getTag(view, ViewTag.VIEW_BACKGROUND.id)
TagViewUtils.getTag(view, ViewTag.VIEW_FOREGROUND.id)

The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github. If you set a drawable in runtime you can use convenient library methods:

setImageViewResource(ImageView view, int id)

In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:

fun ImageView.setImageResourceWithTag(@DrawableRes int id) {
    TagViewUtils.setImageViewResource(this, id)
}

You can find additional info in Tagging in runtime

Android Closing Activity Programmatically

finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.

ERROR in ./node_modules/css-loader?

try using

npm rebuild node-sass

SVN: Is there a way to mark a file as "do not commit"?

I don't believe there is a way to ignore a file in the repository. We often run into this with web.config and other configuration files.

Although not perfect, the solution I most often see and use is to have .default file and an nant task to create local copies.

For example, in the repo is a file called web.config.default that has default values. Then create a nant task that will rename all the web.config.default files to web.config that can then be customized to local values. This task should be called when a new working copy is retrieved or a build is run.

You'll also need to ignore the web.config file that is created so that it isn't committed to the repository.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Iterate through pairs of items in a Python list

>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
...     print a[n],a[n+1]
...
5 7
7 11
11 4
4 5

Converting DateTime format using razor

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")

How do I install a module globally using npm?

You might not have write permissions to install a node module in the global location such as /usr/local/lib/node_modules, in which case run npm install -g package as root.

Java: How to convert List to Map

Since Java 8, the answer by @ZouZou using the Collectors.toMap collector is certainly the idiomatic way to solve this problem.

And as this is such a common task, we can make it into a static utility.

That way the solution truly becomes a one-liner.

/**
 * Returns a map where each entry is an item of {@code list} mapped by the
 * key produced by applying {@code mapper} to the item.
 *
 * @param list the list to map
 * @param mapper the function to produce the key from a list item
 * @return the resulting map
 * @throws IllegalStateException on duplicate key
 */
public static <K, T> Map<K, T> toMapBy(List<T> list,
        Function<? super T, ? extends K> mapper) {
    return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}

And here's how you would use it on a List<Student>:

Map<Long, Student> studentsById = toMapBy(students, Student::getId);

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:

Producer:

@Service
public void FooServiceImpl implements FooService{}

Consumer:

@Autowired
private FooService fooService;

or

@Autowired
private void setFooService(FooService fooService) {}

but not ok if you use it by name:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");

It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined In this case, assigning name to @Service("fooService") would make it work.

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

How does delete[] know it's an array?

The answer:

int* pArray = new int[5];

int size = *(pArray-1);

Posted above is not correct and produces invalid value. The "-1"counts elements On 64 bit Windows OS the correct buffer size resides in Ptr - 4 bytes address

Safely limiting Ansible playbooks to a single machine?

AWS users using the EC2 External Inventory Script can simply filter by instance id:

ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts

This works because the inventory script creates default groups.

Does IMDB provide an API?

https://deanclatworthy.com/tools.html is an IMDB API but has been down due to abuse.

How to round up value C# to the nearest integer?

It is also possible to round negative integers

// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply:          c * a  
// 2.) if c is negative:  (c>0? subtract half of the dividend 
//                              (b>>1) is bit shift right = (b/2)
//     if c is positive:  else  add half of the dividend 
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)

Extended from a tip somewhere else in here. Sorry, missed from where.

/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>

int main () {
   //rounding negative int
   // doing something like d = c * 3/4
   int a=3;
   int b=4;
   int c=-5;
   int d;
   int s=c;
   int e=c+10;


   for(int f=s; f<=e; f++) {
      printf("%d\t",f);

      double cd=f, ad=a, bd=b , dd;

      // d = c * 3/4  with double
      dd = cd * ad / bd;

      printf("%.2f\t",dd);
      printf("%.1f\t",dd);        
      printf("%.0f\t",dd);

      // try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
      // doing div before mul on purpose
      dd =(double)c * ((double)a / (double)b);
      printf("%.2f\t",dd);

      c=f;
      // d = c * 3/4  with integer rounding
      d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
      printf("%d\t",d);
      puts("");
  }
 return 0;
}

/* test output
in  2f     1f   0f cast int   
-5  -3.75   -3.8    -4  -3.75   -4  
-4  -3.00   -3.0    -3  -3.75   -3  
-3  -2.25   -2.2    -2  -3.00   -2  
-2  -1.50   -1.5    -2  -2.25   -2  
-1  -0.75   -0.8    -1  -1.50   -1  
 0   0.00    0.0     0  -0.75    0  
 1   0.75    0.8     1   0.00    1  
 2   1.50    1.5     2   0.75    2  
 3   2.25    2.2     2   1.50    2  
 4   3.00    3.0     3   2.25  3    
 5   3.75    3.8     4   3.00   

// by the way evolution: 
// Is there any decent small integer library out there for that by now?

C# Clear Session

Found this article on net, very relevant to this topic. So posting here.

ASP.NET Internals - Clearing ASP.NET Session variables

Multiple files upload in Codeigniter

_x000D_
_x000D_
<?php

if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
            $image_path = array();          
            $count = count($_FILES[$input_name]['name']);   
            for($key =0; $key <$count; $key++){     
                $_FILES['file']['name']     = $_FILES[$input_name]['name'][$key]; 
                $_FILES['file']['type']     = $_FILES[$input_name]['type'][$key]; 
                $_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key]; 
                $_FILES['file']['error']     = $_FILES[$input_name]['error'][$key]; 
                $_FILES['file']['size']     = $_FILES[$input_name]['size'][$key]; 
                    
                $config['file_name'] = $_FILES[$input_name]['name'][$key];                      
                $this->upload->initialize($config); 
                
                if($this->upload->do_upload('file')) {
                    $data = $this->upload->data();
                    $image_path[$key] = $path ."$data[file_name]";                  
                }else{
                    $error =  $this->upload->display_errors();
                $this->session->set_flashdata('msg_error',"image upload! ".$error);
                }   
            }
            return json_encode($image_path);
        }
    
    
   ?>
_x000D_
_x000D_
_x000D_

Simplest way to wait some asynchronous tasks complete, in Javascript?

All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.

What does PHP keyword 'var' do?

In PHP7.3 still working...

https://www.php.net/manual/en/language.oop5.visibility.php

If declared using var, the property will be defined as public.

Access Https Rest Service using Spring RestTemplate

Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java

public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
    try {
        if (!(connection instanceof HttpsURLConnection)) {
            throw new RuntimeException("An instance of HttpsURLConnection is expected");
        }

        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                }
        };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

        httpsConnection.setHostnameVerifier((hostname, session) -> true);

        super.prepareConnection(httpsConnection, httpMethod);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

/**
 * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
 * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
 */
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

    private final SSLSocketFactory delegate;

    public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port);
        return overrideProtocol(underlyingSocket);
    }

    @Override
    public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
        final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
        return overrideProtocol(underlyingSocket);
    }

    private Socket overrideProtocol(final Socket socket) {
        if (!(socket instanceof SSLSocket)) {
            throw new RuntimeException("An instance of SSLSocket is expected");
        }
        ((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
        return socket;
    }
}
}

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

Using Python's os.path, how do I go up one directory?

os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))

As far as where the templates folder should go, I don't know since Django 1.4 just came out and I haven't looked at it yet. You should probably ask another question on SE to solve that issue.

You can also use normpath to clean up the path, rather than abspath. However, in this situation, Django expects an absolute path rather than a relative path.

For cross platform compatability, use os.pardir instead of '..'.

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

How to clear jQuery validation error messages?

If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.

this.invalid = {};

MySQL - count total number of rows in php

for PHP 5.3 using PDO

<?php
    $staff=$dbh->prepare("SELECT count(*) FROM staff_login");
    $staff->execute();
    $staffrow = $staff->fetch(PDO::FETCH_NUM);
    $staffcount = $staffrow[0];


    echo $staffcount;
?>

WiX tricks and tips

  1. Keep variables in a separate wxi include file. Enables re-use, variables are faster to find and (if needed) allows for easier manipulation by an external tool.

  2. Define Platform variables for x86 and x64 builds

    <!-- Product name as you want it to appear in Add/Remove Programs-->
    <?if $(var.Platform) = x64 ?>
      <?define ProductName = "Product Name (64 bit)" ?>
      <?define Win64 = "yes" ?>
      <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
    <?else ?>
      <?define ProductName = "Product Name" ?>
      <?define Win64 = "no" ?>
      <?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
    <?endif ?>
    
  3. Store the installation location in the registry, enabling upgrades to find the correct location. For example, if a user sets custom install directory.

     <Property Id="INSTALLLOCATION">
        <RegistrySearch Id="RegistrySearch" Type="raw" Root="HKLM" Win64="$(var.Win64)"
                  Key="Software\Company\Product" Name="InstallLocation" />
     </Property>
    

    Note: WiX guru Rob Mensching has posted an excellent blog entry which goes into more detail and fixes an edge case when properties are set from the command line.

    Examples using 1. 2. and 3.

    <?include $(sys.CURRENTDIR)\Config.wxi?>
    <Product ... >
      <Package InstallerVersion="200" InstallPrivileges="elevated"
               InstallScope="perMachine" Platform="$(var.Platform)"
               Compressed="yes" Description="$(var.ProductName)" />
    

    and

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="$(var.PlatformProgramFilesFolder)">
        <Directory Id="INSTALLLOCATION" Name="$(var.InstallName)">
    
  4. The simplest approach is always do major upgrades, since it allows both new installs and upgrades in the single MSI. UpgradeCode is fixed to a unique Guid and will never change, unless we don't want to upgrade existing product.

    Note: In WiX 3.5 there is a new MajorUpgrade element which makes life even easier!

  5. Creating an icon in Add/Remove Programs

    <Icon Id="Company.ico" SourceFile="..\Tools\Company\Images\Company.ico" />
    <Property Id="ARPPRODUCTICON" Value="Company.ico" />
    <Property Id="ARPHELPLINK" Value="http://www.example.com/" />
    
  6. On release builds we version our installers, copying the msi file to a deployment directory. An example of this using a wixproj target called from AfterBuild target:

    <Target Name="CopyToDeploy" Condition="'$(Configuration)' == 'Release'">
      <!-- Note we append AssemblyFileVersion, changing MSI file name only works with Major Upgrades -->
      <Copy SourceFiles="$(OutputPath)$(OutputName).msi" 
            DestinationFiles="..\Deploy\Setup\$(OutputName) $(AssemblyFileVersion)_$(Platform).msi" />
    </Target>
    
  7. Use heat to harvest files with wildcard (*) Guid. Useful if you want to reuse WXS files across multiple projects (see my answer on multiple versions of the same product). For example, this batch file automatically harvests RoboHelp output.

    @echo off  
    robocopy ..\WebHelp "%TEMP%\WebHelpTemp\WebHelp" /E /NP /PURGE /XD .svn  
    "%WIX%bin\heat" dir "%TEMP%\WebHelp" -nologo -sfrag -suid -ag -srd -dir WebHelp -out WebHelp.wxs -cg WebHelpComponent -dr INSTALLLOCATION -var var.WebDeploySourceDir 
    

    There's a bit going on, robocopy is stripping out Subversion working copy metadata before harvesting; the -dr root directory reference is set to our installation location rather than default TARGETDIR; -var is used to create a variable to specify the source directory (web deployment output).

  8. Easy way to include the product version in the welcome dialog title by using Strings.wxl for localization. (Credit: saschabeaumont. Added as this great tip is hidden in a comment)

    <WixLocalization Culture="en-US" xmlns="http://schemas.microsoft.com/wix/2006/localization">
        <String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
    </WixLocalization>
    
  9. Save yourself some pain and follow Wim Coehen's advice of one component per file. This also allows you to leave out (or wild-card *) the component GUID.

  10. Rob Mensching has a neat way to quickly track down problems in MSI log files by searching for value 3. Note the comments regarding internationalization.

  11. When adding conditional features, it's more intuitive to set the default feature level to 0 (disabled) and then set the condition level to your desired value. If you set the default feature level >= 1, the condition level has to be 0 to disable it, meaning the condition logic has to be the opposite to what you'd expect, which can be confusing :)

    <Feature Id="NewInstallFeature" Level="0" Description="New installation feature" Absent="allow">
      <Condition Level="1">NOT UPGRADEFOUND</Condition>
    </Feature>
    <Feature Id="UpgradeFeature" Level="0" Description="Upgrade feature" Absent="allow">
      <Condition Level="1">UPGRADEFOUND</Condition>
    </Feature>
    

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Prevent direct access to a php include file

An alternative (or complement) to Chuck's solution would be to deny access to files matching a specific pattern by putting something like this in your .htaccess file

<FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>

How to delete the contents of a folder?

To delete all the files inside the directory as well as its sub-directories, without removing the folders themselves, simply do this:

import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
    for file in files:
        os.remove(os.path.join(root, file))

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

npm check and update package if needed

To check if any module in a project is 'old':

npm outdated

'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.

For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:

[email protected] node_modules/xml2js current=0.2.6

To update all dependencies, if you are confident this is desirable:

npm update

Or, to update a single dependency such as xml2js:

npm update xml2js

How to convert C++ Code to C

http://llvm.org/docs/FAQ.html#translatecxx

It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.

Usage sytax from the command line is as follows for version 9.0.1:

clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c  CPPtoC.bc -o CPPtoC.c

For older versions (unsure of transition version), use the following syntax:

llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c  CPPtoC.bc -o CPPtoC.c

Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.

Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.

EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.

Deleting multiple columns based on column names in Pandas

The below worked for me:

for col in df:
    if 'Unnamed' in col:
        #del df[col]
        print col
        try:
            df.drop(col, axis=1, inplace=True)
        except Exception:
            pass

In Angular, how to add Validator to FormControl after control is created?

To add onto what @Delosdos has posted.

Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

This is an amazing way to programmatically set your form validation.

Error including image in Latex

Using .jpg files do not forget about compiling directly to .pdf (pdflatex) and use: graphicx package with pdftex option (\usepackage[pdftex]{graphicx}).

Where should I put <script> tags in HTML markup?

I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.

shared global variables in C

If you're sharing code between C and C++, remember to add the following to the shared.hfile:

#ifdef __cplusplus
extern "C" {
#endif

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus
}
#endif

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

Getting windbg without the whole WDK?

WinDbg is now available separately via MS Store. It's called "Preview" but I tested it to analyse some memory dumps and it works fine.

If you're on Windows 10 - launch MS Store, type "WinDbg" in the search box and voi-la - you have it. The download is approx. 100mb. It will downlaod required symbols automatically.

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

What is Turing Complete?

Super-brief summary from what Professor Brasilford explains in this video.

Turing Complete ? do anything that a Turing Machine can do.

  1. It has conditional branching (i.e. "if statement"). Also, implies "go to" and thus permitting loop.

  2. It has arbitrary amount of memory (e.g. long enough tape) that the program needs.

Combine several images horizontally with Python

Edit: DTing's answer is more applicable to your question since it uses PIL, but I'll leave this up in case you want to know how to do it in numpy.

Here is a numpy/matplotlib solution that should work for N images (only color images) of any size/shape.

import numpy as np
import matplotlib.pyplot as plt

def concat_images(imga, imgb):
    """
    Combines two color image ndarrays side-by-side.
    """
    ha,wa = imga.shape[:2]
    hb,wb = imgb.shape[:2]
    max_height = np.max([ha, hb])
    total_width = wa+wb
    new_img = np.zeros(shape=(max_height, total_width, 3))
    new_img[:ha,:wa]=imga
    new_img[:hb,wa:wa+wb]=imgb
    return new_img

def concat_n_images(image_path_list):
    """
    Combines N color images from a list of image paths.
    """
    output = None
    for i, img_path in enumerate(image_path_list):
        img = plt.imread(img_path)[:,:,:3]
        if i==0:
            output = img
        else:
            output = concat_images(output, img)
    return output

Here is example use:

>>> images = ["ronda.jpeg", "rhod.jpeg", "ronda.jpeg", "rhod.jpeg"]
>>> output = concat_n_images(images)
>>> import matplotlib.pyplot as plt
>>> plt.imshow(output)
>>> plt.show()

enter image description here

How do I restrict a float value to only two places after the decimal point in C?

double f_round(double dval, int n)
{
    char l_fmtp[32], l_buf[64];
    char *p_str;
    sprintf (l_fmtp, "%%.%df", n);
    if (dval>=0)
            sprintf (l_buf, l_fmtp, dval);
    else
            sprintf (l_buf, l_fmtp, dval);
    return ((double)strtod(l_buf, &p_str));

}

Here n is the number of decimals

example:

double d = 100.23456;

printf("%f", f_round(d, 4));// result: 100.2346

printf("%f", f_round(d, 2));// result: 100.23

How to use ArrayList's get() method

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of Strings:

List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");

Which can be visualised as: A visual representation of the array list Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1 So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

Hibernate Error: a different object with the same identifier value was already associated with the session

just commit current transaction.

currentSession.getTransaction().commit();

now you can begin another Transaction and do anything on entity

Setting an image for a UIButton in code

Before this would work for me I had to resize the button frame explicitly based on the image frame size.

UIImage *listImage = [UIImage imageNamed:@"list_icon.png"];
UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];

// get the image size and apply it to the button frame
CGRect listButtonFrame = listButton.frame;
listButtonFrame.size = listImage.size;
listButton.frame = listButtonFrame;

[listButton setImage:listImage forState:UIControlStateNormal];
[listButton addTarget:self.navigationController.parentViewController 
               action:@selector(revealToggle:) 
     forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton = 
  [[UIBarButtonItem alloc] initWithCustomView:listButton];

self.navigationItem.leftBarButtonItem = jobsButton;

How to return the current timestamp with Moment.js?

Try this way:

console.log(moment().format('L'));
moment().format('L');    // 05/25/2018
moment().format('l');    // 5/25/2018

Format Dates:

moment().format('MMMM Do YYYY, h:mm:ss a'); // May 25th 2018, 2:02:13 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY");               // May 25th 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                          // 2018-05-25T14:02:13-05:00

Visit: https://momentjs.com/ for more info.

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

How to fix ReferenceError: primordials is not defined in node

I suggest you first make sure NPM install is not your problem. Then you downgrade node and gulp versions. I used node 10.16.1 and gulp 3.9.1.

To downgrade your gulp you can try

npm install gulp@^3.9.1

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

If you move your datadir, you not only need to give the new datadir permissions, but you need to ensure all parent directories have permission.

I moved my datadir to a hard drive, mounted in Ubuntu as:

/media/*user*/Data/

and my datadir was Databases.

I had to set permissions to 771 to each of the media, user and Data directories:

sudo chmod 771 *DIR*

If this does not work, another way you can get mysql to work is to change user in /etc/mysql/my.cnf to root; though there are no doubt some issues with doing that from a security perspective.

Drop unused factor levels in a subsetted data frame

Have tried most of the examples here if not all but none seem to be working in my case. After struggling for quite some time I have tried using as.character() on the factor column to change it to a col with strings which seems to working just fine.

Not sure for performance issues.

Is there a C++ decompiler?

You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.

If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.

How to get system time in Java without creating a new Date

Use System.currentTimeMillis() or System.nanoTime().

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

Regex to match only letters

pattern = /[a-zA-Z]/

puts "[a-zA-Z]: #{pattern.match("mine blossom")}" OK

puts "[a-zA-Z]: #{pattern.match("456")}"

puts "[a-zA-Z]: #{pattern.match("")}"

puts "[a-zA-Z]: #{pattern.match("#$%^&*")}"

puts "[a-zA-Z]: #{pattern.match("#$%^&*A")}" OK

How do I get logs/details of ansible-playbook module executions?

Using callback plugins, you can have the stdout of your commands output in readable form with the play: gist: human_log.py

Edit for example output:

 _____________________________________
< TASK: common | install apt packages >
 -------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


changed: [10.76.71.167] => (item=htop,vim-tiny,curl,git,unzip,update-motd,ssh-askpass,gcc,python-dev,libxml2,libxml2-dev,libxslt-dev,python-lxml,python-pip)

stdout:
Reading package lists...
Building dependency tree...
Reading state information...
libxslt1-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 24 not upgraded.


stderr:

start:
2015-03-27 17:12:22.132237

end:
2015-03-27 17:12:22.136859

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

(How) can I count the items in an enum?

Here is the best way to do it in compilation time. I have used the arg_var count answer from here.

#define PP_NARG(...) \
     PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
         PP_ARG_N(__VA_ARGS__)

#define PP_ARG_N( \
          _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
         _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
         _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
         _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
         _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
         _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
         _61,_62,_63,N,...) N
#define PP_RSEQ_N() \
         63,62,61,60,                   \
         59,58,57,56,55,54,53,52,51,50, \
         49,48,47,46,45,44,43,42,41,40, \
         39,38,37,36,35,34,33,32,31,30, \
         29,28,27,26,25,24,23,22,21,20, \
         19,18,17,16,15,14,13,12,11,10, \
         9,8,7,6,5,4,3,2,1,0

#define TypedEnum(Name, ...)                                      \
struct Name {                                                     \
    enum {                                                        \
        __VA_ARGS__                                               \
    };                                                            \
    static const uint32_t Name##_MAX = PP_NARG(__VA_ARGS__);      \
}

#define Enum(Name, ...) TypedEnum(Name, __VA_ARGS__)

To declare an enum:

Enum(TestEnum, 
Enum_1= 0,
Enum_2= 1,
Enum_3= 2,
Enum_4= 4,
Enum_5= 8,
Enum_6= 16,
Enum_7= 32);

the max will be available here:

int array [TestEnum::TestEnum_MAX];
for(uint32_t fIdx = 0; fIdx < TestEnum::TestEnum_MAX; fIdx++)
{
     array [fIdx] = 0;
}

Confused about __str__ on list in Python

The thing about classes, and setting unencumbered global variables equal to some value within the class, is that what your global variable stores is actually the reference to the memory location the value is actually stored.

What you're seeing in your output is indicative of this.

Where you might be able to see the value and use print without issue on the initial global variables you used because of the str method and how print works, you won't be able to do this with lists, because what is stored in the elements within that list is just a reference to the memory location of the value -- read up on aliases, if you'd like to know more.

Additionally, when using lists and losing track of what is an alias and what is not, you might find you're changing the value of the original list element, if you change it in an alias list -- because again, when you set a list element equal to a list or element within a list, the new list only stores the reference to the memory location (it doesn't actually create new memory space specific to that new variable). This is where deepcopy comes in handy!

Running an Excel macro via Python?

A variation on SMNALLY's code that doesn't quit Excel if you already have it open:

import os, os.path
import win32com.client
    
if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    wb.Close(False) #close the work sheet object rather than quitting excel
    del wb
    del xl

Show a number to two decimal places

For conditional rounding off ie. show decimal where it's really needed otherwise whole number

123.56 => 12.56

123.00 => 123

$somenumber = 123.56;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123.56


$somenumber = 123.00;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123    

How to put two divs side by side

This is just a simple(not-responsive) HTML/CSS translation of the wireframe you provided.

enter image description here

HTML

<div class="container">

  <header>
    <div class="logo">Logo</div>
    <div class="menu">Email/Password</div>
  </header>

  <div class="first-box">
    <p>Video Explaning Site</p>
  </div>

  <div class="second-box">
    <p>Sign up Info</p>
  </div>

  <footer>
    <div>Website Info</div>
  </footer>

</div>

CSS

.container {
  width:900px; 
  height: 150px;
}

header {
  width:900px; 
  float:left; 
  background: pink; 
  height: 50px;
}

.logo {
  float: left;
  padding: 15px
}

.menu {
  float: right;
  padding: 15px
}

.first-box {
  width:300px; 
  float:left; 
  background: green; 
  height: 150px;
  margin: 50px
}

.first-box p {
  color: #ffffff;
  padding-left: 80px;
  padding-top: 50px;
}

.second-box {
  width:300px; 
  height: 150px; 
  float:right; 
  background: blue;
  margin: 50px
}

.second-box p {
  color: #ffffff;
  padding-left: 110px;
  padding-top: 50px;
}

footer {
  width:900px; 
  float:left; 
  background: black; 
  height: 50px;
  color: #ffffff;
}

footer div {
  padding: 15px;
}

python pandas dataframe to dictionary

def get_dict_from_pd(df, key_col, row_col):
    result = dict()
    for i in set(df[key_col].values):
        is_i = df[key_col] == i
        result[i] = list(df[is_i][row_col].values)
    return result

this is my sloution, a basic loop

open a url on click of ok button in android

No need for any Java or Kotlin code to make it a clickable link, now you just need to follow given below code. And you can also link text color change by using textColorLink.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textColorLink="@color/white"/>

Fetch frame count with ffmpeg

Sorry for the necro answer, but maybe will need this (as I didn't found a solution for recent ffmpeg releases.

With ffmpeg 3.3.4 I found one can find with the following:

ffprobe -i video.mp4 -show_streams -hide_banner | grep "nb_frames"

At the end it will output frame count. It worked for me on videos with audio. It gives twice a "nb_frames" line, though, but the first line was the actual frame count on the videos I tested.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

What is the difference between #import and #include in Objective-C?

IF you #include a file two times in .h files than compiler will give error. But if you #import a file more than once compiler will ignore it.

Efficient SQL test query or validation query that will work across all (or most) databases

After a little bit of research along with help from some of the answers here:

SELECT 1

  • H2
  • MySQL
  • Microsoft SQL Server (according to NimChimpsky)
  • PostgreSQL
  • SQLite

SELECT 1 FROM DUAL

  • Oracle

SELECT 1 FROM any_existing_table WHERE 1=0

or

SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS

or

CALL NOW()

  • HSQLDB (tested with version 1.8.0.10)

    Note: I tried using a WHERE 1=0 clause on the second query, but it didn't work as a value for Apache Commons DBCP's validationQuery, since the query doesn't return any rows


VALUES 1 or SELECT 1 FROM SYSIBM.SYSDUMMY1

SELECT 1 FROM SYSIBM.SYSDUMMY1

  • DB2

select count(*) from systables

  • Informix

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

MySQL - ignore insert error: duplicate entry

$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
    while($value=mysql_fetch_array($duplicate_query)
    {
        if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
        {
            echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
            $res=mysql_query($query);
            if($query)
            {
                echo "Success";
            }
            else
            {
                echo "Error";
            }
            else
            {
                echo "Duplicate Entry";
            }
        }
    }
}
else
{
    echo "Records Already Exixts";
}

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

How to check if String value is Boolean type in Java?

The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.

You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.

Wrap that in a Method ContainsBoolString and you're go.

EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.

int i;
if (Int32.TryParse("Hello", out i))
  // Hello is an int and its value is in i
else
  // Hello is not an int

Benchmarks indicate they are way faster than the following:

int i;
try
{
   i = Int32.Parse("Hello");
   // Hello is an int and its value is in i
}
catch
{
   // Hello is not an int
}

Maybe there are similar methods in Java? It's been a while since I've used Java...

Switch case: can I use a range instead of a one number

You can use if-else statements with || operators (or-operator) like:

if(case1 == true || case2 == true || case3 == true)
   {
    Do this!... 
   }
else if(case4 == true || case5 == true || case6 == true)
   {
    Do this!... 
   }
else if(case7 == true || case8 == true || case9 == true)
   {
    Do this!... 
   }

SQL Query NOT Between Two Dates

Assuming that start_date is before end_date,

interval [start_date..end_date] NOT BETWEEN two dates simply means that either it starts before 2009-12-15 or it ends after 2010-01-02.

Then you can simply do

start_date<CAST('2009-12-15' AS DATE) or end_date>CAST('2010-01-02' AS DATE)

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

Press enter in textbox to and execute button command

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

Here's an example from the article linked:

<Button IsDefault = "true" 
        Click     = "SaveClicked"
        Content   = "Save"  ... />
'''

pod install -bash: pod: command not found

This Step Is Proper Working.

Pod Install

[ 1 ] Open terminal and type:

sudo gem install cocoapods

Gem will get installed in Ruby inside the System library. Or try on 10.11 Mac OSX El Capitan, type:

sudo gem install -n /usr/local/bin cocoapods

If there is an error "activesupport requires Ruby version >= 2.xx", then install the latest active support first by typing in the terminal.

sudo gem install activesupport -v 4.2.6

[ 2 ] After installation, there will be a lot of messages, read them and if no error found, it means cocoa pod installation is done. Next, you need to set up the cocoa pod master repo. Type in terminal:

pod setup

And wait it will download the master repo. The size is very big (370.0MB in Dec 2016). So it can be a while. You can track the download by opening Activity and go to the Network tab and search for git-remote-https. Alternatively, you can try adding verbose to the command like so:

pod setup --verbose

[ 3 ] Once done it will output "Setup Complete", and you can create your XCode project and save it.

[ 4 ] Then in a terminal cd to "your XCode project root directory" (where your .xcodeproj file resides) and type:

pod init

[ 5 ] Then open your project's podfile by typing in terminal:

open -a Xcode Podfile

[ 6 ] Your Podfile will get open in text mode. Initially, there will be some default commands in there. Here is where you add your project's dependencies. For example, in the podfile, type

/****** These are Third party pods names ******/
pod 'OpenSSL-Universal'
pod 'IQKeyboardManager'
pod 'FTPopOverMenu'
pod 'TYMActivityIndicatorView'
pod 'SCSkypeActivityIndicatorView'
pod 'Google/SignIn'
pod 'UPStackMenu'

(this is For example of adding library to your project).

When you are done editing the podfile, save it and close XCode.

[ 7 ] Then install pods into your project by typing in terminal:

pod install

Depending on how many libraries you added to your podfile for your project, the time to complete this varies. Once completed, there will be a message that says

"Pod installation complete! There are X dependencies from the Podfile and X total pods installed."

How can I exclude directories from grep -R?

SOLUTION 1 (combine find and grep)

The purpose of this solution is not to deal with grep performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.

Use find, for excluding directories foo and bar :

find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print

Then combine find and the non-recursive use of grep, as a portable solution :

find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;

SOLUTION 2 (using the --exclude-dir option of grep):

You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.

grep -R --exclude-dir=node_modules 'some pattern' /path/to/search

To exclude multiple directories, use --exclude-dir as:

--exclude-dir={node_modules,dir1,dir2,dir3}

SOLUTION 3 (Ag)

If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in .gitignore, so you don't have to keep passing the same cumbersome exclude options to grep or find.

BeanFactory not initialized or already closed - call 'refresh' before

This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound is just an unfortunate exception used to indicate that the web server returned a 404.

C# - Print dictionary

There are so many ways to do this, here is some more:

string.Join(Environment.NewLine, dictionary.Select(a => $"{a.Key}: {a.Value}"))
dictionary.Select(a => $"{a.Key}: {a.Value}{Environment.NewLine}")).Aggregate((a,b)=>a+b)
new String(dictionary.SelectMany(a => $"{a.Key}: {a.Value} {Environment.NewLine}").ToArray())

Additionally, you can then use one of these and encapsulate it in an extension method:

public static class DictionaryExtensions
{
    public static string ToReadable<T,V>(this Dictionary<T, V> d){
        return string.Join(Environment.NewLine, d.Select(a => $"{a.Key}: {a.Value}"));
    }   
}

And use it like this: yourDictionary.ToReadable().

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

unsigned int vs. size_t

The size_t type is the unsigned integer type that is the result of the sizeof operator (and the offsetof operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).

The size_t type may be bigger than, equal to, or smaller than an unsigned int, and your compiler might make assumptions about it for optimization.

You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft.

CSS: Force float to do a whole new line

You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.

How to kill a child process by the parent process?

Try something like this:

#include <signal.h>

pid_t child_pid = -1 ; //Global

void kill_child(int sig)
{
    kill(child_pid,SIGKILL);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM,(void (*)(int))kill_child);
    child_pid = fork();
    if (child_pid > 0) {
     /*PARENT*/
        alarm(30);
        /*
         * Do parent's tasks here.
         */
        wait(NULL);
    }
    else if (child_pid == 0){
     /*CHILD*/
        /*
         * Do child's tasks here.
         */
    }
}

MySQL select with CONCAT condition

Try:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

Your alias firstlast is not available in the where clause of the query unless you do the query as a sub-select.

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Vim for Windows - What do I type to save and exit from a file?

:q! will force an unconditional no-save exit

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

Maven error "Failure to transfer..."

just delete the archetype in maven local repository. As said above, it happens in case of failed archetype downloads.

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

Auto increment in phpmyadmin

This is due to the wp_terms, wp_termmeta and wp_term_taxonomy tables, which had all their ID's not set to AUTO_INCREMENT

To do this go to phpmyadmin, click on the concern database, wp_terms table, click on structure Tab, at right side you will see a tab named A_I(AUTO_INCREMENT), check it and save (You are only doing this for the first option, in the case wp_term you are only doing it for term_id).

Do the same for wp_termmeta and wp_term_taxonomy that will fix the issue.

Should I test private methods or only public ones?

Absolutely YES. That is the point of Unit testing, you test Units. Private method is a Unit. Without testing private methods TDD (Test Driven Development) would be impossible,

What is the most efficient way to store a list in the Django models?

You can store virtually any object using a Django Pickle Field, ala this snippet:

http://www.djangosnippets.org/snippets/513/

ValueError: not enough values to unpack (expected 11, got 1)

The error message is fairly self-explanatory

(a,b,c,d,e) = line.split()

expects line.split() to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.

To see what line is causing the issue, you could add some debug statements like this:

if len(line.split()) != 11:
    print line

As Martin suggests, you might also be splitting on the wrong delimiter.

How to use a findBy method with comparative criteria

I like to use such static methods:

$result = $purchases_repository->matching(
    Criteria::create()->where(
        Criteria::expr()->gt('prize', 200)
    )
);

Of course, you can push logic when it is 1 condition, but when you have more conditions it is better to divide it into fragments, configure and pass it to the method:

$expr = Criteria::expr();

$criteria = Criteria::create();
$criteria->where($expr->gt('prize', 200));
$criteria->orderBy(['prize' => Criteria::DESC]);

$result = $purchases_repository->matching($criteria);

PostgreSQL Crosstab Query

Crosstab function is available under the tablefunc extension. You'll have to create this extension one time for the database.

CREATE EXTENSION tablefunc;

You can use the below code to create pivot table using cross tab:

create table test_Crosstab( section text,
<br/>status text,
<br/>count numeric)

<br/>insert into test_Crosstab values ( 'A','Active',1)
                <br/>,( 'A','Inactive',2)
                <br/>,( 'B','Active',4)
                <br/>,( 'B','Inactive',5)

select * from crosstab(
<br/>'select section
    <br/>,status
    <br/>,count
    <br/>from test_crosstab'
    <br/>)as ctab ("Section" text,"Active" numeric,"Inactive" numeric)

Placing border inside of div and not on its edge

You can also use box-shadow like this:

div{
    -webkit-box-shadow:inset 0px 0px 0px 10px #f00;
    -moz-box-shadow:inset 0px 0px 0px 10px #f00;
    box-shadow:inset 0px 0px 0px 10px #f00;
}

Example here: http://jsfiddle.net/nVyXS/ (hover to view border)

This works in modern browsers only. For example: No IE 8 support. See caniuse.com (box-shadow feature) for more info.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How to use jQuery to show/hide divs based on radio button selection?

I wrote a simple code to unterstand you to how to make a show and hide radio buttons in jquery its very simple

<div id="myRadioGroup">

    Value Based<input type="radio" name="cars" checked="checked" value="2"  />

    Percent Based<input type="radio" name="cars" value="3" />
    <br>
    <div id="Cars2" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Value</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Percent</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
</div>
</div>

Jquery code

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

give me comments

The preferred way of creating a new element with jQuery

According to the jQuery official documentation

To create a HTML element, $("<div/>") or $("<div></div>") is preferred.

Then you can use either appendTo, append, before, after and etc,. to insert the new element to the DOM.

PS: jQuery Version 1.11.x

How to open a web page from my application?

I have the solution for this due to I have a similar problem today.

Supposed you want to open http://google.com from an app running with admin priviliges:

ProcessStartInfo startInfo = new ProcessStartInfo("iexplore.exe", "http://www.google.com/");
Process.Start(startInfo); 

Receiving login prompt using integrated windows authentication

I got the same issue and it was resolved by changing the Application pool identity of the application pool under which the web application is running to NetworkService enter image description here

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

To amend SDP's answer above, you do NOT need to declarecol-xs-12 in <div class="col-xs-12 col-sm-6">. Bootstrap 3 is mobile-first, so every div column is assumed to be a 100% width div by default - which means at the "xs" size it is 100% width, it will always default to that behavior regardless of what you set at sm, md, lg. If you want your xs columns to be not 100%, then you normally do a col-xs-(1-11).

How to get 'System.Web.Http, Version=5.2.3.0?

One way to fix it is by modifying the assembly redirect in the web.config file.

Modify the following:

<dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>

to

<dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>

So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".

How to prevent Google Colab from disconnecting?

I was looking for a solution until I found a Python3 that randomly moves the mouse back and forth and clicks, always on the same place, but that's enough to fool Colab into thinking I'm active on the notebook and not disconnect.

import numpy as np
import time
import mouse
import threading

def move_mouse():
    while True:
        random_row = np.random.random_sample()*100
        random_col = np.random.random_sample()*10
        random_time = np.random.random_sample()*np.random.random_sample() * 100
        mouse.wheel(1000)
        mouse.wheel(-1000)
        mouse.move(random_row, random_col, absolute=False, duration=0.2)
        mouse.move(-random_row, -random_col, absolute=False, duration = 0.2)
        mouse.LEFT
        time.sleep(random_time)


x = threading.Thread(target=move_mouse)
x.start()

You need to install the needed packages: sudo -H pip3 install <package_name> You just need to run it (in your local machine) with sudo (as it takes control of the mouse) and it should work, allowing you to take full advantage of Colab's 12h sessions.

Credits: For those using Colab (Pro): Preventing Session from disconnecting due to inactivity

Create own colormap using matplotlib and plot color scale

This seems to work for me.

def make_Ramp( ramp_colors ): 
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] ) 

custom color ramp

Xcode 10 Error: Multiple commands produce

OK so for anyone who hadn't found correct answer here because it has nothing to do with info.plist...

I ran into this problem while I was developing a macOS app without CocoaPods or Carthage, just with SPM packages, manually dragging xcodeprojs into workplace.

When I was using only one dependency (it was using Swift-NIO from within), everything was OK, but when I added one more one more dependency with overlapping subdeps, I got this nasty problem.

The solution is to try to compile all major dependencies separately (it would fail due to unexisting checkout folders within respective .build folders, and this is most probably happened because you put your pkgs in edit mode (swift package edit YourPkg ...).

You just unedit your pkgs, and force all dependencies to compile successfully. After that you must make sure that your linked binaries within main target aren't overlapped (I'm not sure it's really necessary, but just in case).

After that everything should be working just great :)

How to iterate through a list of dictionaries in Jinja template?

As a sidenote to @Navaneethan 's answer, Jinja2 is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.

Data:

parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]

in Jinja2 iteration:

{% for dict_item in parent_dict %}
   This example has {{dict_item['A']}} and {{dict_item['B']}}:
       with the content --
       {% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}

The rendered output:

This example has val1 and val2:
    with the content --
    1.1 and 2.2.

This example has val3 and val4:
   with the content --
   3.3 and 4.4.

PHP how to get the base domain/url?

Use SERVER_NAME.

echo $_SERVER['SERVER_NAME']; //Outputs www.example.com

Asynchronous Process inside a javascript for loop

JavaScript code runs on a single thread, so you cannot principally block to wait for the first loop iteration to complete before beginning the next without seriously impacting page usability.

The solution depends on what you really need. If the example is close to exactly what you need, @Simon's suggestion to pass i to your async process is a good one.

Checking if a variable is defined?

Please note the distinction between "defined" and "assigned".

$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"

x is defined even though it is never assigned!

How to add an image to the "drawable" folder in Android Studio?

Just copy your images and select drawable then on the option of Paste or press shortcut ctrl v. images are added

Sum a list of numbers in Python

Try the following -

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)

Enter key in textarea

You could do something like this:

_x000D_
_x000D_
$("#txtArea").on("keypress",function(e) {_x000D_
    var key = e.keyCode;_x000D_
_x000D_
    // If the user has pressed enter_x000D_
    if (key == 13) {_x000D_
        document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
        return false;_x000D_
    }_x000D_
    else {_x000D_
        return true;_x000D_
    }_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
_x000D_
_x000D_

How to check whether a int is not null or empty?

if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..

Check if a value is in an array (C#)

Not very clear what your issue is, but it sounds like you want something like this:

    List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );

    if( printer.Exists( p => p.Equals( "jupiter" ) ) )
    {
        ...
    }

How to roundup a number to the closest ten?

Use ROUND but with num_digits = -1

=ROUND(A1,-1)

Also applies to ROUNDUP and ROUNDDOWN

From Excel help:

  • If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places.
  • If num_digits is 0, then number is rounded to the nearest integer.
  • If num_digits is less than 0, then number is rounded to the left of the decimal point.

EDIT: To get the numbers to always round up use =ROUNDUP(A1,-1)

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

How does one represent the empty char?

There is no such thing as the "empty character" ''.

If you need a space character, that can be represented as a space: c[i] = ' ' or as its ASCII octal equivalent: c[i] = '\040'. If you need a NUL character that's c[i] = '\0'.

Loading cross-domain endpoint with AJAX

Figured it out. Used this instead.

$('.div_class').load('http://en.wikipedia.org/wiki/Cross-origin_resource_sharing #toctitle');

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

Split a large pandas dataframe

I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks