Programs & Examples On #Hd44780

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

SELECT query with CASE condition and SUM()

select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType

Cheers -

Determine the path of the executing BASH script

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"

Using OR & AND in COUNTIFS

In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

Access mysql remote database from command line

If you are on windows, try Visual Studio Code with MySQL plugins, an easy and integrated way to access MySQL data on a windows machine. And the database tables listed and can execute any custom queries.

Add Variables to Tuple

It's as easy as the following:

info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")

However, tuples in Python are immutable, so you cannot append variables to a tuple once it is created.

https connection using CURL from command line

use --cacert to specify a .crt file. ca-root-nss.crt for example.

How to use npm with node.exe?

I am running node.js on Windows with npm. The trick is simply use cygwin. I followed the howto under https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) . But make sure that you use version 0.4.11 of nodejs or npm will fail!

Test for multiple cases in a switch, like an OR (||)

You need to make two case labels.

Control will fall through from the first label to the second, so they'll both execute the same code.

How can I determine the direction of a jQuery scroll event?

Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.

    var scrollableElement = document.getElementById('scrollableElement');

    scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);

    function findScrollDirectionOtherBrowsers(event){
        var delta;

        if (event.wheelDelta){
            delta = event.wheelDelta;
        }else{
            delta = -1 * event.deltaY;
        }

        if (delta < 0){
            console.log("DOWN");
        }else if (delta > 0){
            console.log("UP");
        }

    }

Example

Convert String to Type in C#

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

Git - Ignore node_modules folder everywhere

First and foremost thing is to add .gitignore file in my-app. Like so in image below.

Put .gitignore in the parent folder/directory of node_modules.

and next add this in your .gitignore file

/node_modules

Note

You can also add others files too to ignore them to be pushed on github. Here are some more files kept in .gitignore. You can add them according to your requirement. # is just a way to comment in .gitignore file.

# See https://help.github.com/ignore-files/ for more about ignoring files.

# dependencies
/node_modules

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

What is javax.inject.Named annotation supposed to be used for?

Regarding #2, according to the JSR-330 spec:

This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.

So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.

How to get list of all installed packages along with version in composer?

The behaviour of this command as been modified so you don't have to pass the -i option:

[10:19:05] coil@coil:~/workspace/api$ composer show -i
You are using the deprecated option "installed". 
Only installed packages are shown by default now. 
The --all option can be used to show all packages.

How best to read a File into List<string>

//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();

//manipulate data here
foreach(string line in ReadFile)
{
    //do something here
}

//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);

Changing iframe src with Javascript

This should also work, although the src will remain intact:

document.getElementById("myIFrame").contentWindow.document.location.href="http://myLink.com";

Gradle: Execution failed for task ':processDebugManifest'

This appears to occur because Google Play Services require Android 2.2, which is SDK version 8.

In build.gradle, make sure your minSdkVersion is at least 8. The default appears to be 7. So you have something like this:

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
    compile 'com.google.android.gms:play-services:3.1.36'
}

How to Select Every Row Where Column Value is NOT Distinct

Rather than using sub queries in where condition which will increase the query time where records are huge.

I would suggest to use Inner Join as a better option to this problem.

Considering the same table this could give the result

SELECT EmailAddress, CustomerName FROM Customers as a 
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress

For still better results I would suggest you to use CustomerID or any unique field of your table. Duplication of CustomerName is possible.

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

Select last row in MySQL

You can combine two queries suggested by @spacepille into single query that looks like this:

SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);

It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.

Get TimeZone offset value from TimeZone without TimeZone name

ZoneId here = ZoneId.of("Europe/Kiev");
ZonedDateTime hereAndNow = Instant.now().atZone(here);
String.format("%tz", hereAndNow);

will give you a standardized string representation like "+0300"

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

Reading/writing an INI file

Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.

/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
    Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();

    String ini = File.ReadAllText(file);

    // Remove comments, preserve linefeeds, if end-user needs to count line number.
    ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);

    // Pick up all lines from first section to another section
    foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
    {
        String sectionName = m.Groups[2].Value;
        Dictionary<String, String> lines = new Dictionary<String, String>();

        // Pick up "key = value" kind of syntax.
        foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
        {
            String key = l.Groups[1].Value;
            String value = l.Groups[2].Value;

            // Open up quotation if any.
            value = Regex.Replace(value, "^\"(.*)\"$", "$1");

            if (!lines.ContainsKey(key))
                lines[key] = value;
        }

        if (!d.ContainsKey(sectionName))
            d[sectionName] = lines;
    }

    return d;
}

Regular expression to match balanced parentheses

[^\(]*(\(.*\))[^\)]*

[^\(]* matches everything that isn't an opening bracket at the beginning of the string, (\(.*\)) captures the required substring enclosed in brackets, and [^\)]* matches everything that isn't a closing bracket at the end of the string. Note that this expression does not attempt to match brackets; a simple parser (see dehmann's answer) would be more suitable for that.

You have not concluded your merge (MERGE_HEAD exists)

I resolved conflicts and also committed but still getting this error message on git push

All conflicts fixed but you are still merging.
(use "git commit" to conclude merge)

I did these steps to resolve error:

rm -rf .git/MERGE*
git pull origin branch_name 
git push origin branch_name

Entity Framework. Delete all rows in table

I came across this question when I had to deal with a particular case: fully updating of content in a "leaf" table (no FKs pointing to it). This involved removing all rows and putting new rows information and it should be done transactionally (I do not want to end up with an empty table, if inserts fails for whatever reason).

I have tried the public static void Clear<T>(this DbSet<T> dbSet) approach, but new rows are not inserted. Another disadvante is that the whole process is slow, as rows are deleted one by one.

So, I have switched to TRUNCATE approach, since it is much faster and it is also ROLLBACKable. It also resets the identity.

Example using repository pattern:

public class Repository<T> : IRepository<T> where T : class, new()
{
    private readonly IEfDbContext _context;

    public void BulkInsert(IEnumerable<T> entities)
    {
        _context.BulkInsert(entities);
    }

    public void Truncate()
    {
        _context.Database.ExecuteSqlCommand($"TRUNCATE TABLE {typeof(T).Name}");
    }
 }

 // usage 
 DataAccess.TheRepository.Truncate();
 var toAddBulk = new List<EnvironmentXImportingSystem>();

 // fill toAddBulk from source system
 // ...

 DataAccess.TheRepository.BulkInsert(toAddBulk);
 DataAccess.SaveChanges();

Of course, as already mentioned, this solution cannot be used by tables referenced by foreign keys (TRUNCATE fails).

When should I use mmap for file access?

Memory mapping has a potential for a huge speed advantage compared to traditional IO. It lets the operating system read the data from the source file as the pages in the memory mapped file are touched. This works by creating faulting pages, which the OS detects and then the OS loads the corresponding data from the file automatically.

This works the same way as the paging mechanism and is usually optimized for high speed I/O by reading data on system page boundaries and sizes (usually 4K) - a size for which most file system caches are optimized to.

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

How to add/subtract dates with JavaScript?

May be this could help

    <script type="text/javascript" language="javascript">
        function AddDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() + parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }

function SubtractDays(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));

            document.getElementById("result").innerHTML = d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear();
        }
    </script>
    ---------------------- UI ---------------
        <div id="result">
        </div>
        <input type="text" value="0" onkeyup="AddDays(this.value);" />
        <input type="text" value="0" onkeyup="SubtractDays(this.value);" />

Checking if a number is a prime number in Python

a = input('inter a number: ')
s = 0
if a == 1:  
    print a, 'is a prime'

else : 

    for i in range (2, a ):

        if a%i == 0:
            print a,' is not a prime number'
            s = 'true'
            break

    if s == 0 : print a,' is a prime number'

it worked with me just fine :D

Reordering Chart Data Series

To change the sequence of a series in Excel 2010:

  • Select (click on) any data series and click the "Design" tab in the "Chart Tools" group.
  • Click "Select Data" in the "Data" group and in the pop-up window, highlight the series to be moved.
  • Click the up or down triangle at the top of the left hand box labeled "Legend Entries" (Series).

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Swift 3 & Xcode 8.3.2

This code will help you, i add an explanation too

// Create custom class, this will make your life easier
class CustomDelay {

    static let cd = CustomDelay()

    // This is your custom delay function
    func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}


// here how to use it (Example 1)
class YourViewController: UIViewController {

    // example delay time 2 second
    let delayTime = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        CustomDelay.cd.runAfterDelay(delayTime) {
            // This func will run after 2 second
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
            self.runFunc()
        }
    }

    // example function 1
    func runFunc() {
        // do your method 1 here
    }
}

// here how to use it (Example 2)
class YourSecondViewController: UIViewController {

    // let say you want to user run function shoot after 3 second they tap a button

