Programs & Examples On #Pressure

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

When using Object.keys, the following works:

Object.keys(this)
    .forEach(key => {
      console.log(this[key as keyof MyClass]);
    });

Correctly Parsing JSON in Swift 3

A big change that happened with Xcode 8 Beta 6 for Swift 3 was that id now imports as Any rather than AnyObject.

This means that parsedData is returned as a dictionary of most likely with the type [Any:Any]. Without using a debugger I could not tell you exactly what your cast to NSDictionary will do but the error you are seeing is because dict!["currently"]! has type Any

So, how do you solve this? From the way you've referenced it, I assume dict!["currently"]! is a dictionary and so you have many options:

First you could do something like this:

let currentConditionsDictionary: [String: AnyObject] = dict!["currently"]! as! [String: AnyObject]  

This will give you a dictionary object that you can then query for values and so you can get your temperature like this:

let currentTemperatureF = currentConditionsDictionary["temperature"] as! Double

Or if you would prefer you can do it in line:

let currentTemperatureF = (dict!["currently"]! as! [String: AnyObject])["temperature"]! as! Double

Hopefully this helps, I'm afraid I have not had time to write a sample app to test it.

One final note: the easiest thing to do, might be to simply cast the JSON payload into [String: AnyObject] right at the start.

let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! Dictionary<String, AnyObject>

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Accessing JSON elements

'temp_C' is a key inside dictionary that is inside a list that is inside a dictionary

This way works:

wjson['data']['current_condition'][0]['temp_C']
>> '10'

Convert Python dictionary to JSON array

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

What is "406-Not Acceptable Response" in HTTP?

If you are using 'request.js' you might use the following:

var options = {
  url: 'localhost',
  method: 'GET',
  headers:{
    Accept: '*/*'
  }
}

request(options, function (error, response, body) {
  ...
})

PHP Array to CSV

In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:

function array2csv($array, &$title, &$data) {
    foreach($array as $key => $value) {      
        if(is_array($value)) {
            $title .= $key . ",";
            $data .= "" . ",";
            array2csv($value, $title, $data);
        } else {
            $title .= $key . ",";
            $data .= '"' . $value . '",';
        }
    }
}

Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:

agentid     fname           lname      empid    totals  sales   leads   dish    dishnet top200_plus top120  latino  base_packages
G-adriana   ADRIANA EUGENIA PALOMO PAIZ 886                0    19              0         0         0         0      0

You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:

$title .= $key . ",";
$data .= "" . ",";

after the is_array() to compact the code further and remove the extra column.

Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:

$title .= PHP_EOL;
$data .= PHP_EOL;

Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

Peak detection in a 2D array

There are several and extensive pieces of software available from the astronomy and cosmology community - this is a significant area of research both historically and currently.

Do not be alarmed if you are not an astronomer - some are easy to use outside the field. For example, you could use astropy/photutils:

https://photutils.readthedocs.io/en/stable/detection.html#local-peak-detection

[It seems a bit rude to repeat their short sample code here.]

An incomplete and slightly biased list of techniques/packages/links that might be of interest is given below - do add more in the comments and I will update this answer as necessary. Of course there is a trade-off of accuracy vs compute resources. [Honestly, there are too many to give code examples in a single answer such as this so I am not sure whether this answer will fly or not.]

Source Extractor https://www.astromatic.net/software/sextractor

MultiNest https://github.com/farhanferoz/MultiNest [+ pyMultiNest]

ASKAP/EMU source-finding challenge: https://arxiv.org/abs/1509.03931

You could also search for Planck and/or WMAP source-extraction challenges.

...

Reading *.wav files in Python

You can accomplish this using the scikits.audiolab module. It requires NumPy and SciPy to function, and also libsndfile.

Note, I was only able to get it to work on Ubunutu and not on OSX.

from scikits.audiolab import wavread

filename = "testfile.wav"

data, sample_frequency,encoding = wavread(filename)

Now you have the wav data

SQL Server using wildcard within IN

I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or 
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%') 

Why do I need an IoC container as opposed to straightforward DI code?

Here is why. The project is called IOC-with-Ninject. You can download and run it with Visual Studio. This example uses Ninject but ALL the 'new' statements are in one location and you can completely change how your application runs by changing which bind module to use. The example is set up so you can bind to a mocked version of the services or the real version. In small projects that may not matter, but in big projects it's a big deal.

Just to be clear, advantages as I see them: 1) ALL new statements in one location at root of code. 2) Totally re-factor code with one change. 3) Extra points for 'cool factor' 'cause it's... well: cool. :p

Sort arrays of primitive types in descending order

In Java 8, a better and more concise approach could be:

double[] arr = {13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4};

Double[] boxedarr = Arrays.stream( arr ).boxed().toArray( Double[]::new );
Arrays.sort(boxedarr, Collections.reverseOrder());
System.out.println(Arrays.toString(boxedarr));

This would give the reversed array and is more presentable.

Input: [13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4]

Output: [100.4, 45.8, 21.09, 13.6, 9.12, 7.2, 6.02, 2.53]

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Android Studio AVD - Emulator: Process finished with exit code 1

Open AVD manager and click on the drop down along side with your emulator and select the show in disk and delete the file with .lock extension. After deleted, run your emulator. That works for me.

Cannot find or open the PDB file in Visual Studio C++ 2010

If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:

Use e.g.

D:\Visual Studio Projects\my_app\MyFile.pdb

Dont use e.g.

$(IntDir)\MyFile.pdb

in all the Sub-Projects !!!

= Compiler Param /Fd

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

For me in windows server 2012 R2 I solved it by removing the duplicates from web.config file i found this line duplicated twice i removed one line and kept the other line

<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>

orderBy multiple fields in Angular

<select ng-model="divs" ng-options="(d.group+' - '+d.sub) for d in divisions | orderBy:['group','sub']" />

User array instead of multiple orderBY

Combine several images horizontally with Python

my solution would be :

import sys
import os
from PIL import Image, ImageFilter
from PIL import ImageFont
from PIL import ImageDraw 

os.chdir('C:/Users/Sidik/Desktop/setup')
print(os.getcwd())

image_list= ['IMG_7292.jpg','IMG_7293.jpg','IMG_7294.jpg', 'IMG_7295.jpg' ]

image = [Image.open(x) for x in image_list]  # list
im_1 = image[0].rotate(270)
im_2 = image[1].rotate(270)
im_3 = image[2].rotate(270)
#im_4 = image[3].rotate(270)

height = image[0].size[0]
width = image[0].size[1]
# Create an empty white image frame
new_im = Image.new('RGB',(height*2,width*2),(255,255,255))

new_im.paste(im_1,(0,0))
new_im.paste(im_2,(height,0))
new_im.paste(im_3,(0,width))
new_im.paste(im_4,(height,width))


draw = ImageDraw.Draw(new_im)
font = ImageFont.truetype('arial',200)

draw.text((0, 0), '(a)', fill='white', font=font)
draw.text((height, 0), '(b)', fill='white', font=font)
draw.text((0, width), '(c)', fill='white', font=font)
#draw.text((height, width), '(d)', fill='white', font=font)

new_im.show()
new_im.save('BS1319.pdf')   
[![Laser spots on the edge][1]][1]

How to upgrade Angular CLI project?

Solution that worked for me:

  • Delete node_modules and dist folder
  • (in cmd)>> ng update --all --force
  • (in cmd)>> npm install typescript@">=3.4.0 and <3.5.0" --save-dev --save-exact
  • (in cmd)>> npm install --save core-js
  • Commenting import 'core-js/es7/reflect'; in polyfill.ts
  • (in cmd)>> ng serve

OOP vs Functional Programming vs Procedural

I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.

For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.

It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!

Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.

How copy data from Excel to a table using Oracle SQL Developer

You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.

Do anyone know how to import a new table with data from excel?

iOS: how to perform a HTTP POST request?

Here is an updated answer for iOS7+. It uses NSURLSession, the new hotness. Disclaimer, this is untested and was written in a text field:

- (void)post {
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com/dontposthere"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    // Uncomment the following two lines if you're using JSON like I imagine many people are (the person who is asking specified plain text)
    // [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setHTTPMethod:@"POST"];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }];
    [postDataTask resume];
}

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(    NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}

Or better yet, use AFNetworking 2.0+. Usually I would subclass AFHTTPSessionManager, but I'm putting this all in one method to have a concise example.

- (void)post {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://example.com"]];
    // Many people will probably want [AFJSONRequestSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // Many people will probably want [AFJSONResponseSerializer serializer];
    manager.responseSerializer = [AFHTTPRequestSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = NO; // Some servers require this to be YES, but default is NO.
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"username" password:@"password"];
    [[manager POST:@"dontposthere" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"darn it");
    }] resume];
}

If you are using the JSON response serializer, the responseObject will be object from the JSON response (often NSDictionary or NSArray).

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

Mounting multiple volumes on a docker container?

You can have Read only or Read and Write only on the volume

docker -v /on/my/host/1:/on/the/container/1:ro \