    // Create a button (This is programatically, you can create with storyboard too)
    let shootButton: UIButton = {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
        button.setTitle("Shoot", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create an action selector when user tap shoot button
        shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)   
    }

    // example shoot function
    func shoot() {
        // example delay time 3 second then shoot
        let delayTime = 3.0

        // delay a shoot after 3 second
        CustomDelay.cd.runAfterDelay(delayTime) {
            // your shoot method here
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
        }
    }   
}

How to calculate UILabel height dynamically?

Calling -sizeToFit on UILabel instance will automatically resize it to fit text it displays, no calculating required. If you need the size, you can get it from label's frame property after that.

label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = @"some long text";
[label sizeToFit];
NSLog(@"Label's frame is: %@", NSStringFromCGRect(label.frame));

extract month from date in python

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31

How should I make my VBA code compatible with 64-bit Windows?

i found this code (note that some Long are changed to LongPtr):

Declare PtrSafe Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hwnd As LongPtr, ByVal lpOperation As String, _
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As _
String, ByVal nShowCmd As Long) As LongPtr

source: http://www.cadsharp.com/docs/Win32API_PtrSafe.txt

Why does z-index not work?

If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

So with following html

_x000D_
_x000D_
div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }_x000D_
#el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }
_x000D_
<div id="el1" style="z-index: 5"></div>_x000D_
<div id="el2" style="z-index: 3">_x000D_
  <div id="el3" style="z-index: 8"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

If you want to check stacking contexts of parent elements, you can use this:

var el = document.getElementById("#yourElement"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex, el);
} while(el.parentElement && (el = el.parentElement));

There is a great article about stacking contexts on MDN

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

IE8 issue with Twitter Bootstrap 3

Just in case. Make sure you load the IE specific js files after you load your css files.

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

I solved this issue by doing this:

instead of

<Route path="/" component={HomePage} />

do this

<Route
 path="/" component={props => <HomePage {...props} />} />

Cannot ping AWS EC2 instance

might be your internal network is blocking that IP to ping or blocked ping packet in your firewall if you have opened in security group and VPC is correct.

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How to ignore the first line of data when processing CSV data?

You could use an instance of the csv module's Sniffer class to deduce the format of a CSV file and detect whether a header row is present along with the built-in next() function to skip over the first row only when necessary:

import csv

with open('all16.csv', 'r', newline='') as file:
    has_header = csv.Sniffer().has_header(file.read(1024))
    file.seek(0)  # Rewind.
    reader = csv.reader(file)
    if has_header:
        next(reader)  # Skip header row.
    column = 1
    datatype = float
    data = (datatype(row[column]) for row in reader)
    least_value = min(data)

print(least_value)

Since datatype and column are hardcoded in your example, it would be slightly faster to process the row like this:

    data = (float(row[1]) for row in reader)

Note: the code above is for Python 3.x. For Python 2.x use the following line to open the file instead of what is shown:

with open('all16.csv', 'rb') as file:

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

Count a list of cells with the same background color

Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:

http://www.cpearson.com/excel/colors.aspx

Example form the site:

The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)

R adding days to a date

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

in solution explorer just right click and select convert to web application. It will generate all the designer files again.

How to open spss data files in excel?

I tried the below and it worked well,

Install Dimensions Data Model and OLE DB Access

and follow the below steps in excel

Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish

UIView Infinite 360 degree rotation animation?

Swift 3 :

 var rotationAnimation = CABasicAnimation()
     rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
     rotationAnimation.toValue = NSNumber(value: (M_PI * 2.0))
     rotationAnimation.duration = 2.0
     rotationAnimation.isCumulative = true
     rotationAnimation.repeatCount = 10.0
     view.layer.add(rotationAnimation, forKey: "rotationAnimation")

Where is the user's Subversion config file stored on the major operating systems?

~/.subversion/config or /etc/subversion/config

for Mac/Linux

and

%appdata%\subversion\config

for Windows

How to get the current working directory in Java?

this.getClass().getClassLoader().getResource("").getPath()

How to convert a python numpy array to an RGB image with Opencv 2.4?

You are looking for scipy.misc.toimage:

import scipy.misc
rgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray

Seedable JavaScript random number generator

If you want to be able to specify the seed, you just need to replace the calls to getSeconds() and getMinutes(). You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.

That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.

If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.

EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.

"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
                                                                                                                                                          --- John von Neumann

How can I exclude multiple folders using Get-ChildItem -exclude?

VertigoRay, in his answer, explained that -Exclude works only at the leaf level of a path (for a file the filename with path stripped out; for a sub-directory the directory name with path stripped out). So it looks like -Exclude cannot be used to specify a directory (eg "bin") and exclude all the files and sub-directories within that directory.

Here's a function to exclude files and sub-directories of one or more directories (I know this is not directly answering the question but I thought it might be useful in getting around the limitations of -Exclude):

$rootFolderPath = 'C:\Temp\Test'
$excludeDirectories = ("bin", "obj");

function Exclude-Directories
{
    process
    {
        $allowThrough = $true
        foreach ($directoryToExclude in $excludeDirectories)
        {
            $directoryText = "*\" + $directoryToExclude
            $childText = "*\" + $directoryToExclude + "\*"
            if (($_.FullName -Like $directoryText -And $_.PsIsContainer) `
                -Or $_.FullName -Like $childText)
            {
                $allowThrough = $false
                break
            }
        }
        if ($allowThrough)
        {
            return $_
        }
    }
}

Clear-Host

Get-ChildItem $rootFolderPath -Recurse `
    | Exclude-Directories

For a directory tree:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt
  |
  +?bin\
    |
    +?Debug\
      |
      +?SomeFile.txt

The result is:

C:\Temp\Test\
|
+?SomeFolder\
|  |
|  +?bin (file without extension)
|
+?MyApplication\
  |
  +?BinFile.txt
  +?FileA.txt
  +?FileB.txt

It excludes the bin\ sub-folder and all its contents but does not exclude files Bin.txt or bin (file named "bin" without an extension).

Get number of digits with JavaScript

Two digits: simple function in case you need two or more digits of a number with ECMAScript 6 (ES6):

const zeroDigit = num => num.toString().length === 1 ? `0${num}` : num;

Remove Primary Key in MySQL

First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

make sure the bind address configuration option in the my.cnf file in /etc/ is the same with localhost or virtual serve ip address. plus check to make sure that the directory for creating the socket file is well specified.

Anaconda / Python: Change Anaconda Prompt User Path

Go to Start and search for "Anaconda Prompt" - right click this and choose "Open File Location", which will open a folder of shortcuts. Right click the "Anaconda Prompt" shortcut, choose "Properties" and you can adjust the starting dir in the "Start in" box.

Process escape sequences in a string in Python

This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.

input_string = eval('b"' + sys.argv[1] + '"')

It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?

'git status' shows changed files, but 'git diff' doesn't

As already noted in a previous answer, this situation may arise due to line-ending problems (CR/LF vs. LF). I solved this problem (under Git version 2.22.0) with this command:

git add --renormalize .

According to the manual:

       --renormalize
           Apply the "clean" process freshly to all tracked files to
           forcibly add them again to the index. This is useful after
           changing core.autocrlf configuration or the text attribute in
           order to correct files added with wrong CRLF/LF line endings.
           This option implies -u.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

You may use Oracle pipelined functions

Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.

Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?

create type array
as table of number;


create function  gen_numbers(n in number default null)
return array
PIPELINED
as
begin
  for i in 1 .. nvl(n,999999999)
  loop
     pipe row(i);
 end loop;
 return;
end;

Suppose we needed three rows for something. We can now do that in one of two ways:

select * from TABLE(gen_numbers(3));

COLUMN_VALUE


       1
       2
       3

or

select * from TABLE(gen_numbers)
 where rownum <= 3;

COLUMN_VALUE


       1
       2
       3

pipelied Functions1 pipelied Functions2

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}

android: how to change layout on button click?

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.

Unzip All Files In A Directory

for i in *.zip; do
  newdir="${i:0:-4}" && mkdir "$newdir"
  unzip "$i" -d  "$newdir"
done

This will unzip all the zip archives into new folders named with the filenames of the zip archives.

a.zip b.zip c.zip will be unzipped into a b c folders respectively.

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

You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."

How to uninstall Eclipse?

Look for an installation subdirectory, likely named eclipse. Under that subdirectory, if you see files like eclipse.ini, icon.xpm and subdirectories like plugins and dropins, remove the subdirectory parent (the one named eclipse).

That will remove your installation except for anything you've set up yourself (like workspaces, projects, etc.).

Hope this helps.

How can I apply a function to every row/column of a matrix in MATLAB?

For completeness/interest I'd like to add that matlab does have a function that allows you to operate on data per-row rather than per-element. It is called rowfun (http://www.mathworks.se/help/matlab/ref/rowfun.html), but the only "problem" is that it operates on tables (http://www.mathworks.se/help/matlab/ref/table.html) rather than matrices.

Merging dictionaries in C#

Merging using an extension method. It does not throw exception when there are duplicate keys, but replaces those keys with keys from the second dictionary.

internal static class DictionaryExtensions
{
    public static Dictionary<T1, T2> Merge<T1, T2>(this Dictionary<T1, T2> first, Dictionary<T1, T2> second)
    {
        if (first == null) throw new ArgumentNullException("first");
        if (second == null) throw new ArgumentNullException("second");

        var merged = new Dictionary<T1, T2>();
        first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
        second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);

        return merged;
    }
}

Usage:

Dictionary<string, string> merged = first.Merge(second);

How to refresh Android listview?

If you are going by android guide lines and you are using the ContentProviders to get data from Database and you are displaying it in the ListView using the CursorLoader and CursorAdapters ,then you all changes to the related data will automatically be reflected in the ListView.

Your getContext().getContentResolver().notifyChange(uri, null); on the cursor in the ContentProvider will be enough to reflect the changes .No need for the extra work around.

But when you are not using these all then you need to tell the adapter when the dataset is changing. Also you need to re-populate / reload your dataset (say list) and then you need to call notifyDataSetChanged() on the adapter.

notifyDataSetChanged()wont work if there is no the changes in the datset. Here is the comment above the method in docs-

/**
 * Notifies the attached observers that the underlying data has been changed
 * and any View reflecting the data set should refresh itself.
 */

.includes() not working in Internet Explorer

Or just put this in a Javascript file and have a good day :)

String.prototype.includes = function (str) {
  var returnValue = false;

  if (this.indexOf(str) !== -1) {
    returnValue = true;
  }

  return returnValue;
}

How can I select the row with the highest ID in MySQL?

For MySQL:

SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1

You want to sort the rows from highest to lowest id, hence the ORDER BY id DESC. Then you just want the first one so LIMIT 1:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set

How do I extract text that lies between parentheses (round brackets)?

string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);

Python script header

The Python executable might be installed at a location other than /usr/bin, but env is nearly always present in that location so using /usr/bin/envis more portable.

What's the difference between "Layers" and "Tiers"?

Technically a Tier can be a kind of minimum environment required for the code to run.

E.g. hypothetically a 3-tier app can be running on

  1. 3 physical machines with no OS .
  2. 1 physical machine with 3 virtual machines with no OS.

    (That was a 3-(hardware)tier app)

  3. 1 physical machine with 3 virtual machines with 3 different/same OSes

    (That was a 3-(OS)tier app)

  4. 1 physical machine with 1 virtual machine with 1 OS but 3 AppServers

    (That was a 3-(AppServer)tier app)

  5. 1 physical machine with 1 virtual machine with 1 OS with 1 AppServer but 3 DBMS

    (That was a 3-(DBMS)tier app)

  6. 1 physical machine with 1 virtual machine with 1 OS with 1 AppServers and 1 DBMS but 3 Excel workbooks.

    (That was a 3-(AppServer)tier app)

Excel workbook is the minimum required environment for VBA code to run.

Those 3 workbooks can sit on a single physical computer or multiple.

I have noticed that in practice people mean "OS Tier" when they say "Tier" in the app description context.

That is if an app runs on 3 separate OS then its a 3-Tier app.

So a pedantically correct way describing an app would be

"1-to-3-Tier capable, running on 2 Tiers" app.

:)


Layers are just types of code in respect to the functional separation of duties withing the app (e.g. Presentation, Data , Security etc.)

Convert a byte array to integer in Java and vice versa

A basic implementation would be something like this:

public class Test {
    public static void main(String[] args) {
        int[] input = new int[] { 0x1234, 0x5678, 0x9abc };
        byte[] output = new byte[input.length * 2];

        for (int i = 0, j = 0; i < input.length; i++, j+=2) {
            output[j] = (byte)(input[i] & 0xff);
            output[j+1] = (byte)((input[i] >> 8) & 0xff);
        }

        for (int i = 0; i < output.length; i++)
            System.out.format("%02x\n",output[i]);
    }
}

In order to understand things you can read this WP article: http://en.wikipedia.org/wiki/Endianness

The above source code will output 34 12 78 56 bc 9a. The first 2 bytes (34 12) represent the first integer, etc. The above source code encodes integers in little endian format.

Proper way to set response status and JSON content in a REST API made with nodejs and express

try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Shrinking navigation bar when scrolling down (bootstrap3)

Sticky navbar:

To make a sticky nav you need to add the class navbar-fixed-top to your nav

Official documentation:
http://getbootstrap.com/components/#navbar-fixed-top

Official example:
http://getbootstrap.com/examples/navbar-fixed-top/

A simple example code:

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container">
    ...
  </div>
</nav>

with related jsfiddle: http://jsfiddle.net/ur7t8/

Resize the navbar:

If you want the nav bar to resize while you scroll the page you can give a look to this example: http://www.bootply.com/109943

JS

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

CSS

nav.navbar.shrink {
  min-height: 35px;
}

Animation:

To add an animation while you scroll, all you need to do is set a transition on the nav

CSS

nav.navbar{
  background-color:#ccc;
   // Animation
   -webkit-transition: all 0.4s ease;
   transition: all 0.4s ease;
}

I made a jsfiddle with the full example code: http://jsfiddle.net/Filo/m7yww8oa/

Standard Android Button with a different color

values\styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="RedAccentButton" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">#ff0000</item>
</style>

then:

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text"
    android:theme="@style/RedAccentButton" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text"
    android:theme="@style/RedAccentButton" />

result

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

Create or write/append in text file

Although there are many ways to do this. But if you want to do it in an easy way and want to format text before writing it to log file. You can create a helper function for this.

if (!function_exists('logIt')) {
    function logIt($logMe)
    {
        $logFilePath = storage_path('logs/cron.log.'.date('Y-m-d').'.log');
        $cronLogFile = fopen($logFilePath, "a");
        fwrite($cronLogFile, date('Y-m-d H:i:s'). ' : ' .$logMe. PHP_EOL);
        fclose($cronLogFile);
    }
}

How to insert blank lines in PDF?

You can use "\n" in Paragraph

document.add(new Paragraph("\n\n"));

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).

Mysql - How to quit/exit from stored procedure

To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
         CALL SP_Reporting_2(tablename);
     END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
     #proceed with code
END;

How can I change the date format in Java?

SimpleDateFormat newDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = newDateFormat.parse("28/12/2013");
newDateFormat.applyPattern("yyyy/MM/dd")
String myDateString = newDateFormat.format(myDate);

Now MyDate = 2013/12/28

Import Certificate to Trusted Root but not to Personal [Command Line]

There is a fairly simple answer with powershell.

Import-PfxCertificate -Password $secure_pw  -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx

The trick is making a "secure" password...

$plaintext_pw = 'PASSWORD';
$secure_pw = ConvertTo-SecureString $plaintext_pw -AsPlainText -Force; 
Import-PfxCertificate -Password $secure_pw  -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx;

Convert date from String to Date format in Dataframes

I solved the same problem without the temp table/view and with dataframe functions.

Of course I found that only one format works with this solution and that's yyyy-MM-DD.

For example:

val df = sc.parallelize(Seq("2016-08-26")).toDF("Id")
val df2 = df.withColumn("Timestamp", (col("Id").cast("timestamp")))
val df3 = df2.withColumn("Date", (col("Id").cast("date")))

df3.printSchema

root
 |-- Id: string (nullable = true)
 |-- Timestamp: timestamp (nullable = true)
 |-- Date: date (nullable = true)

df3.show

+----------+--------------------+----------+
|        Id|           Timestamp|      Date|
+----------+--------------------+----------+
|2016-08-26|2016-08-26 00:00:...|2016-08-26|
+----------+--------------------+----------+

The timestamp of course has 00:00:00.0 as a time value.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

In many linux release, you can find complier.h in /usr/linux/ , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because

if ( likely( ... ) ) {
     doSomething();
}

it can be optimized as well in many compiler.

And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:

gcc -c test.c objdump -d test.o > obj.s

Then, open obj.s, you can find the answer.

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

What does set -e mean in a bash script?

Script 1: without setting -e
#!/bin/bash
decho "hi"
echo "hello"
This will throw error in decho and program continuous to next line

Script 2: With setting -e
#!/bin/bash
set -e
decho "hi" 
echo "hello"
# Up to decho "hi" shell will process and program exit, it will not proceed further

How to prevent colliders from passing through each other?

So I haven't been able to get the Mesh Colliders to work. I created a composite collider using simple box colliders and it worked exactly as expected.