docker -v /on/my/host/2:/on/the/container/2:rw \

How to set the text/value/content of an `Entry` widget using a button in tkinter

You might want to use insert method. You can find the documentation for the Tkinter Entry Widget here.

This script inserts a text into Entry. The inserted text can be changed in command parameter of the Button.

from tkinter import *

def set_text(text):
    e.delete(0,END)
    e.insert(0,text)
    return

win = Tk()

e = Entry(win,width=10)
e.pack()

b1 = Button(win,text="animal",command=lambda:set_text("animal"))
b1.pack()

b2 = Button(win,text="plant",command=lambda:set_text("plant"))
b2.pack()

win.mainloop()

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

You also can use

start /MIN notepad.exe

PS: Unfortunatly, minimized window status depends on command to run. V.G. doen't work

start /MIN calc.exe

Creating a new empty branch for a new project

i found this help:

git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"

In OS X Lion, LANG is not set to UTF-8, how to fix it?

if you have zsh installed you can also update ~/.zprofile with

if [[ -z "$LC_ALL" ]]; then
  export LC_ALL='en_US.UTF-8'
fi

and check the output using the locale cmd as show above

? locale                                                                                                                                           
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"

What are Aggregates and PODs and how/why are they special?

What has changed for C++14

We can refer to the Draft C++14 standard for reference.

Aggregates

This is covered in section 8.5.1 Aggregates which gives us the following definition:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

The only change is now adding in-class member initializers does not make a class a non-aggregate. So the following example from C++11 aggregate initialization for classes with member in-place initializers:

struct A
{
  int a = 3;
  int b = 3;
};

was not an aggregate in C++11 but it is in C++14. This change is covered in N3605: Member initializers and aggregates, which has the following abstract:

Bjarne Stroustrup and Richard Smith raised an issue about aggregate initialization and member-initializers not working together. This paper proposes to fix the issue by adopting Smith's proposed wording that removes a restriction that aggregates can't have member-initializers.

POD stays the same

The definition for POD(plain old data) struct is covered in section 9 Classes which says:

A POD struct110 is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

which is the same wording as C++11.

Standard-Layout Changes for C++14

As noted in the comments pod relies on the definition of standard-layout and that did change for C++14 but this was via defect reports that were applied to C++14 after the fact.

There were three DRs:

So standard-layout went from this Pre C++14:

A standard-layout class is a class that:

  • (7.1) has no non-static data members of type non-standard-layout class (or array of such types) or reference,
  • (7.2) has no virtual functions ([class.virtual]) and no virtual base classes ([class.mi]),
  • (7.3) has the same access control (Clause [class.access]) for all non-static data members,
  • (7.4) has no non-standard-layout base classes,
  • (7.5) either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
  • (7.6) has no base classes of the same type as the first non-static data member.109

To this in C++14:

A class S is a standard-layout class if it:

  • (3.1) has no non-static data members of type non-standard-layout class (or array of such types) or reference,
  • (3.2) has no virtual functions and no virtual base classes,
  • (3.3) has the same access control for all non-static data members,
  • (3.4) has no non-standard-layout base classes,
  • (3.5) has at most one base class subobject of any given type,
  • (3.6) has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
  • (3.7) has no element of the set M(S) of types as a base class, where for any type X, M(X) is defined as follows.104 [ Note: M(X) is the set of the types of all non-base-class subobjects that may be at a zero offset in X. — end note ]
    • (3.7.1) If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
    • (3.7.2) If X is a non-union class type with a non-static data member of type X0 that is either of zero size or is the first non-static data member of X (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
    • (3.7.3) If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
    • (3.7.4) If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
    • (3.7.5) If X is a non-class, non-array type, the set M(X) is empty.

Resolving require paths with webpack

I didn't get why anybody suggested to include myDir's parent directory into modulesDirectories in webpack, that should make the trick easily:

resolve: {
    modulesDirectories: [
      'parentDir',
      'node_modules',
    ],
    extensions: ['', '.js', '.jsx']
  },

'tsc command not found' in compiling typescript

I had to do this:

npx tsc app.ts

Trigger a keypress/keydown/keyup event in JS/jQuery?

Here's a vanilla js example to trigger any event:

function triggerEvent(el, type){
if ('createEvent' in document) {
        // modern browsers, IE9+
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

Show which git tag you are on?

Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:

git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)

original answer follows:

git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...

This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.

The $() syntax above assumes you're using bash or similar.

Catching errors in Angular HttpClient

Following @acdcjunior answer, this is how I implemented it

service:

  get(url, params): Promise<Object> {

            return this.sendRequest(this.baseUrl + url, 'get', null, params)
                .map((res) => {
                    return res as Object
                }).catch((e) => {
                    return Observable.of(e);
                })
                .toPromise();
        }

caller:

this.dataService.get(baseUrl, params)
            .then((object) => {
                if(object['name'] === 'HttpErrorResponse') {
                            this.error = true;
                           //or any handle
                } else {
                    this.myObj = object as MyClass 
                }
           });

Creating Unicode character from its number

(ANSWER IS IN DOT NET 4.5 and in java, there must be a similar approach exist)

I am from West Bengal in INDIA. As I understand your problem is ... You want to produce similar to ' ? ' (It is a letter in Bengali language) which has Unicode HEX : 0X0985.

Now if you know this value in respect of your language then how will you produce that language specific Unicode symbol right ?

In Dot Net it is as simple as this :

int c = 0X0985;
string x = Char.ConvertFromUtf32(c);

Now x is your answer. But this is HEX by HEX convert and sentence to sentence conversion is a work for researchers :P

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close() method:

>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor

The line del f deletes the last reference to the file object, causing its destructor file.__del__ to be called. The internal state of the file object indicates the file is still open since f.close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

Since the implementation of os.system() does not create any Python file objects, it does not seem likely that the system() call is the origin of the error. Maybe you could show a bit more code?

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to clear an ImageView in Android?

This works for me.

emoji.setBackground(null);

This crashes in runtime.

viewToUse.setImageResource(android.R.color.transparent);  

Getting query parameters from react-router hash fragment

After reading the other answers (First by @duncan-finney and then by @Marrs) I set out to find the change log that explains the idiomatic react-router 2.x way of solving this. The documentation on using location (which you need for queries) in components is actually contradicted by the actual code. So if you follow their advice, you get big angry warnings like this:

Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.

It turns out that you cannot have a context property called location that uses the location type. But you can use a context property called loc that uses the location type. So the solution is a small modification on their source as follows:

const RouteComponent = React.createClass({
    childContextTypes: {
        loc: PropTypes.location
    },

    getChildContext() {
        return { location: this.props.location }
    }
});

const ChildComponent = React.createClass({
    contextTypes: {
        loc: PropTypes.location
    },
    render() {
        console.log(this.context.loc);
        return(<div>this.context.loc.query</div>);
    }
});

You could also pass down only the parts of the location object you want in your children get the same benefit. It didn't change the warning to change to the object type. Hope that helps.

Printing without newline (print 'a',) prints a space, how to remove?

WOW!!!

It's pretty long time ago

Now, In python 3.x it will be pretty easy

code:

for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code

output:

aaaaaaaaaaaaaaaaaaaa 

More about print() function

print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)

Here:

value1,value2,value3

you can print multiple values using commas

sep = '-'

3 values will be separated by '-' character

you can use any character instead of that even string like sep='@' or sep='good'

end='\n'

by default print function put '\n' charater at the end of output

but you can use any character or string by changing end variale value

like end='$' or end='.' or end='Hello'

file=sys.stdout

this is a default value, system standard output

using this argument you can create a output file stream like

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txt where your output I am a Programmer will be stored

flush = False

It's a default value using flush=True you can forcibly flush the stream

Adding placeholder text to textbox

Add this class your project and build your solution. Click to Toolbox on visual studio you will see a new textbox component named PlaceholderTextBox. Delete your current textbox on form designe and replace with PlaceHolderTextBox.

enter image description here

PlaceHolderTextBox has a property PlaceHolderText. Set any text you want and have nice day :)

public class PlaceHolderTextBox : TextBox
{

    bool isPlaceHolder = true;
    string _placeHolderText;
    public string PlaceHolderText
    {
        get { return _placeHolderText; }
        set
        {
            _placeHolderText = value;
            setPlaceholder();
        }
    }

    public new string Text
    {
        get => isPlaceHolder ? string.Empty : base.Text;
        set => base.Text = value;
    }

    //when the control loses focus, the placeholder is shown
    private void setPlaceholder()
    {
        if (string.IsNullOrEmpty(base.Text))
        {
            base.Text = PlaceHolderText;
            this.ForeColor = Color.Gray;
            this.Font = new Font(this.Font, FontStyle.Italic);
            isPlaceHolder = true;
        }
    }