Other tests with simple Mesh Colliders have come out the same.

It looks like the best answer is to build a composite collider out of simple box/sphere colliders.

For my specific case I wrote a Wizard that creates a Pipe shaped compound collider.

@script AddComponentMenu("Colliders/Pipe Collider");
class WizardCreatePipeCollider extends ScriptableWizard
{
    public var outterRadius : float = 200;
    public var innerRadius : float = 190;
    public var sections : int = 12;
    public var height : float = 20;

    @MenuItem("GameObject/Colliders/Create Pipe Collider")
    static function CreateWizard()
    {
        ScriptableWizard.DisplayWizard.<WizardCreatePipeCollider>("Create Pipe Collider");
    }

    public function OnWizardUpdate() {
        helpString = "Creates a Pipe Collider";
    }

    public function OnWizardCreate() {
        var theta : float = 360f / sections;
        var width : float = outterRadius - innerRadius;

        var sectionLength : float = 2 * outterRadius * Mathf.Sin((theta / 2) * Mathf.Deg2Rad);

        var container : GameObject = new GameObject("Pipe Collider");
        var section : GameObject;
        var sectionCollider : GameObject;
        var boxCollider : BoxCollider;

        for(var i = 0; i < sections; i++)
        {
            section = new GameObject("Section " + (i + 1));

            sectionCollider = new GameObject("SectionCollider " + (i + 1));
            section.transform.parent = container.transform;
            sectionCollider.transform.parent = section.transform;

            section.transform.localPosition = Vector3.zero;
            section.transform.localRotation.eulerAngles.y = i * theta;

            boxCollider = sectionCollider.AddComponent.<BoxCollider>();
            boxCollider.center = Vector3.zero;
            boxCollider.size = new Vector3(width, height, sectionLength);

            sectionCollider.transform.localPosition = new Vector3(innerRadius + (width / 2), 0, 0);
        }
    }
}

Android fastboot waiting for devices

To use the fastboot command you first need to put your device in fastboot mode:

$ adb reboot bootloader

Once the device is in fastboot mode, you can boot it with your own kernel, for example:

$ fastboot boot myboot.img

The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:

$ fastboot flash boot myboot.img

Hope that helps.

Issue with adding common code as git submodule: "already exists in the index"

I got it working by doing it the other way around. Starting with an empty repo, adding the submodule in a new folder called "projectfolder/common_code". After that it was possible to add the project code in projectfolder. The details are shown below.

In an empty repo type:

git submodule add url_to_repo projectfolder/common_code

That will create the desired folder structure:

repo
|-- projectfolder
    |-- common_code

It is now possible to add more submodules, and the project code can be added to projectfolder.

I can't yet say why it worked this way around and not the other.

Update Git submodule to latest commit on origin

Git 1.8.2 features a new option, --remote, that will enable exactly this behavior. Running

git submodule update --remote --merge

will fetch the latest changes from upstream in each submodule, merge them in, and check out the latest revision of the submodule. As the documentation puts it:

--remote

This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.

This is equivalent to running git pull in each submodule, which is generally exactly what you want.

How to encode the plus (+) symbol in a URL

In order to encode + value using JavaScript, you can use encodeURIComponent function.

Example:

_x000D_
_x000D_
var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)
_x000D_
_x000D_
_x000D_

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

String concatenation: concat() vs "+" operator

Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts

String a = b + c + d;

into

String a = new StringBuilder(b).append(c).append(d).toString();

which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.

However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this.

So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this.

How to setup Main class in manifest file in jar produced by NetBeans project

Brother you don't need to set class path just follow these simple steps (I use Apache NetBeans)

Steps:

  1. extract the jar file which you want to add in your project.

  2. only copy those packages (folder) which you need in the project. (do not copy manifest file)

  3. open the main project jar file(dist/file.jar) with WinRAR.

  4. paste that folder or package in the main project jar file.

  5. Those packages work 100% in your project.

warning: Do not make any changes in the manifest file.

Another method:

  • In my case lib folder present outside the dist(main jar file) folder.
  • we need to move lib folder in dist folder.then we set class path from manifest.mf file of main jar file.

    Edit the manifest.mf And ADD this type of line

  • Class-Path: lib\foldername\jarfilename.jar lib\foldername\jarfilename.jar

Warning: lib folder must be inside the dist folder otherwise jar file do not access your lib folder jar files

How to use vertical align in bootstrap

http://jsfiddle.net/b9chris/zN39r/

HTML:

<div class="item row">
    <div class="col-xs-12 col-sm-6"><h4>This is some text.</h4></div>
    <div class="col-xs-12 col-sm-6"><h4>This is some more.</h4></div>
</div>

CSS:

div.item div h4 {
    height: 60px;
    vertical-align: middle;    
    display: table-cell;
}

Important notes:

  • The vertical-align: middle; display: table-cell; must be applied to a tag that has no Bootstrap classes applied; it cannot be a col-*, a row, etc.
  • This can't be done without this extra, possibly pointless tag in your HTML, unfortunately.
  • The backgrounds are unnecessary - they're just there for demo purposes. So, you don't need to apply any special rules to the row or col-* tags.
  • It is important to notice the inner tag does not stretch to 100% of the width of its parent; in our scenario this didn't matter but it may to you. If it does, you end up with something closer to some of the other answers here:

http://jsfiddle.net/b9chris/zN39r/1/

CSS:

div.item div {
    background: #fdd;
    table-layout: fixed;
    display: table;
}
div.item div h4 {
    height: 60px;
    vertical-align: middle;    
    display: table-cell;
    background: #eee;
}

Notice the added table-layout and display properties on the col-* tags. This must be applied to the tag(s) that have col-* applied; it won't help on other tags.

Which tool to build a simple web front-end to my database

For Data access you can use OData. Here is a demo where Scott Hanselman creates an OData front end to StackOverflow database in 30 minutes, with XML and JSON access: Creating an OData API for StackOverflow including XML and JSON in 30 minutes.

For administrative access, like phpMyAdmin package, there is no well established one. You may give a try to IIS Database Manager.

Does JavaScript pass by reference?

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed

Invalidating JSON Web Tokens

An alternative would be to have a middleware script just for critical API endpoints.
This middleware script would check in the database if the token is invalidated by an admin.
This solution may be useful for cases where is not necessary to completely block the access of a user right away.

Permission denied at hdfs

I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml

<property>
  <name>dfs.permissions</name>
  <value>false</value>
</property>

How to check for null in a single statement in scala?

If it instead returned Option[QueueObject] you could use a construct like getObject.foreach { QueueManager.add }. You can wrap it right inline with Option(getObject).foreach ... because Option[QueueObject](null) is None.

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

Java logical operator short-circuiting

SET A uses short-circuiting boolean operators.

What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).

For example:

// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)

// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)

How do I programmatically force an onchange event on an input?

In jQuery I mostly use:

$("#element").trigger("change");

ASP.NET MVC View Engine Comparison

I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.

Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.

How to set up default schema name in JPA configuration?

For others who use spring-boot, java based configuration,

I set the schema value in application.properties

spring.jpa.properties.hibernate.dialect=...
spring.jpa.properties.hibernate.default_schema=...

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

Django 1.7 - makemigrations not detecting changes

If you're changing over from an existing app you made in django 1.6, then you need to do one pre-step (as I found out) listed in the documentation:

python manage.py makemigrations your_app_label

The documentation does not make it obvious that you need to add the app label to the command, as the first thing it tells you to do is python manage.py makemigrations which will fail. The initial migration is done when you create your app in version 1.7, but if you came from 1.6 it wouldn't have been carried out. See the 'Adding migration to apps' in the documentation for more details.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

For me the following works good. Just add it. You can edit it as per your requirement. This is just a nice trick I use.

text-shadow : 0 0 0 #your-font-color;

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

Page scroll when soft keyboard popped up

well the simplest answer i tried is just remove your code which makes the activity go full screen .I had a code like this which was responsible for making my activity go fullscreen :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

i just removed my code and it works completely fine although if you want to achieve this with your fullscreen on then you'll have to try some other methods

Executing multiple SQL queries in one statement with PHP

Pass 65536 to mysql_connect as 5th parameter.

Example:

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) 
    or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.

For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);
    SELECT * FROM table2;
");

Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    SELECT * FROM table2;
    INSERT INTO table1 (field1,field2) VALUES(1,2);
");

First char to upper case

userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";

or

userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
   userIdeaUC += userIdea.substring(1);

Difference between const reference and normal parameter

With

 void DoWork(int n);

n is a copy of the value of the actual parameter, and it is legal to change the value of n within the function. With

void DoWork(const int &n);

n is a reference to the actual parameter, and it is not legal to change its value.

include antiforgerytoken in ajax post ASP.NET MVC

You have incorrectly specified the contentType to application/json.