    //when the control is focused, the placeholder is removed
    private void removePlaceHolder()
    {

        if (isPlaceHolder)
        {
            base.Text = "";
            this.ForeColor = System.Drawing.SystemColors.WindowText;
            this.Font = new Font(this.Font, FontStyle.Regular);
            isPlaceHolder = false;
        }
    }
    public PlaceHolderTextBox()
    {
        GotFocus += removePlaceHolder;
        LostFocus += setPlaceholder;
    }

    private void setPlaceholder(object sender, EventArgs e)
    {
        setPlaceholder();
    }

    private void removePlaceHolder(object sender, EventArgs e)
    {
        removePlaceHolder();
    }
}

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Regular Expression to select everything before and up to a particular text

This matches everything up to ".txt" (without including it):

^.*(?=(\.txt))

Visual Studio Copy Project

Following Shane's answer above (which works great BTW)…

You might encounter a slew of yellow triangles in the reference list. Most of these can be eliminated by a Build->Clean Solution and Build->Rebuild Solution.

I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.

Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.

To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

insert/delete/update trigger in SQL server

I use that for all status (update, insert and delete)

CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE 
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Activity  NVARCHAR (50)

-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
    SET @Activity = 'UPDATE'
END

-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
    SET @Activity = 'INSERT'
END

-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
    SET @Activity = 'DELETE'
END



-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                 UNION 
                                                 SELECT * FROM deleted
                                                 ) AS A ORDER BY A.Date DESC
                            ) AS T


-- try catch
BEGIN TRY 

    INSERT INTO MyTable  (
           [Code]
          ,[Name]
           .....
          ,[Activity])
    SELECT [Code]
          ,[Name]
          ,@Activity 
    FROM #tmpTbl

END TRY BEGIN CATCH END CATCH


-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

SET NOCOUNT OFF;
END

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

Pass a PHP string to a JavaScript variable (and escape newlines)

I have had a similar issue and understand that the following is the best solution:

<script>
    var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>

However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's rawurlencode() function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript's decodeURIComponent().

How to create a file in Android?

From here: http://www.anddev.org/working_with_files-t115.html

//Writing a file...  



try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 
      {ioe.printStackTrace();}

Set UILabel line spacing

Best thing I found is: https://github.com/mattt/TTTAttributedLabel

It's a UILabel subclass so you can just drop it in, and then to change the line height:

myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Find a string by searching all tables in SQL Server Management Studio 2008

This was very helpful. I wanted to import this function to a Postgre SQL database. Thought i would share it with anyone who is interested. Will have them a few hours. Note: this function creates a list of SQL statements that can be copied and executed on the Postgre database. Maybe someone smarter then me can get Postgre to create and execute the statements all in one function.

CREATE OR REPLACE FUNCTION SearchAllTables(_search text) RETURNS TABLE( txt text ) as $funct$
    DECLARE __COUNT int;
    __SQL text;
BEGIN
    EXECUTE 'SELECT COUNT(0) FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = ''text'' 
                    AND          table_schema = ''public'' ' INTO __COUNT;

    RETURN QUERY 
        SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY table_name) < __COUNT THEN 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'' UNION ALL' 
            ELSE 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'''
        END AS txt

                    FROM     INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = 'text' 
                    AND          table_schema = 'public';
END
$funct$ LANGUAGE plpgsql;

How to link to apps on the app store

Apple just announced the appstore.com urls.

https://developer.apple.com/library/ios/qa/qa1633/_index.html

There are three types of App Store Short Links, in two forms, one for iOS apps, another for Mac Apps:

Company Name

iOS: http://appstore.com/ for example, http://appstore.com/apple

Mac: http://appstore.com/mac/ for example, http://appstore.com/mac/apple

App Name

iOS: http://appstore.com/ for example, http://appstore.com/keynote

Mac: http://appstore.com/mac/ for example, http://appstore.com/mac/keynote

App by Company

iOS: http://appstore.com// for example, http://appstore.com/apple/keynote

Mac: http://appstore.com/mac// for example, http://appstore.com/mac/apple/keynote

Most companies and apps have a canonical App Store Short Link. This canonical URL is created by changing or removing certain characters (many of which are illegal or have special meaning in a URL (for example, "&")).

To create an App Store Short Link, apply the following rules to your company or app name:

Remove all whitespace

Convert all characters to lower-case

Remove all copyright (©), trademark (™) and registered mark (®) symbols

Replace ampersands ("&") with "and"

Remove most punctuation (See Listing 2 for the set)

Replace accented and other "decorated" characters (ü, å, etc.) with their elemental character (u, a, etc.)

Leave all other characters as-is.

Listing 2 Punctuation characters that must be removed.

!¡"#$%'()*+,-./:;<=>¿?@[]^_`{|}~

Below are some examples to demonstrate the conversion that takes place.

App Store

Company Name examples

Gameloft => http://appstore.com/gameloft

Activision Publishing, Inc. => http://appstore.com/activisionpublishinginc

Chen's Photography & Software => http://appstore.com/chensphotographyandsoftware

App Name examples

Ocarina => http://appstore.com/ocarina

Where’s My Perry? => http://appstore.com/wheresmyperry

Brain Challenge™ => http://appstore.com/brainchallenge

Get final URL after curl is redirected

The parameters -L (--location) and -I (--head) still doing unnecessary HEAD-request to the location-url.

If you are sure that you will have no more than one redirect, it is better to disable follow location and use a curl-variable %{redirect_url}.

This code do only one HEAD-request to the specified URL and takes redirect_url from location-header:

curl --head --silent --write-out "%{redirect_url}\n" --output /dev/null "https://""goo.gl/QeJeQ4"

Speed test

all_videos_link.txt - 50 links of goo.gl+bit.ly which redirect to youtube

1. With follow location

time while read -r line; do
    curl -kIsL -w "%{url_effective}\n" -o /dev/null  $line
done < all_videos_link.txt

Results:

real    1m40.832s
user    0m9.266s
sys     0m15.375s

2. Without follow location

time while read -r line; do
    curl -kIs -w "%{redirect_url}\n" -o /dev/null  $line
done < all_videos_link.txt

Results:

real    0m51.037s
user    0m5.297s
sys     0m8.094s

Sort array by firstname (alphabetically) in Javascript

Pushed the top answers into a prototype to sort by key.

Array.prototype.alphaSortByKey= function (key) {
    this.sort(function (a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    });
    return this;
};

Android YouTube app Play Video Intent

Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData(Uri.parse("http://m.youtube.com/watch?v="+videoId));
startActivityForResult(videoClient, 1234);

Where videoId is the video id of the youtube video that has to be played. This code works fine on Motorola Milestone.

But basically what we can do is to check for what activity is loaded when you start the Youtube app and accordingly substitute for the packageName and the className.

DropDownList in MVC 4 with Razor

Here is the easiest answer:

in your view only just add:

@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

OR in your controller add:

var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

and your view just add:

@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

I learned this with Jess Chadwick

How to check programmatically if an application is installed or not in Android?

Cleaner solution (without try-catch) than the accepted answer (based on AndroidRate Library):

public static boolean isPackageExists(@NonNull final Context context, @NonNull final String targetPackage) {
    List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(0);
    for (ApplicationInfo packageInfo : packages) {
        if (targetPackage.equals(packageInfo.packageName)) {
            return true;
        }
    }
    return false;
}

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

'<option value=''.$key.'">'

should be

'<option value="'.$key.'">'

How to check if spark dataframe is empty?

On PySpark, you can also use this bool(df.head(1)) to obtain a True of False value

It returns False if the dataframe contains no rows

How to change Jquery UI Slider handle

.ui-slider .ui-slider-handle{
    width:50px; 
    height:50px; 
    background:url(../images/slider_grabber.png) no-repeat; overflow: hidden; 
    position:absolute;
    top: -10px;
    border-style:none; 
}

operator << must take exactly one argument

I ran into this problem with templated classes. Here's a more general solution I had to use:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // Friend means operator<< can use private variables
    // It needs to be declared as a template, but T is taken
    template <class U>
    friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}

// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
  obj.toString(os);
  return os;
}

Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.

The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(

Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.

This works too:

template class <T>
class myClass
{
    int myField;

    // Helper function accessing my fields
    void toString(std::ostream&) const;

    // For some reason this requires using T, and not U as above
    friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
    {
        obj.toString(os);
        return os;
    }
}

I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.

If Else in LINQ

Answer above is not suitable for complicate Linq expression. All you need is:

// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
    test = test.Where(p => p.test == str);
}

Purpose of Unions in C and C++

@bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):

https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

since in the current case T1 and T2 donate the same type anyway.

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

How to quickly and conveniently create a one element arraylist

Collections.singletonList(object)

the list created by this method is immutable.

Group dataframe and get sum AND count?

try this:

In [110]: (df.groupby('Company Name')
   .....:    .agg({'Organisation Name':'count', 'Amount': 'sum'})
   .....:    .reset_index()
   .....:    .rename(columns={'Organisation Name':'Organisation Count'})
   .....: )
Out[110]:
          Company Name   Amount  Organisation Count
0  Vifor Pharma UK Ltd  4207.93                   5

or if you don't want to reset index:

df.groupby('Company Name')['Amount'].agg(['sum','count'])

or

df.groupby('Company Name').agg({'Amount': ['sum','count']})

Demo:

In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
                         sum  count
Company Name
Vifor Pharma UK Ltd  4207.93      5

In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
                      Amount
                         sum count
Company Name
Vifor Pharma UK Ltd  4207.93     5

Sending SMS from PHP

You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I've heard good things about Eigen and NT2, but haven't personally used either. There's also Boost.UBLAS, which I believe is getting a bit long in the tooth. The developers of NT2 are building the next version with the intention of getting it into Boost, so that might count for somthing.

My lin. alg. needs don't exteed beyond the 4x4 matrix case, so I can't comment on advanced functionality; I'm just pointing out some options.

Run function from the command line

If you install the runp package with pip install runp its a matter of running:

runp myfile.py hello

You can find the repository at: https://github.com/vascop/runp

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

The answers provided did not work for me (Chrome or Firefox) while creating PWA for local development and testing. DO NOT USE FOR PRODUCTION! I was able to use the following:

  1. Online certificate tools site with the following options:
    • Common Names: Add both the "localhost" and IP of your system e.g. 192.168.1.12
    • Subject Alternative Names: Add "DNS" = "localhost" and "IP" = <your ip here, e.g. 192.168.1.12>
    • "CRS" drop down options set to "Self Sign"
    • all other options were defaults
  2. Download all links
  3. Import .p7b cert into Windows by double clicking and select "install"/ OSX?/Linux?
  4. Added certs to node app... using Google's PWA example
    • add const https = require('https'); const fs = require('fs'); to the top of the server.js file
    • comment out return app.listen(PORT, () => { ... }); at the bottom of server.js file
    • add below https.createServer({ key: fs.readFileSync('./cert.key','utf8'), cert: fs.readFileSync('./cert.crt','utf8'), requestCert: false, rejectUnauthorized: false }, app).listen(PORT)

I have no more errors in Chrome or Firefox

How to rsync only a specific list of files?

For the record, none of the answers above helped except for one. To summarize, you can do the backup operation using --files-from= by using either:

 rsync -aSvuc `cat rsync-src-files` /mnt/d/rsync_test/

OR

 rsync -aSvuc --recursive --files-from=rsync-src-files . /mnt/d/rsync_test/

The former command is self explanatory, beside the content of the file rsync-src-files which I will elaborate down below. Now, if you want to use the latter version, you need to keep in mind the following four remarks:

  1. Notice one needs to specify both --files-from and the source directory
  2. One needs to explicitely specify --recursive.
  3. The file rsync-src-files is a user created file and it was placed within the src directory for this test
  4. The rsyn-src-files contain the files and folders to copy and they are taken relative to the source directory. IMPORTANT: Make sure there is not trailing spaces or blank lines in the file. In the example below, there are only two lines, not three (Figure it out by chance). Content of rsynch-src-files is:

folderName1
folderName2

How do I use su to execute the rest of the bash script as that user?

Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:

#!/bin/bash
if [ $UID -eq 0 ]; then
  user=$1
  dir=$2
  shift 2     # if you need some other parameters
  cd "$dir"
  exec su "$user" "$0" -- "$@"
  # nothing will be executed beyond that line,
  # because exec replaces running process with the new one
fi

echo "This will be run from user $UID"
...

How to "grep" for a filename instead of the contents of a file?

Also for multiple files.

tree /path/to/directory/ | grep -i "file1 \| file2 \| file3"

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Check which element has been clicked with jQuery

So you are doing this a bit backwards. Typically you'd do something like this:

?<div class='article'>
  Article 1
</div>
<div class='article'>
  Article 2
</div>
<div class='article'>
  Article 3
</div>?

And then in your jQuery:

$('.article').click(function(){
    article = $(this).text(); //$(this) is what you clicked!
    });?

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

Add a link to an image in a css style sheet

You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

Based only on your style you would have:

<a href="home.com" id="logo"></a>

Rails 4 Authenticity Token

These features were added for security and forgery protection purposes.
However, to answer your question, here are some inputs. You can add these lines after your the controller name.

Like so,

class NameController < ApplicationController
    skip_before_action :verify_authenticity_token

Here are some lines for different versions of rails.

Rails 3

skip_before_filter :verify_authenticity_token

Rails 4:

skip_before_action :verify_authenticity_token


Should you intend to disable this security feature for all controller routines, you can change the value of protect_from_forgery to :null_session on your application_controller.rb file.

Like so,

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It is an abbreviation for 'optional' , used for optional software in some distros.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How do I record audio on iPhone with AVAudioRecorder?

Its really helpful. The only problem i had was the size of sound file created after recording. I needed to reduce the file size so i did some changes in settings.

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];

File size reduced from 360kb to just 25kb (2 seconds recording).

Manifest Merger failed with multiple errors in Android Studio

Just add below code in your project Manifest application tag...

<application
        tools:node="replace">

Changing the row height of a datagridview

You can change the row height of the Datagridview in the .cs [Design].

Then click the datagridview Properties.

Look for RowTemplate and expand it,

then type the value in the Height.

How to change the Text color of Menu item in Android?

One simple line in your theme :)

<item name="android:actionMenuTextColor">@color/your_color</item>

App.settings - the Angular way?

Here's my solution, loads from .json to allow changes without rebuilding

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Location } from '@angular/common';

@Injectable()
export class ConfigService {

    private config: any;

    constructor(private location: Location, private http: Http) {
    }

    async apiUrl(): Promise<string> {
        let conf = await this.getConfig();
        return Promise.resolve(conf.apiUrl);
    }

    private async getConfig(): Promise<any> {
        if (!this.config) {
            this.config = (await this.http.get(this.location.prepareExternalUrl('/assets/config.json')).toPromise()).json();
        }
        return Promise.resolve(this.config);
    }
}

and config.json

{
    "apiUrl": "http://localhost:3000/api"
}

Convert Current date to integer

The issue is that an Integer is not large enough to store a current date, you need to use a Long.

The date is stored internally as the number of milliseconds since 1/1/1970.

The maximum Integer value is 2147483648, whereas the number of milliseconds since 1970 is currently in the order of 1345618537869

Putting the maximum integer value into a date yields Monday 26th January 1970.

Edit: Code to display division by 1000 as per comment below:

    int i = (int) (new Date().getTime()/1000);
    System.out.println("Integer : " + i);
    System.out.println("Long : "+ new Date().getTime());
    System.out.println("Long date : " + new Date(new Date().getTime()));
    System.out.println("Int Date : " + new Date(((long)i)*1000L));

Integer : 1345619256
Long : 1345619256308
Long date : Wed Aug 22 16:37:36 CST 2012
Int Date : Wed Aug 22 16:37:36 CST 2012

Excel data validation with suggestions/autocomplete

If you don't want to go down the VBA path, there is this trick from a previous question.

Excel 2010: how to use autocomplete in validation list

It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.

Convert String array to ArrayList

new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

Console.log not working at all

Click on the restore button. console.log will start to work.

enter image description here

How do I exit a foreach loop in C#?

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

PHP cURL, extract an XML response

no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.

use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

How do I convert a string to enum in TypeScript?

If the TypeScript compiler knows that the type of variable is string then this works:

let colorName : string = "Green";
let color : Color = Color[colorName];

Otherwise you should explicitly convert it to a string (to avoid compiler warnings):

let colorName : any = "Green";
let color : Color = Color["" + colorName];

At runtime both solutions will work.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

  1. Check if compatible Mysql for your PHP version is correctly installed. (eg. mysql-installer-community-5.5.40.1.msi for PHP 5.2.10, apache 2.2 and phpMyAdmin 3.5.2)
  2. In your php\php.ini set your loadable php extensions path (eg. extension_dir = "C:\php\ext") (https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)
  3. (In your php\php.ini) check if extension=php_mysqli.dll is uncommented (https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)
  4. Set your php folder (eg."C:\php") and php\ext folder (eg."C:\php\ext") as your runtime environment variable path (https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)
  5. Restart apache service (https://drive.google.com/open?id=1kJF5kxPSrj3LdKWJcJTos9ecKFx0ORAW)

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

This will work to both load and save a file into TXT from a HTML page with a save as choice

<html>
<body>

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>

<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

</script>

</body>
</html>

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

How to simulate target="_blank" in JavaScript

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

Is it possible only to declare a variable without assigning any value in Python?

You can trick an interpreter with this ugly oneliner if None: var = None It do nothing else but adding a variable var to local variable dictionary, not initializing it. Interpreter will throw the UnboundLocalError exception if you try to use this variable in a function afterwards. This would works for very ancient python versions too. Not simple, nor beautiful, but don't expect much from python.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

First of all, I suggest that you narrow the problem to which component throws the "Out of Memory Exception".

This could be:

  1. Eclipse itself (which I doubt)
  2. Your application under Tomcat

The JVM parameters -xms and -xmx represent the heap's "start memory" and the "maximum memory". Forget the "start memory". This is not going to help you now and you should only change this parameter if you're sure your app will consume this amount of memory rapidly.

In production, I think the only parameter that you can change is the -xmx under the Catalina.sh or Catalina.bat files. But if you are testing your webapp directly from Eclipse with a configured debug environment of Tomcat, you can simply go to your "Debug Configurations" > "Apache Tomcat" > "Arguments" > "VM arguments" and set the -xmx there.

As for the optimal -xmx for 2gb, this depends a lot of your environment and the number of requests your app might take. I would try values from 500mb up to 1gb. Check your OS virtual memory "zone" limit and the limit of the JVM itself.

How can I get Android Wifi Scan Results into a list?

In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

Check if input is number or letter javascript

You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    if (isNaN(x)) // this is the code I need to change
    {
        alert("Must input numbers");
        return false;
    }
}

Note: isNan considers 10.2 as a valid number.

CSS selectors ul li a {...} vs ul > li > a {...}

1) for example HTML code:

<ul>
    <li>
        <a href="#">firstlink</a>
        <span><a href="#">second link&lt;/a>
    </li>
</ul>

and css rules:

1) ul li a {color:red;} 
2) ul > li > a {color:blue;}

">" - symbol mean that that will be searching only child selector (parentTag > childTag)

so first css rule will apply to all links (first and second) and second rule will apply anly to first link

2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"

some thing like this. Hope I describe all properly for you

Check if string contains a value in array

I find this fast and simple without running loop.

$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";

$newStr = str_replace($array, "", $string);

if(strcmp($string, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

$newStr = str_replace($array, "", $string2);

if(strcmp($string2, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

Little explanation!

  1. Create new variable with $newStr replacing value in array of original string.

  2. Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.

  3. if it is vice versa of 2, i.e, while doing string comparison, both original and new string was not matched, that means, something got replaced, hence value in array exists in string.

How to restore the dump into your running mongodb

mongodump: To dump all the records:

mongodump --db databasename

To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:

mongodump --collection myCollection --db test

This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.


mongorestore: To restore all data to the original database:

1) mongorestore --verbose \path\dump

or restore to a new database:

2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>

Note: Both requires mongod instances.

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

How do I increase the contrast of an image in Python OpenCV

I would like to suggest a method using the LAB color channel. Wikipedia has enough information regarding what the LAB color channel is about.

I have done the following using OpenCV 3.0.0 and python:

import cv2

#-----Reading the image-----------------------------------------------------
img = cv2.imread('Dog.jpg', 1)
cv2.imshow("img",img) 

#-----Converting image to LAB Color model----------------------------------- 
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
cv2.imshow("lab",lab)

#-----Splitting the LAB image to different channels-------------------------
l, a, b = cv2.split(lab)
cv2.imshow('l_channel', l)
cv2.imshow('a_channel', a)
cv2.imshow('b_channel', b)

#-----Applying CLAHE to L-channel-------------------------------------------
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
cl = clahe.apply(l)
cv2.imshow('CLAHE output', cl)

#-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
limg = cv2.merge((cl,a,b))
cv2.imshow('limg', limg)

#-----Converting image from LAB Color model to RGB model--------------------
final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
cv2.imshow('final', final)

#_____END_____#

You can run the code as it is. To know what CLAHE (Contrast Limited Adaptive Histogram Equalization)is about, you can again check Wikipedia.

Can a div have multiple classes (Twitter Bootstrap)

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well. All you have to do is separate each class with a space.

Example below:

<label class="checkbox inline">
   <input type="checkbox" id="inlineCheckbox1" value="option1"> 1
</label>

Increasing the JVM maximum heap size for memory intensive applications

32-bit Java is limited to approximately 1.4 to 1.6 GB.

Oracle 32 bit heap FAQ

Quote

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.

Time complexity of accessing a Python dict

To answer your specific questions:

Q1:
"Am I correct that python dicts suffer from linear access times with such inputs?"

A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)

Q2:
"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"

A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key).

Relative div height

Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...

See this : percentage in height doesn’t work?

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

How do I get a Date without time in Java?

Use LocalDate.now() and convert into Date like below:

Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());

How to make Twitter Bootstrap tooltips have multiple lines?

You can use the html property: http://jsfiddle.net/UBr6c/

My <a href="#" title="This is a<br />test...<br />or not" class="my_tooltip">Tooltip</a> test.

$('.my_tooltip').tooltip({html: true})

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

You are trying to use it as a CSS file, probably by using

<link rel=stylesheet href=ABCD.html>

or

<style>
@import url("ABCD.html");
</style>

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

How to prune local tracking branches that do not exist on remote anymore

I wanted something that would purge all local branches that were tracking a remote branch, on origin, where the remote branch has been deleted (gone). I did not want to delete local branches that were never set up to track a remote branch (i.e.: my local dev branches). Also, I wanted a simple one-liner that just uses git, or other simple CLI tools, rather than writing custom scripts. I ended up using a bit of grep and awk to make this simple command, then added it as an alias in my ~/.gitconfig.

[alias]
  prune-branches = !git remote prune origin && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D

Here is a git config --global ... command for easily adding this as git prune-branches:

git config --global alias.prune-branches '!git remote prune origin && git branch -vv | grep '"'"': gone]'"'"' | awk '"'"'{print $1}'"'"' | xargs -r git branch -d'

NOTE: Use of the -D flag to git branch can be very dangerous. So, in the config command above I use the -d option to git branch rather than -D; I use -D in my actual config. I use -D because I don't want to hear Git complain about unmerged branches, I just want them to go away. You may want this functionality as well. If so, simply use -D instead of -d at the end of that config command.

Error: EACCES: permission denied

This solved my issue straight away - mac Mojave 10.14.6 - PhpStorm.

Unhandled rejection Error: EACCES: permission denied, mkdir '/Users/myname/.npm/_cacache/index-v5/fb/5a'

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config

Original post: https://stackoverflow.com/a/50639828

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Playing HTML5 video on fullscreen in android webview

Tested on Android 9.0 version

None of the answers worked for me . This is the final thing worked

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;


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


        mWebView = (WebView) findViewById(R.id.webView);


        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyChrome());
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

       if (savedInstanceState == null) {
          mWebView.loadUrl("https://www.youtube.com/");
       }

    }


    private class MyChrome extends WebChromeClient {

        private View mCustomView;
        private WebChromeClient.CustomViewCallback mCustomViewCallback;
        protected FrameLayout mFullscreenContainer;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        MyChrome() {}

        public Bitmap getDefaultVideoPoster()
        {
            if (mCustomView == null) {
                return null;
            }
            return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
        }

        public void onHideCustomView()
        {
            ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
            this.mCustomView = null;
            getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
            setRequestedOrientation(this.mOriginalOrientation);
            this.mCustomViewCallback.onCustomViewHidden();
            this.mCustomViewCallback = null;
        }

        public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
        {
            if (this.mCustomView != null)
            {
                onHideCustomView();
                return;
            }
            this.mCustomView = paramView;
            this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            this.mOriginalOrientation = getRequestedOrientation();
            this.mCustomViewCallback = paramCustomViewCallback;
            ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
            getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
}

In AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:configChanges="orientation|screenSize" />

Source Monster Techno

How to prevent colliders from passing through each other?

Collision with fast-moving objects is always a problem. A good way to ensure that you detect all collision is to use Raycasting instead of relying on the physics simulation. This works well for bullets or small objects, but will not produce good results for large objects. http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

Pseudo-codeish (I don't have code-completion here and a poor memory):

void FixedUpdate()
{
    Vector3 direction = new Vector3(transform.position - lastPosition);
    Ray ray = new Ray(lastPosition, direction);
    RaycastHit hit;
    if (Physics.Raycast(ray, hit, direction.magnitude))
    {
        // Do something if hit
    }

    this.lastPosition = transform.position;
}

How do I 'foreach' through a two-dimensional array?

It depends on how you define your multi-dimensional array. Here are two options:

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            // First
            string[,] arr1 = {
                       { "aa", "aaa" },
                       { "bb", "bbb" }
                   };

            // Second
            string[][] arr2 = new[] {
                new[] { "aa", "aaa" },
                new[] { "bb", "bbb" }
            };

            // Iterate through first
            for (int x = 0; x <= arr1.GetUpperBound(0); x++)
                for (int y = 0; y <= arr1.GetUpperBound(1); y++)
                    Console.Write(arr1[x, y] + "; ");

            Console.WriteLine(Environment.NewLine);

            // Iterate through second second
            foreach (string[] entry in arr2)
                foreach (string element in entry)
                    Console.Write(element + "; ");

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Press any key to finish");
            Console.ReadKey();
        }
    }
}

How do I get the name of a Ruby class?

If you want to get a class name from inside a class method, class.name or self.class.name won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

module Foo
  class Bar
    def self.say_name
      puts "I'm a #{name}!"
    end
  end
end

Foo::Bar.say_name

output:

I'm a Foo::Bar!

Multiple submit buttons in the same form calling different Servlets

There are several ways to achieve this.

Probably the easiest would be to use JavaScript to change the form's action.

<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">

But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).


Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.

<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
    <input type="submit"value="SecondServlet">
</form>

Note that a form would on submit only send the input data contained in the very same form, not in the other form.


Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name):

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="action" value="FirstServlet">
    <input type="submit" name="action" value="SecondServlet">
</form>

with the following in MainServlet

String action = request.getParameter("action");

if ("FirstServlet".equals(action)) {
    // Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
    // Invoke SecondServlet's job here.
}

This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?


A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="first" value="FirstServlet">
    <input type="submit" name="second" value="SecondServlet">
</form>

with the following in MainServlet

if (request.getParameter("first") != null) {
    // Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
    // Invoke SecondServlet's job here.
}

Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.

<h:form>
    Last Name: <h:inputText value="#{bean.lastName}" size="20" />
    <br/><br/>
    <h:commandButton value="First" action="#{bean.first}" />
    <h:commandButton value="Second" action="#{bean.Second}" />
</h:form>

with just the following javabean instead of a servlet

@ManagedBean
@RequestScoped
public class Bean {

    private String lastName; // +getter+setter

    public void first() {
        // Invoke original FirstServlet's job here.
    }

    public void second() {
        // Invoke original SecondServlet's job here.
    }

}

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

Insert HTML with React Variable Statements (JSX)

You don't need any special library or "dangerous" attribute. You can just use React Refs to manipulate the DOM:

class MyComponent extends React.Component {
    
    constructor(props) {
        
        super(props);       
        this.divRef = React.createRef();
        this.myHTML = "<p>Hello World!</p>"
    }
    
    componentDidMount() {
        
        this.divRef.current.innerHTML = this.myHTML;
    }
    
    render() {
        
        return (
            
            <div ref={this.divRef}></div>
        );
    }
}

A working sample can be found here:

https://codepen.io/bemipefe/pen/mdEjaMK

I keep getting "Uncaught SyntaxError: Unexpected token o"

I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.

I was accessing the iframe data like this:

$('#load-file-iframe').contents().text()

which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to

$('#load-file-iframe').contents().find('body').text()

once I noticed some garbage in the HTML response.

Long story short check your raw HTML response data and you might turn something up.

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

How to order citations by appearance using BibTeX?

I use natbib in combination with bibliographystyle{apa}. Eg:

\begin{document}

The body of the document goes here...

\newpage

\bibliography{bibliography} % Or whatever you decided to call your .bib file 

\usepackage[round, comma, sort&compress ]{natbib} 

bibliographystyle{apa}
\end{document}

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

One way I found that helps with this is to use \include{file_with_tex_figure_commands}

(not input)

Java: Getting a substring from a string starting after a particular character

String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));

What is the default boolean value in C#?

The default value is indeed false.

However you can't use a local variable is it's not been assigned first.

You can use the default keyword to verify:

bool foo = default(bool);
if (!foo) { Console.WriteLine("Default is false"); }

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

Calculate number of hours between 2 dates in PHP

$day1 = "2006-04-12 12:30:00"
$day1 = strtotime($day1);
$day2 = "2006-04-14 11:30:00"
$day2 = strtotime($day2);

$diffHours = round(($day2 - $day1) / 3600);

I guess strtotime() function accept this date format.

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

How to show matplotlib plots in python

Save the plot as png

plt.savefig("temp.png")

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

How to make an unaware datetime timezone aware in python

This codifies @Sérgio and @unutbu's answers. It will "just work" with either a pytz.timezone object or an IANA Time Zone string.

def make_tz_aware(dt, tz='UTC', is_dst=None):
    """Add timezone information to a datetime object, only if it is naive."""
    tz = dt.tzinfo or tz
    try:
        tz = pytz.timezone(tz)
    except AttributeError:
        pass
    return tz.localize(dt, is_dst=is_dst) 

This seems like what datetime.localize() (or .inform() or .awarify()) should do, accept both strings and timezone objects for the tz argument and default to UTC if no time zone is specified.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

How can I add a line to a file in a shell script?

Add a given line at the beginning of a file in two commands:

cat <(echo "blablabla") input_file.txt > tmp_file.txt
mv tmp_file.txt input_file.txt

Get filename and path from URI from mediastore

Try This

Still, if you are getting the problem to get the real path, you can try my answers. Above answers didn't help me.

Explanation:- This method gets the URI and then check the API level of your Android device after that according to API level it will generate the Real path. Code for generating real path method is different according to API levels.

  1. method to get the Real path from URI

    @SuppressLint("ObsoleteSdkInt")
    public String getPathFromURI(Uri uri){
        String realPath="";
    // SDK < API11
        if (Build.VERSION.SDK_INT < 11) {
            String[] proj = { MediaStore.Images.Media.DATA };
            @SuppressLint("Recycle") Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
            int column_index = 0;
            String result="";
            if (cursor != null) {
                column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                realPath=cursor.getString(column_index);
            }
        }
        // SDK >= 11 && SDK < 19
        else if (Build.VERSION.SDK_INT < 19){
            String[] proj = { MediaStore.Images.Media.DATA };
            CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if(cursor != null){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                realPath = cursor.getString(column_index);
            }
        }
        // SDK > 19 (Android 4.4)
        else{
            String wholeID = DocumentsContract.getDocumentId(uri);
            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];
            String[] column = { MediaStore.Images.Media.DATA };
            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";
            Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
            int columnIndex = 0;
            if (cursor != null) {
                columnIndex = cursor.getColumnIndex(column[0]);
                if (cursor.moveToFirst()) {
                    realPath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
        }
        return realPath;
     }
    
  2. Use this method like this

    Log.e(TAG, "getRealPathFromURI: "+getPathFromURI(your_selected_uri) );
    

Output:-

04-06 12:39:46.993 6138-6138/com.app.qtm E/tag: getRealPathFromURI: /storage/emulated/0/Video/avengers_infinity_war_4k_8k-7680x4320.jpg

Changing the child element's CSS when the parent is hovered

Why not just use CSS?

.parent:hover .child, .parent.hover .child { display: block; }

and then add JS for IE6 (inside a conditional comment for instance) which doesn't support :hover properly:

jQuery('.parent').hover(function () {
    jQuery(this).addClass('hover');
}, function () {
    jQuery(this).removeClass('hover');
});

Here's a quick example: Fiddle

Angular: conditional class with *ngClass

[ngClass]=... instead of *ngClass.

* is only for the shorthand syntax for structural directives where you can for example use

<div *ngFor="let item of items">{{item}}</div>

instead of the longer equivalent version

<template ngFor let-item [ngForOf]="items">
  <div>{{item}}</div>
</template>

See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

See also https://angular.io/docs/ts/latest/guide/template-syntax.html

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>

How to disable registration new users in Laravel

In routes.php, just add the following:

if (!env('ALLOW_REGISTRATION', false)) {
    Route::any('/register', function() {
        abort(403);
    });
}

Then you can selectively control whether registration is allowed or not in you .env file.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Are loops really faster in reverse?

This guy compared a lot of loops in javascript, in a lot of browsers. He also has a test suite so you can run them yourself.

In all cases (unless I missed one in my read) the fastest loop was:

var i = arr.length; //or 10
while(i--)
{
  //...
}

Run Batch File On Start-up

To start the batch file at the start of your system, you can also use a registry key.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Here you can create a string. As name you can choose anything and the data is the full path to your file.

There is also the registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

to run something at only the next start of your system.

Understanding generators in Python

I believe the first appearance of iterators and generators were in the Icon programming language, about 20 years ago.

You may enjoy the Icon overview, which lets you wrap your head around them without concentrating on the syntax (since Icon is a language you probably don't know, and Griswold was explaining the benefits of his language to people coming from other languages).

After reading just a few paragraphs there, the utility of generators and iterators might become more apparent.

Styling twitter bootstrap buttons

For Bootstrap for Sass override it's

.btn-default {

    @include button-variant($color, $background, $border);

}

You can see the source for it here: https://github.com/twbs/bootstrap-sass/blob/a5f5954268779ce0faf7607b3c35191a8d0fdfe6/assets/stylesheets/bootstrap/mixins/_buttons.scss#L6

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

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

This is definitely a syntax issue, when it happened to me I discovered I typed

module.export = Component; instead of module.exports = Component;

How to change line width in ggplot?

If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.

library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)


df = gather(df,A,B,C,key="Model",value="Y")


ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") ) 

split python source code into multiple files?

I am researching module usage in python just now and thought I would answer the question Markus asks in the comments above ("How to import variables when they are embedded in modules?") from two perspectives:

  1. variable/function, and
  2. class property/method.

Here is how I would rewrite the main program f1.py to demonstrate variable reuse for Markus:

import f2
myStorage = f2.useMyVars(0) # initialze class and properties
for i in range(0,10):
    print "Hello, "
    f2.print_world()
    myStorage.setMyVar(i)
    f2.inc_gMyVar()
print "Display class property myVar:", myStorage.getMyVar()
print "Display global variable gMyVar:", f2.get_gMyVar()

Here is how I would rewrite the reusable module f2.py:

# Module: f2.py
# Example 1: functions to store and retrieve global variables
gMyVar = 0
def print_world():
    print "World!"
def get_gMyVar():
    return gMyVar # no need for global statement 
def inc_gMyVar():
    global gMyVar
    gMyVar += 1  

# Example 2: class methods to store and retrieve properties
class useMyVars(object):
    def __init__(self, myVar):
        self.myVar = myVar
    def getMyVar(self):
        return self.myVar
    def setMyVar(self, myVar):
        self.myVar = myVar
    def print_helloWorld(self):
        print "Hello, World!"

When f1.py is executed here is what the output would look like:

%run "f1.py"
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Hello, 
World!
Display class property myVar: 9
Display global variable gMyVar: 10

I think the point to Markus would be:

  • To reuse a module's code more than once, put your module's code into functions or classes,
  • To reuse variables stored as properties in modules, initialize properties within a class and add "getter" and "setter" methods so variables do not have to be copied into the main program,
  • To reuse variables stored in modules, initialize the variables and use getter and setter functions. The setter functions would declare the variables as global.

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

How to push a single file in a subdirectory to Github (not master)

When you do a push, git only takes the changes that you have committed.

Remember when you do a git status it shows you the files you changed since the last push?

Once you commit those changes and do a push they are the only files that get pushed so you don't have to worry about thinking that the entire master gets pushed because in reality it does not.

How to push a single file:

git commit yourfile.js
git status
git push origin master

C++ terminate called without an active exception

Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.

Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:

  • The runtime exits the scope, only after that thread finishes executing. This is achieved by joining with that thread. Note the language, it is the outer scope that joins with that thread.
  • The runtime leaves the thread to run on its own. So, the program will exit the scope, whether this thread finished executing or not. This thread executes and exits by itself. This is achieved by detaching the thread. This could lead to issues, for example, if the thread refers to variables in that outer scope.

Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.

Prevent a webpage from navigating away using JavaScript

The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Batch not-equal (inequality) operator

I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)

I pulled this from the example code in your link:

IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.

!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.

The suggestion to use if not "asdf" == "fdas" is definitely the way to go.

Convert a positive number to negative in C#

How about

myInt = myInt * -1

how to get the child node in div using javascript

var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;

Plotting a fast Fourier transform in Python

Just as a complement to the answers already given, I would like to point out that often it is important to play with the size of the bins for the FFT. It would make sense to test a bunch of values and pick the one that makes more sense to your application. Often, it is in the same magnitude of the number of samples. This was as assumed by most of the answers given, and produces great and reasonable results. In case one wants to explore that, here is my code version:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

fig = plt.figure(figsize=[14,4])
N = 600           # Number of samplepoints
Fs = 800.0
T = 1.0 / Fs      # N_samps*T (#samples x sample period) is the sample spacing.
N_fft = 80        # Number of bins (chooses granularity)
x = np.linspace(0, N*T, N)     # the interval
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)   # the signal

# removing the mean of the signal
mean_removed = np.ones_like(y)*np.mean(y)
y = y - mean_removed

# Compute the fft.
yf = scipy.fftpack.fft(y,n=N_fft)
xf = np.arange(0,Fs,Fs/N_fft)

##### Plot the fft #####
ax = plt.subplot(121)
pt, = ax.plot(xf,np.abs(yf), lw=2.0, c='b')
p = plt.Rectangle((Fs/2, 0), Fs/2, ax.get_ylim()[1], facecolor="grey", fill=True, alpha=0.75, hatch="/", zorder=3)
ax.add_patch(p)
ax.set_xlim((ax.get_xlim()[0],Fs))
ax.set_title('FFT', fontsize= 16, fontweight="bold")
ax.set_ylabel('FFT magnitude (power)')
ax.set_xlabel('Frequency (Hz)')
plt.legend((p,), ('mirrowed',))
ax.grid()

##### Close up on the graph of fft#######
# This is the same histogram above, but truncated at the max frequence + an offset. 
offset = 1    # just to help the visualization. Nothing important.
ax2 = fig.add_subplot(122)
ax2.plot(xf,np.abs(yf), lw=2.0, c='b')
ax2.set_xticks(xf)
ax2.set_xlim(-1,int(Fs/6)+offset)
ax2.set_title('FFT close-up', fontsize= 16, fontweight="bold")
ax2.set_ylabel('FFT magnitude (power) - log')
ax2.set_xlabel('Frequency (Hz)')
ax2.hold(True)
ax2.grid()

plt.yscale('log')

the output plots: enter image description here

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

for i in *.xls ; do 
  [[ -f "$i" ]] || continue
  xls2csv "$i" "${i%.xls}.csv"
done

The first line in the do checks if the "matching" file really exists, because in case nothing matches in your for, the do will be executed with "*.xls" as $i. This could be horrible for your xls2csv.

"static const" vs "#define" vs "enum"

In C #define is much more popular. You can use those values for declaring array sizes for example:

#define MAXLEN 5

void foo(void) {
   int bar[MAXLEN];
}

ANSI C doesn't allow you to use static consts in this context as far as I know. In C++ you should avoid macros in these cases. You can write

const int maxlen = 5;

void foo() {
   int bar[maxlen];
}

and even leave out static because internal linkage is implied by const already [in C++ only].

Initializing a static std::map<int, int> in C++

For example:

const std::map<LogLevel, const char*> g_log_levels_dsc =
{
    { LogLevel::Disabled, "[---]" },
    { LogLevel::Info,     "[inf]" },
    { LogLevel::Warning,  "[wrn]" },
    { LogLevel::Error,    "[err]" },
    { LogLevel::Debug,    "[dbg]" }
};

If map is a data member of a class, you can initialize it directly in header by the following way (since C++17):

// Example

template<>
class StringConverter<CacheMode> final
{
public:
    static auto convert(CacheMode mode) -> const std::string&
    {
        // validate...
        return s_modes.at(mode);
    }

private:
    static inline const std::map<CacheMode, std::string> s_modes =
        {
            { CacheMode::All, "All" },
            { CacheMode::Selective, "Selective" },
            { CacheMode::None, "None" }
            // etc
        };
}; 

Min/Max-value validators in asp.net mvc

jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

public class MaxAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int maxValue;

    public MaxAttribute(int maxValue)
    {
        this.maxValue = maxValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = ErrorMessageString, maxValue;

        rule.ValidationType = "max";
        rule.ValidationParameters.Add("max", maxValue);
        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return (int)value <= maxValue;
    }
}

Adapter:

$.validator.unobtrusive.adapters.add(
   'max',
   ['max'],
   function (options) {
       options.rules['max'] = parseInt(options.params['max'], 10);
       options.messages['max'] = options.message;
   });

Min attribute would be very similar.

MongoDB: How to update multiple documents with a single command?

To Update Entire Collection,

db.getCollection('collection_name').update({},
{$set: {"field1" : "value1", "field2" : "value2", "field3" : "value3"}},
{multi: true })

What is the best comment in source code you have ever encountered?

Just added this one today:

// Hardcoded this for time sake ... will make andrew fix later :)

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I have the same issue, and solved by change the '+' to a exact number, like compile "com.android.support:appcompat-v7:21.0.+" to compile "com.android.support:appcompat-v7:21.0.0".

This works for me. :)

Open URL in Java to get the content

Are you sure using the java.net.URL class? Check your import statements.

How to debug heap corruption errors?

I had a similar problem - and it popped up quite randomly. Perhaps something was corrupt in the build files, but I ended up fixing it by cleaning the project first then rebuilding.

So in addition to the other responses given:

What sort of things can cause these errors? Something corrupt in the build file.

How do I debug them? Cleaning the project and rebuilding. If it's fixed, this was likely the problem.

React fetch data in server before render

What you're looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

How to reset a form using jQuery with .reset() method

By using jquery function .closest(element) and .find(...).

Getting the parent element and looking for the child.

Finally, do the function needed.

$("#form").closest('form').find("input[type=text], textarea").val("");

git: patch does not apply

Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:

git apply --ignore-space-change --ignore-whitespace mychanges.patch

This solved my problem.

I forgot the password I entered during postgres installation

The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).

This file should contain lines of the following format:

hostname:port:database:username:password

(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.

On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored. On Microsoft Windows, it is assumed that the file is stored in a directory that is secure, so no special permissions check is made.

Call javascript from MVC controller action

For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.

First, create a string property on your Model.

public class MyModel 
{
    public string JavascriptToRun { get; set;}
}

Now, bind to your new model property in the Javascript of your view:

<script type="text/javascript">
     @Model.JavascriptToRun
</script>

Now, also in your view, create a Javascript function that does whatever you need to do:

<script type="text/javascript">
     @Model.JavascriptToRun

     function ShowErrorPopup() {
          alert('Sorry, we could not process your order.');
     }

</script>

Finally, in your controller action, you need to call this new Javascript function:

[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
    // Do something useful
    ...

    if (success == false)
    {
        model.JavascriptToRun= "ShowErrorPopup()";
        return View(model);
    }
    else
        return RedirectToAction("Success");
}

How to display div after click the button in Javascript?

HTML Code:

<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />

Javascript:

function showDiv() {
   document.getElementById('welcomeDiv').style.display = "block";
}

See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

How to vertically align text with icon font?

to center vertically and horizontally use this:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);

Using getopts to process long and short command line options

Th built-in OS X (BSD) getopt does not support long options, but the GNU version does: brew install gnu-getopt. Then, something similar to: cp /usr/local/Cellar/gnu-getopt/1.1.6/bin/getopt /usr/local/bin/gnu-getopt.

The best way to remove duplicate values from NSMutableArray in Objective-C?

Your NSSet approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet to begin with?

I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:

NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];

If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:

NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
    if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [mutableArray removeObjectAtIndex:index];
    }
    index--;
}
[copy release];

Get characters after last / in url

$str = basename($url);

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.

Project -> Properties -> Java Compiler

Enable project specific settings.

Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.

Now, it should be fine.

How can I show an element that has display: none in a CSS rule?

Because setting the div's display style property to "" doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.

You need to set it to something that has a value:

document.getElementById('mybox').style.display = "block";

What you're doing would work if you were replacing an inline style on the div, like this:

<div id="myBox" style="display: none;"></div>

document.getElementById('mybox').style.display = "";

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Differences in boolean operators: & vs && and | vs ||

While the basic difference is that & is used for bitwise operations mostly on long, int or byte where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&.

The difference is more noticeable in some scenarios:

  1. Evaluating some of the expressions is time consuming
  2. Evaluating one of the expression can be done only if the previous one was true
  3. The expressions have some side-effect (intended or not)

First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.

For second point, see this example:

if ((a != null) & (a.isEmpty()))

This fails for null, as evaluating the second expression produces a NullPointerException. Logical operator && is lazy, if left operand is false, the result is false no matter what right operand is.

Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:

if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))

This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&, it works as intended and it stops after first failure.

As for a || b, it is equivalent of !(!a && !b), it stops if a is true, no more explanation needed.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

Since you now specified you want to add to it, what you want isn't a simple IEnumerable<T> but at least an ICollection<T>. I recommend simply using a List<T> like this:

List<object> myList=new List<object>();
myList.Add(1);
myList.Add(2);
myList.Add(3);

You can use myList everywhere an IEnumerable<object> is expected, since List<object> implements IEnumerable<object>.

(old answer before clarification)

You can't create an instance of IEnumerable<T> since it's a normal interface(It's sometimes possible to specify a default implementation, but that's usually used only with COM).

So what you really want is instantiate a class that implements the interface IEnumerable<T>. The behavior varies depending on which class you choose.

For an empty sequence use:

IEnumerable<object> e0=Enumerable.Empty<object>();

For an non empty enumerable you can use some collection that implements IEnumerable<T>. Common choices are the array T[], List<T> or if you want immutability ReadOnlyCollection<T>.

IEnumerable<object> e1=new object[]{1,2,3};
IEnumerable<object> e2=new List<object>(){1,2,3};
IEnumerable<object> e3=new ReadOnlyCollection(new object[]{1,2,3});

Another common way to implement IEnumerable<T> is the iterator feature introduced in C# 3:

IEnumerable<object> MyIterator()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

IEnumerable<object> e4=MyIterator();

How to replicate vector in c?

They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.

Something like this:

typedef struct vec
{
    unsigned char* _mem;
    unsigned long _elems;
    unsigned long _elemsize;
    unsigned long _capelems;
    unsigned long _reserve;
};

vec* vec_new(unsigned long elemsize)
{
    vec* pvec = (vec*)malloc(sizeof(vec));
    pvec->_reserve = 10;
    pvec->_capelems = pvec->_reserve;
    pvec->_elemsize = elemsize;
    pvec->_elems = 0;
    pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
    return pvec;
}

void vec_delete(vec* pvec)
{
    free(pvec->_mem);
    free(pvec);
}

void vec_grow(vec* pvec)
{
    unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
    memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
    free(pvec->_mem);
    pvec->_mem = mem;
    pvec->_capelems += pvec->_reserve;
}

void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
    assert(elemsize == pvec->_elemsize);
    if (pvec->_elems == pvec->_capelems) {
        vec_grow(pvec);
    }
    memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
    pvec->_elems++;    
}

unsigned long vec_length(vec* pvec)
{
    return pvec->_elems;
}

void* vec_get(vec* pvec, unsigned long index)
{
    assert(index < pvec->_elems);
    return (void*)(pvec->_mem + (index * pvec->_elemsize));
}

void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
    memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}

void playwithvec()
{
    vec* pvec = vec_new(sizeof(int));

    for (int val = 0; val < 1000; val += 10) {
        vec_push_back(pvec, &val, sizeof(val));
    }

    for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
        int val;
        vec_copy_item(pvec, &val, index);
        printf("vec(%d) = %d\n", index, val);
    }

    vec_delete(pvec);
}

Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.

In Android, how do I set margins in dp programmatically?

As today, the best is probably to use Paris, a library provided by AirBnB.

Styles can then be applied like this:

Paris.style(myView).apply(R.style.MyStyle);

it also support custom view (if you extend a view) using annotations:

@Styleable and @Style

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

How different is Scrum practice from Agile Practice?

As mentioned Agile is a set of principles about how a methodology should be implemented to achieve the benefits of embracing change, close co-operation etc. These principles address some of the project management issues found in studies such as the Chaos Report by the Standish group.

Agile methodologies are created by the development and supporting teams to meet the principles. The methodology is made to fit the business and changed as appropriate.

SCRUM is a fixed set of processes to implement an incremental development methodology. Since the processes are fixed and not catered to the teams it cannot really be considered agile in the original sense of focus on individuals rather than processes.

Remove style attribute from HTML tags

I use this:

function strip_word_html($text, $allowed_tags = '<a><ul><li><b><i><sup><sub><em><strong><u><br><br/><br /><p><h2><h3><h4><h5><h6>')
{
    mb_regex_encoding('UTF-8');
    //replace MS special characters first
    $search = array('/&lsquo;/u', '/&rsquo;/u', '/&ldquo;/u', '/&rdquo;/u', '/&mdash;/u');
    $replace = array('\'', '\'', '"', '"', '-');
    $text = preg_replace($search, $replace, $text);
    //make sure _all_ html entities are converted to the plain ascii equivalents - it appears
    //in some MS headers, some html entities are encoded and some aren't
    //$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    //try to strip out any C style comments first, since these, embedded in html comments, seem to
    //prevent strip_tags from removing html comments (MS Word introduced combination)
    if(mb_stripos($text, '/*') !== FALSE){
        $text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
    }
    //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
    //'<1' becomes '< 1'(note: somewhat application specific)
    $text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
    $text = strip_tags($text, $allowed_tags);
    //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
    $text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
    //strip out inline css and simplify style tags
    $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
    $replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
    $text = preg_replace($search, $replace, $text);
    //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
    //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
    //some MS Style Definitions - this last bit gets rid of any leftover comments */
    $num_matches = preg_match_all("/\<!--/u", $text, $matches);
    if($num_matches){
        $text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
    }
    $text = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $text);
return $text;
}

Eclipse error: "The import XXX cannot be resolved"

Check If Your POM file is Updated with same Version in all Modules.

Easy way to test an LDAP User's Credentials

ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>, where binddn is the DN of the person whose credentials you are authenticating.

On success (i.e., valid credentials), you get Result: Success (0). On failure, you get ldap_bind: Invalid credentials (49).

App not setup: This app is still in development mode

Go to Settings->Basic, on top you will find a Switch button which will say App is in development mode.

enter image description here

Click on in development switch button, it will ask you to make app live, and after providing all necessary things, it will become live.

enter image description here

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

How to get milliseconds from LocalDateTime in Java 8

Date and time as String to Long (millis):

String dateTimeString = "2020-12-12T14:34:18.000Z";

DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);

LocalDateTime localDateTime = LocalDateTime
        .parse(dateTimeString, formatter);

Long dateTimeMillis = localDateTime
        .atZone(ZoneId.systemDefault())
        .toInstant()
        .toEpochMilli();

What is the difference between JVM, JDK, JRE & OpenJDK?

JDK: The complete package which you need to write and run java code

OpenJDK: An independent implementation of JDK for making it much better

JVM: Converts Java code into bytecode and provides the specifications which tells how should a Java code be compiled, loaded, verified, checked for errors and executed.

JRE: Implementation of the JVM with which some Java libraries are used to Run the program

Tomcat request timeout

This article talks about setting the timeouts on the server level. http://www.coderanch.com/t/364207/Servlets/java/Servlet-Timeout-two-ways

What is causing the application to go into infinite loop? If you are opening connections to other resources, you might want to put timeouts on those connections and sending appropriate response when those time out occurs.