Here's an example of how this might work.

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

View:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="myDiv" data-url="@Url.Action("Index", "Home")">
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute
</div>

<script type="text/javascript">
    $('#myDiv').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                someValue: 'some value' 
            },
            success: function (result) {
                alert(result.someValue);
            }
        });
        return false;
    });
</script>

Can a table row expand and close?

It depends on your mark-up, but it can certainly be made to work, I used the following:

jQuery

$(document).ready(
  function() {
  $('td p').slideUp();
    $('td h2').click(
      function(){
       $(this).siblings('p').slideToggle();
      }
      );
  }
  );

html

  <table>
  <thead>
    <tr>
      <th>Actor</th>
      <th>Which Doctor</th>
      <th>Significant companion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><h2>William Hartnell</h2></td>
      <td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
    <tr>
      <td><h2>Patrick Troughton</h2></td>
      <td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
    <tr>
      <td><h2>Jon Pertwee</h2></td>
      <td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
  </tbody>
</table>

The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp() as the paragraphs were hidden, and still leave an element, h2 to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.

Demo at JS Bin


As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p elements this would work:

$(document).ready(
  function() {
  $('td p').slideUp();
    $('td h2').click(
      function(){
       $(this).closest('tr').find('p').slideToggle();
      }
      );
  }
  );

Demo at JS Bin

C# Debug - cannot start debugging because the debug target is missing

Go to Project > properties > Debug Tab and set the Launch to "Project"

How to get a list of column names on Sqlite3 database?

If you do

.headers ON

you will get the desired result.

How to change default format at created_at and updated_at value laravel

If anyone is looking for a simple solution in Laravel 5.3:

  1. Let default timestamps() be saved as is i.e. '2016-11-14 12:19:49'
  2. In your views, format the field as below (or as required):

    date('F d, Y', strtotime($list->created_at))
    

It worked for me very well for me.

How to strip a specific word from a string?

You can also use a regexp with re.sub:

article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

Storing money in a decimal column - what precision and scale?

If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4) is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.

The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency type in the front end to DECIMAL(19, 4) type in the back end was that Currency exhibited bankers' rounding by nature, whereas DECIMAL(p, s) rounded by truncation.

An extra decimal place in storage for DECIMAL allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).

Yes, DECIMAL(24, 8) sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)

However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6) for storage. Accountants generally seem to favour four decimal places.


PS Avoid SQL Server's MONEY data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.


Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).

How to set default vim colorscheme

Your .vimrc file goes in your $HOME directory. In *nix, cd ~; vim .vimrc. The commands in the .vimrc are the same as you type in ex-mode in vim, only without the leading colon, so colo evening would suffice. Comments in the .vimrc are indicated with a leading double-quote.

To see an example vimrc, open $VIMRUNTIME/vimrc_example.vim from within vim

:e $VIMRUNTIME/vimrc_example.vim

Is there a bash command which counts files?

You can use the -R option to find the files along with those inside the recursive directories

ls -R | wc -l // to find all the files

ls -R | grep log | wc -l // to find the files which contains the word log

you can use patterns on the grep

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

Optional Parameters in Web Api Attribute Routing

Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

MyMethod(string name = "someDefaultValue", int? Id = null)

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Python unexpected EOF while parsing

Check if all the parameters of functions are defined before they are called. I faced this problem while practicing Kaggle.

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

How to read numbers from file in Python?

Assuming you don't have extraneous whitespace:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

You could condense the last for loop into a nested list comprehension:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

Determine if two rectangles overlap each other?

struct Rect
{
    Rect(int x1, int x2, int y1, int y2)
    : x1(x1), x2(x2), y1(y1), y2(y2)
    {
        assert(x1 < x2);
        assert(y1 < y2);
    }

    int x1, x2, y1, y2;
};

bool
overlap(const Rect &r1, const Rect &r2)
{
    // The rectangles don't overlap if
    // one rectangle's minimum in some dimension 
    // is greater than the other's maximum in
    // that dimension.

    bool noOverlap = r1.x1 > r2.x2 ||
                     r2.x1 > r1.x2 ||
                     r1.y1 > r2.y2 ||
                     r2.y1 > r1.y2;

    return !noOverlap;
}

"Proxy server connection failed" in google chrome

I had the same problem with a freshly installed copy of Chrome. If nothing works, and your Use a proxy server your LAN setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.

Remove quotes from String in Python

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)

Batch file script to zip files

for /d %%a in (*) do (ECHO zip -r -p "%%~na.zip" ".\%%a\*")

should work from within a batch.

Note that I've included an ECHO to simply SHOW the command that is proposed. You'd need to remove the ECHO keywor to EXECUTE the commands.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • CSS3 transition doesn't work with display property

    display:none; removes a block from the page as if it were never there. A block cannot be partially displayed; it’s either there or it’s not. The same is true for visibility; you can’t expect a block to be half hidden which, by definition, would be visible! Fortunately, you can use opacity for fading effects instead.
    - reference

    As an alternatiive CSS solution, you could play with opacity, height and padding properties to achieve the desirable effect:

    #header #button:hover > .content {
        opacity:1;
        height: 150px;
        padding: 8px;    
    }
    
    #header #button .content {
        opacity:0;
        height: 0;
        padding: 0 8px;
        overflow: hidden;
        transition: all .3s ease .15s;
    }
    

    (Vendor prefixes omitted due to brevity.)

    Here is a working demo. Also here is a similar topic on SO.

    _x000D_
    _x000D_
    #header #button {_x000D_
      width:200px;_x000D_
      background:#ddd;_x000D_
      transition: border-radius .3s ease .15s;_x000D_
    }_x000D_
    _x000D_
    #header #button:hover, #header #button > .content {_x000D_
        border-radius: 0px 0px 7px 7px;_x000D_
    }_x000D_
    _x000D_
    #header #button:hover > .content {_x000D_
      opacity: 1;_x000D_
      height: 150px;_x000D_
      padding: 8px;    _x000D_
    }_x000D_
    _x000D_
    #header #button > .content {_x000D_
      opacity:0;_x000D_
      clear: both;_x000D_
      height: 0;_x000D_
      padding: 0 8px;_x000D_
      overflow: hidden;_x000D_
    _x000D_
      -webkit-transition: all .3s ease .15s;_x000D_
      -moz-transition: all .3s ease .15s;_x000D_
      -o-transition: all .3s ease .15s;_x000D_
      -ms-transition: all .3s ease .15s;_x000D_
      transition: all .3s ease .15s;_x000D_
    _x000D_
      border: 1px solid #ddd;_x000D_
    _x000D_
      -webkit-box-shadow: 0px 2px 2px #ddd;_x000D_
      -moz-box-shadow: 0px 2px 2px #ddd;_x000D_
      box-shadow: 0px 2px 2px #ddd;_x000D_
      background: #FFF;_x000D_
    }_x000D_
    _x000D_
    #button > span { display: inline-block; padding: .5em 1em }
    _x000D_
    <div id="header">_x000D_
      <div id="button"> <span>This is a Button</span>_x000D_
        <div class="content">_x000D_
          This is the Hidden Div_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    OpenCV - DLL missing, but it's not?

    just open the bin folder and copy and paste the .dll files to the folder you are working in..it should fix the problem

    Differences between cookies and sessions?

    Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

    Most modern sites use the second approach, saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). You are probably using this approach without knowing it, and by deleting the cookies you effectively erase their matching sessions as you remove the unique session identifier contained in the cookies.

    Does reading an entire file leave the file handle open?

    Well, if you have to read file line by line to work with each line, you can use

    with open('Path/to/file', 'r') as f:
        s = f.readline()
        while s:
            # do whatever you want to
            s = f.readline()
    

    Or even better way:

    with open('Path/to/file') as f:
        for line in f:
            # do whatever you want to
    

    How to convert a date string to different format

    I assume I have import datetime before running each of the lines of code below

    datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
    

    prints "01/25/13".

    If you can't live with the leading zero, try this:

    dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
    print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)
    

    This prints "1/25/13".

    EDIT: This may not work on every platform:

    datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
    

    jQuery $(this) keyword

    When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

    When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

    $('.class-name').on('click', (evt) => {
        $(this).hide(); // does not run a DOM query
        $('.class-name').hide() // runs a DOM query
    }); 
    

    $(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

    Some more information:

    Web Performance with jQuery selectors

    Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

    In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

    When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

    Amazon products API - Looking for basic overview and information

    I agree that Amazon appears to be intentionally obfuscating even how to find the API documentation, as well as use it. I'm just speculating though.

    Renaming the services from "ECS" to "Product Advertising API" was probably also not the best move, it essentially invalidated all that Google mojo they had built up over time.

    It took me quite a while to 'discover' this updated link for the Product Advertising API. I don't remember being able to easily discover it through the typical 'Developer' link on the Amazon webpage. This documentation appears to valid and what I've worked from recently.

    The change to authentication procedures also seems to add further complexity, but I'm sure they have a reason for it.

    I use SOAP via C# to communicate with Amazon Product API.

    With the REST API you have to encrypt the whole URL in a fairly specific way. The params have to be sorted, etc. There is just more to do. With the SOAP API, you just encrypt the operation+timestamp, and thats it.

    Adam O'Neil's post here, How to get album, dvd, and blueray cover art from Amazon, walks through the SOAP with C# method. Its not the original sample I pulled down, and contrary to his comment, it was not an official Amazon sample I stumbled on, though the code looks identical. However, Adam does a good job at presenting all the necessary steps. I wish I could credit the original author.

    How to customize the back button on ActionBar

    So you can change it programmatically easily by using homeAsUpIndicator() function that added in android API level 18 and upper.

    ActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

    If you use support library

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

    javascript object max size limit

    There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

    The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

    To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

    Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

    var items = $.map(keys, function(item, i) {
      var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
      return
        '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
        '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
    });
    var jsonObj =
      '{"code":"' + code + '",'+
      '"defaultfile":"' + defaultfile + '",'+
      '"filename":"' + currentFile + '",'+
      '"lstResDef":[' + items.join(',') + ']}';
    

    Delete a row in DataGridView Control in VB.NET

    For Each row As DataGridViewRow In yourDGV.SelectedRows
        yourDGV.Rows.Remove(row)
    Next
    

    This will delete all rows that had been selected.

    Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    If your file my.cnf (usually in the etc folder) is correctly configured with

    socket=/var/lib/mysql/mysql.sock
    

    you can check if mysql is running with the following command:

    mysqladmin -u root -p status
    

    try changing your permission to mysql folder. If you are working locally, you can try:

    sudo chmod -R 777 /var/lib/mysql/
    

    that solved it for me

    how to parse JSONArray in android

    getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

    {"abridged_cast":["name": blah...]}
    ^ its trying to search for a value "characters"
    

    but you need to get into the array and then do a search for "characters"

    try this

    String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
    
        JSONObject jsonResponse;
        try {
            ArrayList<String> temp = new ArrayList<String>();
            jsonResponse = new JSONObject(json);
            JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
            for(int i=0;i<movies.length();i++){
                JSONObject movie = movies.getJSONObject(i);
                JSONArray characters = movie.getJSONArray("characters");
                for(int j=0;j<characters.length();j++){
                    temp.add(characters.getString(j));
                }
            }
            Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    checked it :)

    .autocomplete is not a function Error

    For my case, my another team member included another version of jquery.js when he add in bootstrap.min.js. After remove the extra jquery.js, the problem is solved

    using mailto to send email with an attachment

    this is not possible in "mailto" function.

    please go with server side coding(C#).make sure open vs in administrative permission.

    Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
    Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
    
    oMsg.Subject = "emailSubject";
    oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
    oMsg.BCC = "emailBcc";
    oMsg.To = "emailRecipient";
    
    string body = "emailMessage";
    
    oMsg.HTMLBody = "body";              
    oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
    
    oMsg.Display(false); //In order to displ
    

    google map API zoom range

    Available Zoom Levels

    Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

    Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

    As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

    • Road maps - seem to go up to zoom level 22 everywhere
    • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
    • Remote regions of Antarctica: 13
    • Gobi Desert: 17
    • Much of the U.S. and Europe: 21
    • "Deep zoom" locations: 22-23 (see bkaid's link)

    Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

    Map Scale at Various Zoom Levels

    Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

    meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

    Formula is from Chris Broadfoot's comment.


    Google Maps basics

    Zoom Level - zoom

    0 - 19

    0 lowest zoom (whole world)

    19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


    What you're looking for are the scales for each zoom level. Use these:

    20 : 1128.497220
    19 : 2256.994440
    18 : 4513.988880
    17 : 9027.977761
    16 : 18055.955520
    15 : 36111.911040
    14 : 72223.822090
    13 : 144447.644200
    12 : 288895.288400
    11 : 577790.576700
    10 : 1155581.153000
    9  : 2311162.307000
    8  : 4622324.614000
    7  : 9244649.227000
    6  : 18489298.450000
    5  : 36978596.910000
    4  : 73957193.820000
    3  : 147914387.600000
    2  : 295828775.300000
    1  : 591657550.500000
    

    jQuery Validate Plugin - How to create a simple custom rule?

    You can add a custom rule like this:

    $.validator.addMethod(
        'booleanRequired',
        function (value, element, requiredValue) {
            return value === requiredValue;
        },
        'Please check your input.'
    );
    

    And add it as a rule like this:

    PhoneToggle: {
        booleanRequired: 'on'
    }        
    

    PHP-FPM and Nginx: 502 Bad Gateway

    Don't forget that php-fpm is a service. After installing it, make sure you start it:

    # service php-fpm start
    # chkconfig php-fpm on
    

    How do I run a simple bit of code in a new thread?

    Here how can use threads with a progressBar , its just for understing how the threads works, in the form there are three progressBar and 4 button:

     public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Thread t, t2, t3;
        private void Form1_Load(object sender, EventArgs e)
        {
    
            CheckForIllegalCrossThreadCalls = false;
    
             t = new Thread(birinicBar); //evry thread workes with a new progressBar
    
    
             t2 = new Thread(ikinciBar);
    
    
             t3 = new Thread(ucuncuBar);
    
        }
    
        public void birinicBar() //to make progressBar work
        {
            for (int i = 0; i < 100; i++) {
                progressBar1.Value++;
                Thread.Sleep(100); // this progressBar gonna work faster
            }
        }
    
        public void ikinciBar()
        {
            for (int i = 0; i < 100; i++)
            {
                progressBar2.Value++;
                Thread.Sleep(200);
            }
    
    
        }
    
        public void ucuncuBar()
        {
            for (int i = 0; i < 100; i++)
            {
                progressBar3.Value++;
                Thread.Sleep(300);
            }
        }
    
        private void button1_Click(object sender, EventArgs e) //that button to start the threads
        {
            t.Start();
            t2.Start(); t3.Start();
    
        }
    
        private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar
        {
            t.Suspend();
            t2.Suspend();
            t3.Suspend();
        }
    
        private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping
        {
            t.Resume();
            t2.Resume();
            t3.Resume();
        }
    
        private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads
        {
            t.Abort();
            t2.Abort();
            t3.Abort();
        }
    }
    

    How to change an Eclipse default project into a Java project

    Using project Project facets we can configure characteristics and requirements for projects.

    To find Project facets on eclipse:

    • Step 1: Right click on the project and choose properties from the menu.
    • Step 2:Select project facets option. Click on Convert to faceted form... enter image description here

    • Step 3: We can find all available facets you can select and change their settings. enter image description here

    MySQL select rows where left join is null

    You could use the following query:

    SELECT  table1.id 
    FROM    table1 
            LEFT JOIN table2 
                ON table1.id IN (table2.user_one, table2.user_two)
    WHERE   table2.user_one IS NULL;
    

    Although, depending on your indexes on table2 you may find that two joins performs better:

    SELECT  table1.id 
    FROM    table1 
            LEFT JOIN table2 AS t1
                ON table1.id = t1.user_one
            LEFT JOIN table2 AS t2
                ON table1.id = t2.user_two
    WHERE   t1.user_one IS NULL
    AND     t2.user_two IS NULL;
    

    Syncing Android Studio project with Gradle files

    Keys combination:

    Ctrl + F5
    

    Syncs the project with Gradle files.

    How to retrieve inserted id after inserting row in SQLite using Python?

    All credits to @Martijn Pieters in the comments:

    You can use the function last_insert_rowid():

    The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

    angular 4: *ngIf with multiple conditions

    Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

    currentStatus !== 'open' || currentStatus !== 'reopen'
    

    perhaps you mean one of

    !(currentStatus === 'open' || currentStatus === 'reopen')
    (currentStatus !== 'open' && currentStatus !== 'reopen')
    

    What GRANT USAGE ON SCHEMA exactly do?

    GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

    If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

    The rights tests are done in order:

    Do you have `USAGE` on the schema? 
        No:  Reject access. 
        Yes: Do you also have the appropriate rights on the table? 
            No:  Reject access. 
            Yes: Check column privileges.
    

    Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

    The phrase:

    (assuming that the objects' own privilege requirements are also met)

    Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

    It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

    If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

    If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

    You need to set both permissions for people to actually be able to view the file.

    Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

    (The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

    Changing text color of menu item in navigation drawer

    Use app:itemIconTint in your NavigationView, ej:

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:itemTextColor="@color/customColor"
        app:itemIconTint="@color/customColor"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/activity_home_drawer" />
    

    Const in JavaScript: when to use it and is it necessary?

    There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so.

    The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.

    The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.

    In Spring MVC, how can I set the mime type header when using @ResponseBody

    I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1, the implementation looks quite neat:

    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
        method = RequestMethod.GET
        value = "/foo/bar")
    @ResponseBody
    public Bar fooBar(){
        return myService.getBar();
    }
    

    Comments:

    First, the <mvc:annotation-driven /> or the @EnableWebMvc must be added to your application config.

    Next, the produces attribute of the @RequestMapping annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or "application/json").

    Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the MappingJacksonHttpMessageConverter will be under the hood).

    Set min-width either by content or 200px (whichever is greater) together with max-width

    The problem is that flex: 1 sets flex-basis: 0. Instead, you need

    .container .box {
      min-width: 200px;
      max-width: 400px;
      flex-basis: auto; /* default value */
      flex-grow: 1;
    }
    

    _x000D_
    _x000D_
    .container {_x000D_
      display: -webkit-flex;_x000D_
      display: flex;_x000D_
      -webkit-flex-wrap: wrap;_x000D_
      flex-wrap: wrap;_x000D_
    }_x000D_
    _x000D_
    .container .box {_x000D_
      -webkit-flex-grow: 1;_x000D_
      flex-grow: 1;_x000D_
      min-width: 100px;_x000D_
      max-width: 400px;_x000D_
      height: 200px;_x000D_
      background-color: #fafa00;_x000D_
      overflow: hidden;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
      <div class="box">_x000D_
        <table>_x000D_
          <tr>_x000D_
            <td>Content</td>_x000D_
            <td>Content</td>_x000D_
            <td>Content</td>_x000D_
          </tr>_x000D_
        </table>    _x000D_
      </div>_x000D_
      <div class="box">_x000D_
        <table>_x000D_
          <tr>_x000D_
            <td>Content</td>_x000D_
          </tr>_x000D_
        </table>    _x000D_
      </div>_x000D_
      <div class="box">_x000D_
        <table>_x000D_
          <tr>_x000D_
            <td>Content</td>_x000D_
            <td>Content</td>_x000D_
          </tr>_x000D_
        </table>    _x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Valid values for android:fontFamily and what they map to?

    Where do these values come from? The documentation for android:fontFamily does not list this information in any place

    These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

    In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

    Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

    <item name="android:fontFamily">sans-serif</item>
    

    Like the linked answer already stated, 12 variants are possible:

    Added in Android Jelly Bean (4.1) - API 16 :

    Regular (default):

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">normal</item> 
    

    Italic:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">italic</item>
    

    Bold:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    

    Bold-italic:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold|italic</item>
    

    Light:

    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    

    Light-italic:

    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">italic</item>
    

    Thin :

    <item name="android:fontFamily">sans-serif-thin</item>
    <item name="android:textStyle">normal</item>
    

    Thin-italic :

    <item name="android:fontFamily">sans-serif-thin</item>
    <item name="android:textStyle">italic</item>
    

    Condensed regular:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">normal</item>
    

    Condensed italic:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">italic</item>
    

    Condensed bold:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">bold</item>
    

    Condensed bold-italic:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">bold|italic</item>
    

    Added in Android Lollipop (v5.0) - API 21 :

    Medium:

    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textStyle">normal</item>
    

    Medium-italic:

    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textStyle">italic</item>
    

    Black:

    <item name="android:fontFamily">sans-serif-black</item>
    <item name="android:textStyle">italic</item>
    

    For quick reference, this is how they all look like:

    What does the "at" (@) symbol do in Python?

    An @ symbol at the beginning of a line is used for class, function and method decorators.

    Read more here:

    PEP 318: Decorators

    Python Decorators

    The most common Python decorators you'll run into are:

    @property

    @classmethod

    @staticmethod

    If you see an @ in the middle of a line, that's a different thing, matrix multiplication. See this answer showing the use of @ as a binary operator.

    How to find third or n?? maximum salary from salary table?

    select min(salary) 
    from (select salary 
          from employee 
          where rownum < n+1 
          order by salary desc);
    

    Python - use list as function parameters

    This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.

    def some_func(a_char, a_float, a_something):
        print a_char
    
    params = ['a', 3.4, None]
    some_func(*params)
    
    >> a
    

    LINQ-to-SQL vs stored procedures?

    I think the pro LINQ argument seems to be coming from people who don't have a history with database development (in general).

    Especially if using a product like VS DB Pro or Team Suite, many of the arguments made here do not apply, for instance:

    Harder to maintain and Test: VS provides full syntax checking, style checking, referential and constraint checking and more. It also provide full unit testing capabilities and refactoring tools.

    LINQ makes true unit testing impossible as (in my mind) it fails the ACID test.

    Debugging is easier in LINQ: Why? VS allows full step-in from managed code and regular debugging of SPs.

    Compiled into a single DLL rather than deployment scripts: Once again, VS comes to the rescue where it can build and deploy full databases or make data-safe incremental changes.

    Don't have to learn TSQL with LINQ: No you don't, but you have to learn LINQ - where's the benefit?

    I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.

    Um, loosely coupled apps are the ultimate goal of all good programmers as they really do increase flexibility. Being able to change things in isolation is fantastic, and it is your unit tests that will ensure it is still returning appropriate results.

    Before you all get upset, I think LINQ has its place and has a grand future. But for complex, data-intensive applications I do not think it is ready to take the place of stored procedures. This was a view I had echoed by an MVP at TechEd this year (they will remain nameless).

    EDIT: The LINQ to SQL Stored Procedure side of things is something I still need to read more on - depending on what I find I may alter my above diatribe ;)

    Access IP Camera in Python OpenCV

    To access an Ip Camera, first, I recommend you to install it like you are going to use for the standard application, without any code, using normal software.

    After this, you have to know that for different cameras, we have different codes. There is a website where you can see what code you can use to access them:

    https://www.ispyconnect.com/sources.aspx

    But be careful, for my camera (Intelbras S3020) it does not work. The right way is to ask the company of your camera, and if they are a good company they will provide it.

    When you know your code just add it like:

    cap = cv2.VideoCapture("http://LOGIN:PASSWORD@IP/cgi-bin/mjpg/video.cgi?&subtype=1")
    

    Instead LOGIN you will put your login, and instead PASSWORD you will put your password.

    To find out camera's IP address there is many softwares that you can download and provide the Ip address to you. I use the software from Intelbras, but I also recommend EseeCloud because they work for almost all cameras that I've bought:

    https://eseecloud.software.informer.com/1.2/

    In this example, it shows the protocol http to access the Ip camera, but you can also use rstp, it depends on the camera, as I said.

    If you have any further questions just let me know.

    How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

    Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)

    How to convert an object to a byte array in C#

    Take a look at Serialization, a technique to "convert" an entire object to a byte stream. You may send it to the network or write it into a file and then restore it back to an object later.

    How to "set a breakpoint in malloc_error_break to debug"

    Set a breakpoint on malloc_error_break() by opening the Breakpoint Navigator (View->Navigators->Show Breakpoint Navigator or ?8), clicking the plus button in the lower left corner, and selecting "Add Symbolic Breakpoint". In the popup that comes up, enter malloc_error_break in the Symbol field, then click Done.

    EDIT: openfrog added a screenshot and indicated that he's already tried these steps without success after I posted my answer. With that edit, I'm not sure what to say. I haven't seen that fail to work myself, and indeed I always keep a breakpoint on malloc_error_break set.

    How can I count the occurrences of a string within a file?

    The number of string occurrences (not lines) can be obtained using grep with -o option and wc (word count):

    $ echo "echo 1234 echo" | grep -o echo
    echo
    echo
    $ echo "echo 1234 echo" | grep -o echo | wc -l
    2
    

    So the full solution for your problem would look like this:

    $ grep -o "echo" FILE | wc -l
    

    EXCEL Multiple Ranges - need different answers for each range

    Nested if's in Excel Are ugly:

    =If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))
    

    That should cover it.

    How to list the properties of a JavaScript object?

    Under browsers supporting js 1.8:

    [i for(i in obj)]
    

    Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

    Things you can add to declarations: [] in modules

    • Pipe
    • Directive
    • Component

    Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

    Web-scraping JavaScript page with Python

    I personally prefer using scrapy and selenium and dockerizing both in separate containers. This way you can install both with minimal hassle and crawl modern websites that almost all contain javascript in one form or another. Here's an example:

    Use the scrapy startproject to create your scraper and write your spider, the skeleton can be as simple as this:

    import scrapy
    
    
    class MySpider(scrapy.Spider):
        name = 'my_spider'
        start_urls = ['https://somewhere.com']
    
        def start_requests(self):
            yield scrapy.Request(url=self.start_urls[0])
    
    
        def parse(self, response):
    
            # do stuff with results, scrape items etc.
            # now were just checking everything worked
    
            print(response.body)
    

    The real magic happens in the middlewares.py. Overwrite two methods in the downloader middleware, __init__ and process_request, in the following way:

    # import some additional modules that we need
    import os
    from copy import deepcopy
    from time import sleep
    
    from scrapy import signals
    from scrapy.http import HtmlResponse
    from selenium import webdriver
    
    class SampleProjectDownloaderMiddleware(object):
    
    def __init__(self):
        SELENIUM_LOCATION = os.environ.get('SELENIUM_LOCATION', 'NOT_HERE')
        SELENIUM_URL = f'http://{SELENIUM_LOCATION}:4444/wd/hub'
        chrome_options = webdriver.ChromeOptions()
    
        # chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
        self.driver = webdriver.Remote(command_executor=SELENIUM_URL,
                                       desired_capabilities=chrome_options.to_capabilities())
    
    
    def process_request(self, request, spider):
    
        self.driver.get(request.url)
    
        # sleep a bit so the page has time to load
        # or monitor items on page to continue as soon as page ready
        sleep(4)
    
        # if you need to manipulate the page content like clicking and scrolling, you do it here
        # self.driver.find_element_by_css_selector('.my-class').click()
    
        # you only need the now properly and completely rendered html from your page to get results
        body = deepcopy(self.driver.page_source)
    
        # copy the current url in case of redirects
        url = deepcopy(self.driver.current_url)
    
        return HtmlResponse(url, body=body, encoding='utf-8', request=request)
    

    Dont forget to enable this middlware by uncommenting the next lines in the settings.py file:

    DOWNLOADER_MIDDLEWARES = {
    'sample_project.middlewares.SampleProjectDownloaderMiddleware': 543,}
    

    Next for dockerization. Create your Dockerfile from a lightweight image (I'm using python Alpine here), copy your project directory to it, install requirements:

    # Use an official Python runtime as a parent image
    FROM python:3.6-alpine
    
    # install some packages necessary to scrapy and then curl because it's  handy for debugging
    RUN apk --update add linux-headers libffi-dev openssl-dev build-base libxslt-dev libxml2-dev curl python-dev
    
    WORKDIR /my_scraper
    
    ADD requirements.txt /my_scraper/
    
    RUN pip install -r requirements.txt
    
    ADD . /scrapers
    

    And finally bring it all together in docker-compose.yaml:

    version: '2'
    services:
      selenium:
        image: selenium/standalone-chrome
        ports:
          - "4444:4444"
        shm_size: 1G
    
      my_scraper:
        build: .
        depends_on:
          - "selenium"
        environment:
          - SELENIUM_LOCATION=samplecrawler_selenium_1
        volumes:
          - .:/my_scraper
        # use this command to keep the container running
        command: tail -f /dev/null
    

    Run docker-compose up -d. If you're doing this the first time it will take a while for it to fetch the latest selenium/standalone-chrome and the build your scraper image as well.

    Once it's done, you can check that your containers are running with docker ps and also check that the name of the selenium container matches that of the environment variable that we passed to our scraper container (here, it was SELENIUM_LOCATION=samplecrawler_selenium_1).

    Enter your scraper container with docker exec -ti YOUR_CONTAINER_NAME sh , the command for me was docker exec -ti samplecrawler_my_scraper_1 sh, cd into the right directory and run your scraper with scrapy crawl my_spider.

    The entire thing is on my github page and you can get it from here

    Font awesome is not showing icon

    Check that the path to your CSS file is correct. Rather prefer absolute links, they are easier to understand since we know where we start from and search engines will also prefer them over relative links. And to reduce bandwidth rather use the link from font-awesome servers:

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css">
    

    Moreover if you use it, there will be no need of uploading extra fonts to your server and you will be sure that you point to the right CSS file, and you will also benefit from the latest updates instantly.

    Selected value for JSP drop down using JSTL

    Below is Example of simple dropdown using jstl tag

     <form:select path="cityFrom">  
        <form:option value="Ghaziabad" label="Ghaziabad"/>  
        <form:option value="Modinagar" label="Modinagar"/>  
        <form:option value="Meerut" label="Meerut"/>  
        <form:option value="Amristar" label="Amristar"/>  
     </form:select>
    

    ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

    Applications using JDBC 10.1 has got a bug (Doc ID 370438.1) and can throw the same ORA-01461 exception while working with UTF8 character set database even though inserted characters are less than the maximum size of the column.

    Recommended Solution: - Use 10gR2 JDBC drivers or higher in such case.

    HTH

    Guzzlehttp - How get the body of a response from Guzzle 6?

    Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

    $contents = (string) $response->getBody();
    

    You can also do it with

    $contents = $response->getBody()->getContents();
    

    The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

    $stream = $response->getBody();
    $contents = $stream->getContents(); // returns all the contents
    $contents = $stream->getContents(); // empty string
    $stream->rewind(); // Seek to the beginning
    $contents = $stream->getContents(); // returns all the contents
    

    Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

    $contents = (string) $response->getBody(); // returns all the contents
    $contents = (string) $response->getBody(); // returns all the contents
    

    Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

    Select elements by attribute

    if (!$("#element").attr('my_attr')){
      //return false
      //attribute doesn't exists
    }
    

    Calculate row means on subset of columns

    Using dplyr:

    library(dplyr)
    
    # exclude ID column then get mean
    DF %>%
      transmute(ID,
                Mean = rowMeans(select(., -ID)))
    

    Or

    # select the columns to include in mean
    DF %>%
      transmute(ID,
                Mean = rowMeans(select(., C1:C3)))
    
    #   ID     Mean
    # 1  A 3.666667
    # 2  B 4.333333
    # 3  C 3.333333
    # 4  D 4.666667
    # 5  E 4.333333
    

    Encrypt and Decrypt in Java

    Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.

    Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.

    DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.

    Steps :

    1. Add the Security Provider : We are using the SunJCE Provider that is available with the JDK.
    2. Generate Secret Key : Use KeyGenerator and an algorithm to generate a secret key. We are using DESede.
    3. Encode Text : For consistency across platform encode the plain text as byte using UTF-8 encoding.
    4. Encrypt Text : Instantiate Cipher with ENCRYPT_MODE, use the secret key and encrypt the bytes.
    5. Decrypt Text : Instantiate Cipher with DECRYPT_MODE, use the same secret key and decrypt the bytes.

    All the above given steps and concept are same, we just replace algorithms.

    import java.util.Base64;    
    import javax.crypto.Cipher;  
    import javax.crypto.KeyGenerator;   
    import javax.crypto.SecretKey;  
    public class EncryptionDecryptionAES {  
        static Cipher cipher;  
    
        public static void main(String[] args) throws Exception {
            /* 
             create key 
             If we need to generate a new key use a KeyGenerator
             If we have existing plaintext key use a SecretKeyFactory
            */ 
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128); // block size is 128bits
            SecretKey secretKey = keyGenerator.generateKey();
    
            /*
              Cipher Info
              Algorithm : for the encryption of electronic data
              mode of operation : to avoid repeated blocks encrypt to the same values.
              padding: ensuring messages are the proper length necessary for certain ciphers 
              mode/padding are not used with stream cyphers.  
             */
            cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  
    
            String plainText = "AES Symmetric Encryption Decryption";
            System.out.println("Plain Text Before Encryption: " + plainText);
    
            String encryptedText = encrypt(plainText, secretKey);
            System.out.println("Encrypted Text After Encryption: " + encryptedText);
    
            String decryptedText = decrypt(encryptedText, secretKey);
            System.out.println("Decrypted Text After Decryption: " + decryptedText);
        }
    
        public static String encrypt(String plainText, SecretKey secretKey)
                throws Exception {
            byte[] plainTextByte = plainText.getBytes();
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedByte = cipher.doFinal(plainTextByte);
            Base64.Encoder encoder = Base64.getEncoder();
            String encryptedText = encoder.encodeToString(encryptedByte);
            return encryptedText;
        }
    
        public static String decrypt(String encryptedText, SecretKey secretKey)
                throws Exception {
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] encryptedTextByte = decoder.decode(encryptedText);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
            String decryptedText = new String(decryptedByte);
            return decryptedText;
        }
    }
    

    Output:

    Plain Text Before Encryption: AES Symmetric Encryption Decryption
    Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
    Decrypted Text After Decryption: AES Symmetric Encryption Decryption
    

    Source

    Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text. enter image description here

    Unable to start MySQL server

    I had the same issue. Try this, it should work!

    1. Right click on MySQL Notifier -> Actions -> Manage Monitored Items

    2. Highlight the MySQL56 entry and click the delete button

    3. Click the add button -> windows service
    4. Scroll down and look for MySQL56
    5. Highlight it and click ok