Programs & Examples On #Decorator chaining

How to check a channel is closed or not without reading it?

it's easier to check first if the channel has elements, that would ensure the channel is alive.

func isChanClosed(ch chan interface{}) bool {
    if len(ch) == 0 {
        select {
        case _, ok := <-ch:
            return !ok
        }
    }
    return false 
}

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
    }
</script>

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

What is the correct way to restore a deleted file from SVN?

With Tortoise SVN:

If you haven't committed your changes yet, you can do a revert on the parent folder where you deleted the file or directory.

If you have already committed the deleted file, then you can use the repository browser, change to the revision where the file still existed and then use the command Copy to... from the context menu. Enter the path to your working copy as the target and the deleted file will be copied from the repository to your working copy.

Plot multiple columns on the same graph in R

The easiest is to convert your data to a "tall" format.

s <- 
"A       B        C       G       Xax
0.451   0.333   0.034   0.173   0.22        
0.491   0.270   0.033   0.207   0.34    
0.389   0.249   0.084   0.271   0.54    
0.425   0.819   0.077   0.281   0.34
0.457   0.429   0.053   0.386   0.53    
0.436   0.524   0.049   0.249   0.12    
0.423   0.270   0.093   0.279   0.61    
0.463   0.315   0.019   0.204   0.23
"
d <- read.delim(textConnection(s), sep="")

library(ggplot2)
library(reshape2)
d <- melt(d, id.vars="Xax")

# Everything on the same plot
ggplot(d, aes(Xax,value, col=variable)) + 
  geom_point() + 
  stat_smooth() 

# Separate plots
ggplot(d, aes(Xax,value)) + 
  geom_point() + 
  stat_smooth() +
  facet_wrap(~variable)

PHP cURL HTTP CODE return 0

check the curl_error after the curl_getinfo to find out the hidden errors.

if(curl_errno($ch)){   
    echo 'Curl error: ' . curl_error($ch);
}

How can I pass a file argument to my bash script using a Terminal command in Linux?

Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:

#!/bin/bash
ext_program="$1"
shift
"$ext_program" "$@"

The shift will remove the first argument, renaming the rest ($2 becomes $1, and so on).$@` refers to the arguments, as an array of words (it must be quoted!).

If you must have your --file syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replace ext_program="$1" with whatever parsing of $1 you need to do, perhaps using getopt or getopts.

If you want to roll your own, for just the one specific case, you could do something like this:

if [ "$#" -gt 0 -a "${1:0:6}" == "--file" ]; then
    ext_program="${1:7}"
else
    ext_program="default program"
fi

How to assign a NULL value to a pointer in python?

left = None

left is None #evaluates to True

SQL use CASE statement in WHERE IN clause

maybe you can try this way

SELECT * FROM Product P WHERE (CASE WHEN @Status = 'published' THEN (CASE WHEN P.Status IN (1, 3) THEN 'TRUE' ELSE FALSE END) WHEN @Status = 'standby' THEN (CASE WHEN P.Status IN (2, 5, 9, 6) THEN 'TRUE' ELSE 'FALSE' END) WHEN @Status = 'deleted' THEN (CASE WHEN P.Status IN (4, 5, 8, 10) THEN 'TRUE' ELSE 'FALSE' END) ELSE (CASE WHEN P.Status IN (1, 3) THEN 'TRUE' ELSE 'FALSE' END) END) = 'TRUE'

In this way if @Status = 'published', the query will check if P.Status is among 1 or 3, it will return TRUE else 'FALSE'. This will be matched with TRUE at the end

Hope it helps.

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

What is String pool in Java?

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

The 'Access-Control-Allow-Origin' header contains multiple values

This happens when you have Cors option configured at multiple locations. In my case I had it at the controller level as well as in the Startup.Auth.cs/ConfigureAuth.

My understanding is if you want it application wide then just configure it under Startup.Auth.cs/ConfigureAuth like this...You will need reference to Microsoft.Owin.Cors

public void ConfigureAuth(IAppBuilder app)
        {
          app.UseCors(CorsOptions.AllowAll);

If you rather keep it at the controller level then you may just insert at the Controller level.

[EnableCors("http://localhost:24589", "*", "*")]
    public class ProductsController : ApiController
    {
        ProductRepository _prodRepo;

The difference between Classes, Objects, and Instances

The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.

Here an example of a class representing a Car:

public class Car {

    int currentSpeed;
    String name;

    public void accelerate() {  
    }

    public void park() {
    }

    public void printCurrentSpeed() {
    }
}

You can create instances of the object Car like this:

Car audi = new Car();
Car toyota = new Car();

I have taken the example from this tutorial

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

For other readers, the error can come from the fact that there is no brackets wrapping the async function:

Considering the async function initData

  async function initData() {
  }

This code will lead to your error:

  useEffect(() => initData(), []);

But this one, won't:

  useEffect(() => { initData(); }, []);

(Notice the brackets around initData()

:touch CSS pseudo-class or something similar?

I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

How to get the last five characters of a string using Substring() in C#?

e.g.

string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);

This return "substring"

C# substring sample source

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

How can I avoid Java code in JSP files, using JSP 2?

  1. Make your values and parameters inside your servlet classes
  2. Fetch those values and parameters within your JSP using JSTL/Taglib

The good thing about this approach is that your code is also HTML like code!

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

This compilation unit is not on the build path of a Java project

If your project is imported as an existing maven project then --> Just right click on project and do maven update. It resolved my similar issue.

How to access static resources when mapping a global front controller servlet on /*

What you do is add a welcome file in your web.xml

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

And then add this to your servlet mappings so that when someone goes to the root of your application, they get sent to index.html internally and then the mapping will internally send them to the servlet you map it to

<servlet-mapping>
    <servlet-name>MainActions</servlet-name>
    <url-pattern>/main</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>MainActions</servlet-name>
    <url-pattern>/index.html</url-pattern>
</servlet-mapping>

End result: You visit /Application, but you are presented with /Application/MainActions servlet without disrupting any other root requests.

Get it? So your app still sits at a sub url, but automatically gets presented when the user goes to the root of your site. This allows you to have the /images/bob.img still go to the regular place, but '/' is your app.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

For Rect-Native developers. I encounter this error while renderingItem in FlatList. I had two Text components. I was using them like below

renderItem = { ({item}) => 
     <Text style = {styles.item}>{item.key}</Text>
     <Text style = {styles.item}>{item.user}</Text>
}

But after I put these tow Inside View Components it worked for me.

renderItem = { ({item}) => 
   <View style={styles.flatview}>
      <Text style = {styles.item}>{item.key}</Text>
      <Text style = {styles.item}>{item.user}</Text>
   </View>
 }

You might be using other components but putting them into View may be worked for you.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.

var mockFileBrowser = new Mock<FileBrowser>();

instead of

var mockFileBrowser = new Mock<IFileBrowser>();

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Passing multiple parameters to pool.map() function in Python

You can use functools.partial for this (as you suspected):

from functools import partial

def target(lock, iterable_item):
    for item in iterable_item:
        # Do cool stuff
        if (... some condition here ...):
            lock.acquire()
            # Write to stdout or logfile, etc.
            lock.release()

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    l = multiprocessing.Lock()
    func = partial(target, l)
    pool.map(func, iterable)
    pool.close()
    pool.join()

Example:

def f(a, b, c):
    print("{} {} {}".format(a, b, c))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    a = "hi"
    b = "there"
    func = partial(f, a, b)
    pool.map(func, iterable)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()

Output:

hi there 1
hi there 2
hi there 3
hi there 4
hi there 5

Make a UIButton programmatically in Swift

Swift 4.2 - XCode 10.1

Using a closure

let button: UIButton = {
  let button = UIButton(type: .system)
  button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
  ...
  return button
}()

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

You need to do two additional things after following the link that you have mentioned in your post:

One have to map the changed login cridentials in phpmyadmin's config.inc.php

and second, you need to restart your web and mysql servers..

php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php and in that file put your current mysql password at line

$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here

Why I got " cannot be resolved to a type" error?

for some reason, my.demo.service has the same level as src/ in eclise project explorer view. After I move my.demo.service under src/, it is fine. Seems I should not create new package in "Project Explorer" view in Eclipse...

But thank you for your response:)

How to check if internet connection is present in Java?

1) Figure out where your application needs to be connecting to.

2) Set up a worker process to check InetAddress.isReachable to monitor the connection to that address.

Delete column from pandas DataFrame

A nice addition is the ability to drop columns only if they exist. This way you can cover more use cases, and it will only drop the existing columns from the labels passed to it:

Simply add errors='ignore', for example.:

df.drop(['col_name_1', 'col_name_2', ..., 'col_name_N'], inplace=True, axis=1, errors='ignore')
  • This is new from pandas 0.16.1 onward. Documentation is here.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I had same problem and despite having jstl

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

I had to add 'standard' as well:

<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

Also, as mentioned in previous post:

How to read data when some numbers contain commas as thousand separator?

We can also use readr::parse_number, the columns must be characters though. If we want to apply it for multiple columns we can loop through columns using lapply

df[2:3] <- lapply(df[2:3], readr::parse_number)
df

#  a        b        c
#1 a    12234       12
#2 b      123  1234123
#3 c     1234     1234
#4 d 13456234    15342
#5 e    12312 12334512

Or use mutate_at from dplyr to apply it to specific variables.

library(dplyr)
df %>% mutate_at(2:3, readr::parse_number)
#Or
df %>% mutate_at(vars(b:c), readr::parse_number)

data

df <- data.frame(a = letters[1:5], 
                 b = c("12,234", "123", "1,234", "13,456,234", "123,12"),
                 c = c("12", "1,234,123","1234", "15,342", "123,345,12"), 
                 stringsAsFactors = FALSE)

Shortest way to print current year in a website

You've asked for a JavaScript solution, so here's the shortest I can get it:

<script>document.write(new Date().getFullYear())</script>

That will work in all browsers I've run across.

How I got there:

  • You can just call getFullYear directly on the newly-created Date, no need for a variable. new Date().getFullYear() may look a bit odd, but it's reliable: the new Date() part is done first, then the .getFullYear().
  • You can drop the type, because JavaScript is the default; this is even documented as part of the HTML5 specification, which is likely in this case to be writing up what browsers already do.
  • You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally despise and rail against, but in this specific use case it should be safe enough.

It's important to note that this only works on browsers where JavaScript is enabled. Ideally, this would be better handled as an offline batch job (sed script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets. (Now I've gone and tempted fate.)


However, unless you're using a server that can only provide static files, you're probably better off doing this on the server with a templating engine and using caching headers to allow the resulting page to be cached until the date needs to change. That way, you don't require JavaScript on the client. Using a non-defer/async script tag in the content also briefly delays the parsing and presentation of the page (for exactly this reason: because the code in the script might use document.write to output HTML).

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

What is the correct way of reading from a TCP socket in C/C++?

If you actually create the buffer as per dirks suggestion, then:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE);

may completely fill the buffer, possibly overwriting the terminating zero character which you depend on when extracting to a stringstream. You need:

  int readResult = read(socketFileDescriptor, buffer, BUFFER_SIZE - 1 );

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error

UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates

It works:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phon','phon','phone','phone1','phone','phone1','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

it doesn't work:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phone','phone','phone','phone','phone','phone','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

source: https://stackoverflow.com/a/37021196/6088984

How to upgrade Git to latest version on macOS?

I prefer not to alter the path hierarchy, but instead deal with git specifically...knowing that I'm never going to use old git to do what new git will now manage. This is a brute force solution.

NOTE: I installed XCode on Yosemite (10.10.2) clean first.

I then installed from the binary available on git-scm.com.

$ which git
/usr/bin/git
$ cd /usr/bin
$ sudo ln -sf /usr/local/git/bin/git
$ sudo ln -sf /usr/local/git/bin/git-credential-osxkeychain
$ sudo ln -sf /usr/local/git/bin/git-cvsserver
$ sudo ln -sf /usr/local/git/bin/git-receive-pack
$ sudo ln -sf /usr/local/git/bin/git-shell
$ sudo ln -sf /usr/local/git/bin/git-upload-archive
$ sudo ln -sf /usr/local/git/bin/git-upload-pack
$ ls -la
(you should see your new symlinks)

How to get visitor's location (i.e. country) using geolocation?

You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

$.get("https://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

How to send an email with Python?

While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 - Internet Message Format:

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding".

In the function form of your sendmail call, all lines are starting with white space and so are "unfolded" (concatenated) and you are trying to send

From: [email protected]    To: [email protected]    Subject: Hello!    This message was sent with Python's smtplib.

Other than our mind suggests, smtplib will not understand the To: and Subject: headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib will assume a very long sender email address:

[email protected]    To: [email protected]    Subject: Hello!    This message was sent with Python's smtplib.

This won't work and so comes your Exception.

The solution is simple: Just preserve the message string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:

import smtplib

def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
    """this is some test documentation in the function"""
    message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
    # Send the mail
    server = smtplib.SMTP(SERVER)
    server.sendmail(FROM, TO, message)
    server.quit()

Now the unfolding does not occur and you send

From: [email protected]
To: [email protected]
Subject: Hello!

This message was sent with Python's smtplib.

which is what works and what was done by your old code.

Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).

Getting the parent div of element

I had to do recently something similar, I used this snippet:

const getNode = () =>
  for (let el = this.$el; el && el.parentNode; el = el.parentNode){
    if (/* insert your condition here */) return el;
  }
  return null
})

The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null

In case somebody would look for multiple elements it only returns closest parent to the element that you provided.

My example was:

if (el.classList?.contains('o-modal')) return el;

I used it in a vue component (this.$el) change that to your document.getElementById function and you're good to go. Hope it will be useful for some people ??

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

java : non-static variable cannot be referenced from a static context Error

This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Make content horizontally scroll inside a div

Same as what clairesuzy answered, except you can get a similar result by adding display: flex instead of white-space: nowrap. Using display: flex will collapse the img "margins", in case that behavior is preferred.

Foreign Key naming scheme

I usually just leave my PK named id, and then concatenate my table name and key column name when naming FKs in other tables. I never bother with camel-casing, because some databases discard case-sensitivity and simply return all upper or lower case names anyway. In any case, here's what my version of your tables would look like:

task (id, userid, title);
note (id, taskid, userid, note);
user (id, name);

Note that I also name my tables in the singular, because a row represents one of the objects I'm persisting. Many of these conventions are personal preference. I'd suggest that it's more important to choose a convention and always use it, than it is to adopt someone else's convention.

Delete all records in a table of MYSQL in phpMyAdmin

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a db with approx 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Here is the actual implementation of both methods ( decompiled using dotPeek)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

SQL Server: Difference between PARTITION BY and GROUP BY

It provides rolled-up data without rolling up

i.e. Suppose I want to return the relative position of sales region

Using PARTITION BY, I can return the sales amount for a given region and the MAX amount across all sales regions in the same row.

This does mean you will have repeating data, but it may suit the end consumer in the sense that data has been aggregated but no data has been lost - as would be the case with GROUP BY.

What is the easiest way to remove the first character from a string?

If you always want to strip leading brackets:

"[12,23,987,43".gsub(/^\[/, "")

If you just want to remove the first character, and you know it won't be in a multibyte character set:

"[12,23,987,43"[1..-1]

or

"[12,23,987,43".slice(1..-1)

How do I set hostname in docker-compose?

I needed to spin freeipa container to have a working kdc and had to give it a hostname otherwise it wouldn't run. What eventually did work for me is setting the HOSTNAME env variable in compose:

version: 2
services:
  freeipa:
    environment:
      - HOSTNAME=ipa.example.test

Now its working:

docker exec -it freeipa_freeipa_1 hostname
ipa.example.test

How do I convert an array object to a string in PowerShell?

I found that piping the array to the Out-String cmdlet works well too.

For example:

PS C:\> $a  | out-string

This
Is
a
cat

It depends on your end goal as to which method is the best to use.

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As mentioned by Dan Abramov

Do it right inside render

We actually use that approach with memoise one for any kind of proxying props to state calculations.

Our code looks this way

// ./decorators/memoized.js  
import memoizeOne from 'memoize-one';

export function memoized(target, key, descriptor) {
  descriptor.value = memoizeOne(descriptor.value);
  return descriptor;
}

// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';

class ExampleComponent extends React.Component {
  buildValuesFromProps() {
    const {
      watchedProp1,
      watchedProp2,
      watchedProp3,
      watchedProp4,
      watchedProp5,
    } = this.props
    return {
      value1: buildValue1(watchedProp1, watchedProp2),
      value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
      value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
    }
  }

  @memoized
  buildValue1(watchedProp1, watchedProp2) {
    return ...;
  }

  @memoized
  buildValue2(watchedProp1, watchedProp3, watchedProp5) {
    return ...;
  }

  @memoized
  buildValue3(watchedProp3, watchedProp4, watchedProp5) {
    return ...;
  }

  render() {
    const {
      value1,
      value2,
      value3
    } = this.buildValuesFromProps();

    return (
      <div>
        <Component1 value={value1}>
        <Component2 value={value2}>
        <Component3 value={value3}>
      </div>
    );
  }
}

The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps or componentWillReceiveProps and you can skip copy-paste initialization inside a constructor.

NOTE:

This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.

Want to upgrade project from Angular v5 to Angular v6

I had to re-run ng update @angular/cli for angular-cli.json to be changed to angular.json

Squash the first two commits in Git?

You can use git filter-branch for that. e.g.

git filter-branch --parent-filter \
'if test $GIT_COMMIT != <sha1ofB>; then cat; fi'

This results in AB-C throwing away the commit log of A.

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

How to completely remove a dialog on close

$(this).dialog('destroy').remove()

This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM

How to create checkbox inside dropdown?

Multiple drop downs with checkbox's and jQuery.

<div id="list3" class="dropdown-check-list" tabindex="100">
<span class="anchor">Which development(s) are you interested in?</span>
  <ul class="items">
      <li><input id="answers_2529_the-lawns" name="answers[2529][answers][]" type="checkbox" value="The Lawns"/><label for="answers_2529_the-lawns">The Lawns</label></li>
      <li><input id="answers_2529_the-residence" name="answers[2529][answers][]" type="checkbox" value="The Residence"/><label for="answers_2529_the-residence">The Residence</label></li>
  </ul>
</div>

<style>
.dropdown-check-list{
display: inline-block;
width: 100%;
}
.dropdown-check-list:focus{
outline:0;
}
.dropdown-check-list .anchor {
width: 98%;
position: relative;
cursor: pointer;
display: inline-block;
padding-top:5px;
padding-left:5px;
padding-bottom:5px;
border:1px #ccc solid;
}
.dropdown-check-list .anchor:after {
position: absolute;
content: "";
border-left: 2px solid black;
border-top: 2px solid black;
padding: 5px;
right: 10px;
top: 20%;
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.dropdown-check-list .anchor:active:after {
right: 8px;
top: 21%;
}
.dropdown-check-list ul.items {
padding: 2px;
display: none;
margin: 0;
border: 1px solid #ccc;
border-top: none;
}
.dropdown-check-list ul.items li {
list-style: none;
}
.dropdown-check-list.visible .anchor {
color: #0094ff;
}
.dropdown-check-list.visible .items {
display: block;
}
</style>

<script>
jQuery(function ($) {
        var checkList = $('.dropdown-check-list');
        checkList.on('click', 'span.anchor', function(event){
            var element = $(this).parent();

            if ( element.hasClass('visible') )
            {
                element.removeClass('visible');
            }
            else
            {
                element.addClass('visible');
            }
        });
    });
</script>

complex if statement in python

if
  ...
  # several checks
  ...
elif ((var1 > 65535) or ((var1 < 1024)) and (var1 != 80) and (var1 != 443)):
  # fail
else
  ...

You missed a parenthesis.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.

My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.

But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.

Database Diagram Support Objects cannot be Installed ... no valid owner

Only need to execute it in query editor ALTER AUTHORIZATION ON DATABASE::YourDatabase TO [domain\account];

How can I pass an argument to a PowerShell script?

You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.

Example:

 PS C:\temp> $stepsize = 30
 PS C:\temp> .\itunesForward.ps1

with iTunesForward.ps1 being

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize
}

create table in postgreSQL

First the bigint(20) not null auto_increment will not work, simply use bigserial primary key. Then datetime is timestamp in PostgreSQL. All in all:

CREATE TABLE article (
    article_id bigserial primary key,
    article_name varchar(20) NOT NULL,
    article_desc text NOT NULL,
    date_added timestamp default NULL
);

Rails - Could not find a JavaScript runtime?

On CentOS 6.5, the following worked for me:

sudo yum install -y nodejs

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

how can get index & count in vuejs

this might be a dirty code but i think it can suffice

<div v-for="(counter in counters">
{{ counter }}) {{ userlist[counter-1].name }}
</div>

on your script add this one

data(){return {userlist: [],user_id: '',counters: 0,edit: false,}},

Is it possible to clone html element objects in JavaScript / JQuery?

In one line:

$('#selector').clone().attr('id','newid').appendTo('#newPlace');

How do I disable Git Credential Manager for Windows?

Use:

C:\Program Files\Git\mingw64\libexec\git-core                                                                       
git credential-manager uninstall --force    

This works on Windows systems. I tested it, and it worked for me.

Can I have H2 autocreate a schema in an in-memory database?

"By default, when an application calls DriverManager.getConnection(url, ...) and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.

Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {

    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
        Statement st = conn.createStatement();
        st.execute("create table customer(id integer, name varchar(10))");
        st.execute("insert into customer values (1, 'Thomas')");
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("select name from customer");
        while (rset.next()) {
            String name = rset.getString(1);
            System.out.println(name);
        }
    }
}

Working with SQL views in Entity Framework Core

Here is a new way to work with SQL views in EF Core: Query Types.

how to set mongod --dbpath

For me it must have:

mongod --dbpath=/whatever/data/path

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

C:\Users\USER\AppData\Roaming\Notepad++\backup

or

%AppData%\Notepad++\backup

How to run a command in the background on Windows?

I believe the command you are looking for is start /b *command*

For unix, nohup represents 'no hangup', which is slightly different than a background job (which would be *command* &. I believe that the above command should be similar to a background job for windows.

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Get value of div content using jquery

your div looks like this:

<div class="readonly_label" id="field-function_purpose">Other</div>

With jquery you can easily get inner content:

Use .html() : HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

var text = $('#field-function_purpose').html(); 

Read more about jquery .html()

or

Use .text() : Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

var text = $('#field-function_purpose').text();

Read more about jquery .text()

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

How to run JUnit tests with Gradle?

If you set up your project with the default gradle package structure, i.e.:

src/main/java
src/main/resources
src/test/java
src/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.

CodeIgniter: How to get Controller, Action, URL information

Update

The answer was added was in 2015 and the following methods are deprecated now

$this->router->fetch_class();  in favour of  $this->router->class; 
$this->router->fetch_method(); in favour of  $this->router->method;

Hi you should use the following approach

$this->router->fetch_class(); // class = controller
$this->router->fetch_method(); // action

for this purpose but for using this you need to extend your hook from the CI_Controller and it works like a charm, you should not use uri segments

Oracle SELECT TOP 10 records

You'll need to put your current query in subquery as below :

SELECT * FROM (
  SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC )
WHERE ROWNUM <= 10

Oracle applies rownum to the result after it has been returned.
You need to filter the result after it has been returned, so a subquery is required. You can also use RANK() function to get Top-N results.

For performance try using NOT EXISTS in place of NOT IN. See this for more.

What does "Object reference not set to an instance of an object" mean?

Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

Duplicate line in Visual Studio Code

The duplicate can be achieved by CTRL+C and CTRL+V with cursor in the line without nothing selected.

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Restore the mysql database from .frm files

Before starting you should stop the WAMP services, or at least restart the services when prompted to start them.

On the old server instance navigate to the MySQL data folder by default this should look something similar to C:\wamp\bin\mysql\mysql5.1.53\data\ where mysql5.1.53 will be the version number of the previously installed MySQL database.

Inside this folder you should see a few files and folders. The folders are the actual MySQL databases, and contain a bunch of .frm files which we will require. You should recognise the folder names as the database names. These folder and all their contents can be copied directly to your MySQL data folder, you can neglect the default databases mysql, performance_schema, test.

If you started the server now you will see the databases are picked up, however the databases will contain none of the tables which were copied across. In order for the contents of the database to be picked up, back in the data folder you should see a file ibdata1, this is the data file for tables, copy this directly into the data folder, you should already have a file in your new data folder called “ibdata1" so you may wish to rename this to ibdata1.bak before copying across the ibdata1 from the old MySQL data folder.

Once this has been done Restart all the WAMP services. You can use PhpMyAdmin to check if your databases have been successfully restored.

Hiding elements in responsive layout?

Bootstrap 4 Beta Answer:

d-block d-md-none to hide on medium, large and extra large devices.

d-none d-md-block to hide on small and extra-small devices.

enter image description here

Note that you can also inline by replacing d-*-block with d-*-inline-block


Old answer: Bootstrap 4 Alpha

  • You can use the classes .hidden-*-up to hide on a given size and larger devices

    .hidden-md-up to hide on medium, large and extra large devices.

  • The same goes with .hidden-*-down to hide on a given size and smaller devices

    .hidden-md-down to hide on medium, small and extra-small devices

  • visible-* is no longer an option with bootstrap 4

  • To display only on medium devices, you can combine the two:

    hidden-sm-down and hidden-xl-up

The valid sizes are:

  • xs for phones in portrait mode (<34em)
  • sm for phones in landscape mode (=34em)
  • md for tablets (=48em)
  • lg for desktops (=62em)
  • xl for desktops (=75em)

This was as of Bootstrap 4, alpha 5 (January 2017). More details here: http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

On Bootstrap 4.3.x: https://getbootstrap.com/docs/4.3/utilities/display/

Convert laravel object to array

foreach($yourArrayName as $object)
{
    $arrays[] = $object->toArray();
}
// Dump array with object-arrays
dd($arrays);

Or when toArray() fails because it's a stdClass

foreach($yourArrayName as $object)
{
    $arrays[] =  (array) $object;
}
// Dump array with object-arrays
dd($arrays);

Not working? Maybe you can find your answer here:

Convert PHP object to associative array

Creating an instance using the class name and calling constructor

Another helpful answer. How do I use getConstructor(params).newInstance(args)?

return Class.forName(**complete classname**)
    .getConstructor(**here pass parameters passed in constructor**)
    .newInstance(**here pass arguments**);

In my case, my class's constructor takes Webdriver as parameter, so used below code:

return Class.forName("com.page.BillablePage")
    .getConstructor(WebDriver.class)
    .newInstance(this.driver);

Print JSON parsed object?

Most debugger consoles support displaying objects directly. Just use

console.log(obj);

Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.

How can I access global variable inside class in Python

It is very simple to make a variable global in a class:

a = 0

class b():
    global a
    a = 10

>>> a
10

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Easy.

open xampp control panel -> Config -> my.ini edit with notepad. now add this below [mysqld]

skip-grant-tables

Save. Start apache and mysql.

I hope help you

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

Lining up labels with radio buttons in bootstrap

Since Bootstrap 3 you have to use checkbox-inline and radio-inline classes on the label.

This takes care of vertical alignment.

<label class="checkbox-inline">
    <input type="checkbox" id="inlineCheckbox1" value="option1"> 1
</label>
<label class="radio-inline">
    <input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> 1
</label>

How to get a path to a resource in a Java JAR file

The following path worked for me: classpath:/path/to/resource/in/jar

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Missing Maven dependencies in Eclipse project

I got this error when had an error in Pom.

  1. Run mvn eclipse:eclipse command on console to check that pom is parsable or not.
  2. If not parsable search for the error.

Compare a string using sh shell

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test says that you use -z to match for empty strings.

JavaScript global event mechanism

One should preserve the previously associated onerror callback as well

<script type="text/javascript">

(function() {
    var errorCallback = window.onerror;
    window.onerror = function () {
        // handle error condition
        errorCallback && errorCallback.apply(this, arguments);
    };
})();

</script>

PHP header(Location: ...): Force URL change in address bar

why all of this location url?

http://localhost:8080/meet2eat/index.php

you can just use

index.php

if the php files are in the same folder and this is better because if you want to host the files or change the port you will have no problem reaching this URL.

Why is Spring's ApplicationContext.getBean considered bad?

It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:

public class AutowireThisDriver {

    private MySpringBean mySpringBean;    

    public static void main(String[] args) {
       AutowireThisDriver atd = new AutowireThisDriver(); //get instance

       ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                  "/WEB-INF/applicationContext.xml"); //get Spring context 

       //the magic: auto-wire the instance with all its dependencies:
       ctx.getAutowireCapableBeanFactory().autowireBeanProperties(atd,
                  AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        

       // code that uses mySpringBean ...
       mySpringBean.doStuff() // no need to instantiate - thanks to Spring
    }

    public void setMySpringBean(MySpringBean bean) {
       this.mySpringBean = bean;    
    }
}

I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.

How to get a variable value if variable name is stored as string?

Had the same issue with arrays, here is how to do it if you're manipulating arrays too :

array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")

ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"

This will output :

ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2

Which maven dependencies to include for spring 3.0?

What classes are missing? The class name itself should be a good clue to the missing module.

FYI, I know its really convenient to include the uber spring jar but this really causes issues when integrating with other projects. One of the benefits behind the dependency system is that it will resolve version conflicts among the dependencies.

If my library depends on spring-core:2.5 and you depend on my library and uber-spring:3.0, you now have 2 versions of spring on your classpath.

You can get around this with exclusions but its much easier to list the dependencies correctly and not have to worry about it.

Purpose of ESI & EDI registers?

Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,

mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!

Failure [INSTALL_FAILED_INVALID_APK]

I have recently had this problem building a multi-module, multi-apk application. As it turns out, my top level gradle build was modifying the android:versionCode, and that was making it out of sync with the manifests in the dynamic feature modules. This took me hours to find the cause, and only minutes to solve.

I found that the android studio log itself,

idea.log

, tells me way more about the problem than the IDE did.

2020-02-05 22:52:56,206 [thread 246]   WARN -            #com.android.ddmlib - Failed to commit install session 986623974 with command cmd package install-commit 986623974. Error: INSTALL_FAILED_INVALID_APK: /data/app/vmdl986623974.tmp/1_mytestapp-afat-debug version code 1829 inconsistent with 18290 
2020-02-05 22:52:56,206 [thread 246]   WARN - a.run.tasks.AbstractDeployTask - Install failed: The application could not be installed: INSTALL_FAILED_INVALID_APK The APKs are invalid. 

Find the number of columns in a table

SELECT COUNT(COLUMN_NAME) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE 
    TABLE_CATALOG = 'Database name' 
    AND TABLE_SCHEMA = 'dbo' 
    AND TABLE_NAME = 'table name'

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Swift 5, 4

Usage

let text = "Hello world"
text[0] // H
text[...3] // "Hell"
text[6..<text.count] // world
text[NSRange(location: 6, length: 3)] // wor

Code

import Foundation

public extension String {
  subscript(value: Int) -> Character {
    self[index(at: value)]
  }
}

public extension String {
  subscript(value: NSRange) -> Substring {
    self[value.lowerBound..<value.upperBound]
  }
}

public extension String {
  subscript(value: CountableClosedRange<Int>) -> Substring {
    self[index(at: value.lowerBound)...index(at: value.upperBound)]
  }

  subscript(value: CountableRange<Int>) -> Substring {
    self[index(at: value.lowerBound)..<index(at: value.upperBound)]
  }

  subscript(value: PartialRangeUpTo<Int>) -> Substring {
    self[..<index(at: value.upperBound)]
  }

  subscript(value: PartialRangeThrough<Int>) -> Substring {
    self[...index(at: value.upperBound)]
  }

  subscript(value: PartialRangeFrom<Int>) -> Substring {
    self[index(at: value.lowerBound)...]
  }
}

private extension String {
  func index(at offset: Int) -> String.Index {
    index(startIndex, offsetBy: offset)
  }
}

How to get HttpClient to pass credentials along with the request?

I was also having this same problem. I developed a synchronous solution thanks to the research done by @tpeczek in the following SO article: Unable to authenticate to ASP.NET Web Api service with HttpClient

My solution uses a WebClient, which as you correctly noted passes the credentials without issue. The reason HttpClient doesn't work is because of Windows security disabling the ability to create new threads under an impersonated account (see SO article above.) HttpClient creates new threads via the Task Factory thus causing the error. WebClient on the other hand, runs synchronously on the same thread thereby bypassing the rule and forwarding its credentials.

Although the code works, the downside is that it will not work async.

var wi = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;

var wic = wi.Impersonate();
try
{
    var data = JsonConvert.SerializeObject(new
    {
        Property1 = 1,
        Property2 = "blah"
    });

    using (var client = new WebClient { UseDefaultCredentials = true })
    {
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        client.UploadData("http://url/api/controller", "POST", Encoding.UTF8.GetBytes(data));
    }
}
catch (Exception exc)
{
    // handle exception
}
finally
{
    wic.Undo();
}

Note: Requires NuGet package: Newtonsoft.Json, which is the same JSON serializer WebAPI uses.

How to connect to a docker container from outside the host (same network) [Windows]

  1. Open Oracle VM VirtualBox Manager
  2. Select the VM used by Docker
  3. Click Settings -> Network
  4. Adapter 1 should (default?) be "Attached to: NAT"
  5. Click Advanced -> Port Forwarding
  6. Add rule: Protocol TCP, Host Port 8080, Guest Port 8080 (leave Host IP and Guest IP empty)
  7. Guest is your docker container and Host is your machine

You should now be able to browse to your container via localhost:8080 and your-internal-ip:8080.

What SOAP client libraries exist for Python, and where is the documentation for them?

Im using SOAPpy with Python 2.5.3 in a production setting.

I had to manually edit a couple of files in SOAPpy (something about header code being in the wrong place) but other than that it worked and continues to do so very reliably.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

Changing the color of an hr element

hr {
    height: 1px;
    color: #123455;
    background-color: #123455;
    border: none;
}

Doing it this way allows you to change the height if needed. Good luck. Source: How To Style HR with CSS

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

How to document a method with parameter(s)?

Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:

def copy_net(
    infile: (str, 'The name of the file to send'),
    host: (str, 'The host to send the file to'),
    port: (int, 'The port to connect to')):

    pass

example adopted from: https://pypi.org/project/autocommand/

What is base 64 encoding used for?

When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings.

Why 64?
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

Looping through all rows in a table column, Excel-VBA

You can search column before assignments:

Dim col_n as long
for i = 1 to NumCols
    if Cells(1, i).Value = "column header you are looking for" Then col_n = i
next

for i = 1 to NumRows
    Cells(i, col_n).Value = "PHEV"
next i

How do I rename a column in a SQLite database table?

Say you have a table and need to rename "colb" to "col_b":

First you rename the old table:

ALTER TABLE orig_table_name RENAME TO tmp_table_name;

Then create the new table, based on the old table but with the updated column name:

CREATE TABLE orig_table_name (
  col_a INT
, col_b INT
);

Then copy the contents across from the original table.

INSERT INTO orig_table_name(col_a, col_b)
SELECT col_a, colb
FROM tmp_table_name;

Lastly, drop the old table.

DROP TABLE tmp_table_name;

Wrapping all this in a BEGIN TRANSACTION; and COMMIT; is also probably a good idea.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

test_dict = {}
if not test_dict.keys():
    print "Dict is Empty"

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is version specific and is now allowed for DATETIME columns as of version 5.6.

See MySQL docs.

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

How to find path of active app.config file?

Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

break out of if and foreach

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$device = "wanted";
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;

        // will leave the foreach loop and also the if statement
        break;
        some_function(); // never reached!
    }
    another_function();  // not executed after match/break
}

Just for completeness for others that stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

foreach (array('1','2','3') as $a) {
    echo "$a ";
    foreach (array('3','2','1') as $b) {
        echo "$b ";
        if ($a == $b) { 
            break 2;  // this will break both foreach loops
        }
    }
    echo ". ";  // never reached!
}
echo "!";

Resulting output:

1 3 2 1 !

Set Content-Type to application/json in jsp file

@Petr Mensik & kensen john

Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

    <%
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("UTF-8");
        if (callback != null) {
            // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
            response.setContentType("text/javascript");
        } else {
            // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
            response.setContentType("application/json");
        }

        [...]

        String output = "";

        if (callback != null) {
            output += callback + "(";
        }

        output += jsonObj.toString();

        if (callback != null) {
            output += ");";
        }
    %>
    <%=output %>

When callback is supplied, returns:

    callback({...JSON stuff...});

with content-type "text/javascript"

When callback is NOT supplied, returns:

    {...JSON stuff...}

with content-type "application/json"

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Below code gives in hh:mm format.

select RIGHT(LEFT(job_end- job_start,17),5)

How to redirect the output of a PowerShell to a file during its execution

Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.

In PowerShell 3.0, we've extended output redirection to include the following streams: 
 Pipeline (1) 
 Error    (2) 
 Warning  (3) 
 Verbose  (4) 
 Debug    (5)
 All      (*)

We still use the same operators
 >    Redirect to a file and replace contents
 >>   Redirect to a file and append to existing content
 >&1  Merge with pipeline output

See the "about_Redirection" help article for details and examples.

help about_Redirection

How to save to local storage using Flutter?

If you are in a situation where you wanna save a small value that you wanna refer later. then you should store your data as key-value data using shared_preferences

but if you want to store large data you should go with SQLITE

however you can always use firebase database which is available offline

Since we are talking about local storage you can always read and write files to the disk

Other solutions :

ArrayList: how does the size increase?

Typically, the memory for ArrayList type containers is increased by doubling it. Thus, if you initially had space for 10 items and you added 10, the eleventh item will be added to a new (internal) array of 20 items. The reason for this is that the incremental cost of adding items is reduced from O(n^2) if the array had been incremented in fixed size increments to a nice O(n) when doubling the size each time the internal array is full.

Extract values in Pandas value_counts()

#!/usr/bin/env python

import pandas as pd

# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
                   (2, 'France'),
                   (3, 'Indonesia'),
                   (4, 'France'),
                   (5, 'France'),
                   (6, 'Germany'),
                   (7, 'UK'),
                   ],
                  columns=['groupid', 'country'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()

Now, print(df['country'].value_counts()) gives:

France       3
Germany      2
UK           1
Indonesia    1

and print(values) gives:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts) gives:

[3, 2, 1, 1]

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

On this MSDN blog: Troubleshooting HTTP 500.19 Errors in IIS 7 in scenario 8 for error code 0x80070005 (E_ACCESSDENIED - General access denied error) it says:

Grant Read permission to the IIS_IUSRS group ...

.... the worker process identity (and/or the IIS_IUSRS group) needs at least Read access to the directory so that it can check for a web.config file in that directory.

How to add title to subplots in Matplotlib?

A shorthand answer assuming import matplotlib.pyplot as plt:

plt.gca().set_title('title')

as in:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

Then there is no need for superfluous variables.

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

Application Crashes With "Internal Error In The .NET Runtime"

In my case the problem was related to "Referencing .NET standard library in classic asp.net projects" and these two issues

https://github.com/dotnet/standard/issues/873

https://github.com/App-vNext/Polly/issues/628

and downgrading to Polly v6 was enough to workaround it

how to read System environment variable in Spring applicationContext

Yes, you can do <property name="defaultLocale" value="#{ systemProperties['user.region']}"/> for instance.

The variable systemProperties is predefined, see 6.4.1 XML based configuration.

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

What are some good Python ORM solutions?

There is no conceivable way that the unused features in Django will give a performance penalty. Might just come in handy if you ever decide to upscale the project.

Using Java to find substring of a bigger string using Regular Expression

"FOO[DOG]".replaceAll("^.*?\\[|\\].*", "");

This will return a string taking only the string inside square brackets.

This remove all string outside from square brackets.

You can test this java sample code online: http://tpcg.io/wZoFu0

You can test this regex from here: https://regex101.com/r/oUAzsS/1

How do I make a MySQL database run completely in memory?

In place of the Memory storage engine, one can consider MySQL Cluster. It is said to give similar performance but to support disk-backed operation for durability. I've not tried it, but it looks promising (and been in development for a number of years).

You can find the official MySQL Cluster documentation here.

How to select a CRAN mirror in R

You should either get a window with a list of repositories or a text menu with some options. But if that is not appearing, you can always specify the mirror from where to download the packages yourself by using repos parameter. By doing that, R will not ask you anymore about the repository. Example:

install.packages('RMySQL', repos='http://cran.us.r-project.org')

Here you have a list of mirrors for R.

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

Filter output in logcat by tagname

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

If you just want to set the log levels for some tags you can do it on a tag by tag basis.

create table with sequence.nextval in oracle

I for myself prefer Lukas Edger's solution.

But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.

you can read more about pros and cons here

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

How to load my app from Eclipse to my Android phone instead of AVD

The USB drivers in \extras\google\usb_driver didn't work for me.

However the official drivers from Samsung did: http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows

Note: I'm using a Samsung Galaxy S2 with Android 4.0 on Windows 7 64bit

How do I concatenate strings and variables in PowerShell?

(Current PowerShell version 5.1.17134.407)

This also works as of now:

$myVar = "Hello"

echo "${myVar} World"

Note: this only works with double quotes

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

I solved my problem with the change of the parent Spring Boot Dependency.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
</parent>

For more Information, take a look at the release notes: Spring Boot 2.1.0 Release Notes

Apply CSS rules if browser is IE

A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):

margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/

A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.

Angular window resize event

I know this was asked a long time ago, but there is a better way to do this now! I'm not sure if anyone will see this answer though. Obviously your imports:

import { fromEvent, Observable, Subscription } from "rxjs";

Then in your component:

resizeObservable$: Observable<Event>
resizeSubscription$: Subscription

ngOnInit() {
    this.resizeObservable$ = fromEvent(window, 'resize')
    this.resizeSubscription$ = this.resizeObservable$.subscribe( evt => {
      console.log('event: ', evt)
    })
}

Then be sure to unsubscribe on destroy!

ngOnDestroy() {
    this.resizeSubscription$.unsubscribe()
}

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.

This has worked for me:

HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
    response = (HttpWebResponse)we.Response;
}

statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

How to read file binary in C#?

Use simple FileStream.Read then print it with Convert.ToString(b, 2)

Cloning a private Github repo

I was using Android Studio to clone the project from GitHub private repository and two-factor authentication (2FA). I created a personal token as made in lzl124631x's answer.

Then I cloned the repo using an url like this: https://YourGitHubUsername:[email protected]/YourRepoPath.git

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

C:\ProgramData\Oracle\Java\javapath

I took a back up of the files in it and removed those files from there. Then I opened a new cmd prompt and it works like a charm.

How to iterate over a JavaScript object?

For most objects, use for .. in :

for (let key in yourobject) {
  console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 let keys = [];
 for (let key in yourobject) {      
     if (yourobject.hasOwnProperty(key)) keys.push(key);
 }

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (let i=300; i < keys.length && i < 600; i++) { 
   console.log(keys[i], yourobject[keys[i]]);
}

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

How do I retrieve a textbox value using JQuery?

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

var txt=$('input:text[name=DrugDurationLength]').val();

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

How to increase the max connections in postgres?

Just increasing max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.


Considerations

max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.

Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.

Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.

A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.


How to increase max connections

1. Increase max_connection and shared_buffers

in /var/lib/pgsql/{version_number}/data/postgresql.conf

change

max_connections = 100
shared_buffers = 24MB

to

max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

  • If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
  • it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount (like 25%)
  • Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB.
  • Note that on Windows, large values for shared_buffers aren't as effective, and you may find better results keeping it relatively low and using the OS cache more instead. On Windows the useful range is 64MB to 512MB.

2. Change kernel.shmmax

You would need to increase kernel max segment size to be slightly larger than the shared_buffers.

In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)

kernel.shmmax=100663296

References

Postgres Max Connections And Shared Buffers

Tuning Your PostgreSQL Server

fatal error: iostream.h no such file or directory

That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.

Use #include <iostream> instead. And all the library classes are in the std:: namespace, for ex­am­ple std::cout.

Also, throw away any book or notes that mention the thing you said.

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

updating table rows in postgres using subquery

There are many ways to update the rows.

When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

  1. Approach-1 [Using direct table reference]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2>
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

  1. Approach-2 [Using SubQueries]
UPDATE
  <table1>
SET
  customer=subquery.customer,
  address=subquery.address,
  partn=subquery.partn
FROM
  (
    SELECT
      address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
  ) AS subquery
WHERE
  dummy.address_id=subquery.address_id;

Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

  1. Approach-3 [Using multiple Joined tables]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2> as t2
  JOIN <table3> as t3
  ON
    t2.id = t3.id
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

  1. Approach-4 [Using WITH statement]

    • 4.1 [Using simple query]
WITH subquery AS (
    SELECT
      address_id,
      customer,
      address,
      partn
    FROM
      <table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
  • 4.2 [Using query with complex JOIN]
WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM
      <table1> as t1
    JOIN
      <table2> as t2
    ON
      t1.id = t2.id;
    -- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;

Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

I hope, this would be helpful.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

As many have already stated, as much as you want to test the private methods you shouldn't hack your code or transpiler to make it work for you. Modern day TypeScript will deny most all of the hacks that people have provided so far.


Solution

TLDR; if a method should be tested then you should be decoupling the code into a class that you can expose the method to be public to be tested.

The reason you have the method private is because the functionality doesn't necessarily belong to be exposed by that class, and therefore if the functionality doesn't belong there it should be decoupled into it's own class.

Example

I ran across this article that does a great job of explaining how you should tackle testing private methods. It even covers some of the methods here and how why they're bad implementations.

https://patrickdesjardins.com/blog/how-to-unit-test-private-method-in-typescript-part-2

Note: This code is lifted from the blog linked above (I'm duplicating in case the content behind the link changes)

Before
class User{
    public getUserInformationToDisplay(){
        //...
        this.getUserAddress();
        //...
    }

    private getUserAddress(){
        //...
        this.formatStreet();
        //...
    }
    private formatStreet(){
        //...
    }
}
After
class User{
    private address:Address;
    public getUserInformationToDisplay(){
        //...
        address.getUserAddress();
        //...
    }
}
class Address{
    private format: StreetFormatter;
    public format(){
        //...
        format.ToString();
        //...
    }
}
class StreetFormatter{
    public toString(){
        // ...
    }
}

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Using AND/OR in if else PHP statement

i think i am having a bit of confusion here. :) But seems no one else have ..

Are you asking which one to use in this scenario? If Yes then And is the correct answer.

If you are asking about how the operators are working, then

In php both AND, && and OR, || will work in the same way. If you are new in programming and php is one of your first languages them i suggest using AND and OR, because it increases readability and reduces confusion when you check back. But if you are familiar with any other languages already then you might already have familiarized the && and || operators.

ORA-28000: the account is locked error getting frequently

Check the PASSWORD_LOCK_TIME parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock command.

Should I return EXIT_SUCCESS or 0 from main()?

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example.

If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.

For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.)

(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

Using Excel as front end to Access database (with VBA)

I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.

In this case the best solution is:

  1. Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.

  2. Use Excel forms for user interaction and for data visualisation.

  3. I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

How do I filter query objects by date range in Django?

Is simple,

YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())

Works for me

How to diff one file to an arbitrary version in Git?

If neither commit is your HEAD then bash's brace expansion proves really useful, especially if your filenames are long, the example above:

git diff master~20:pom.xml master:pom.xml

Would become

git diff {master~20,master}:pom.xml

More on Brace expansion with bash.

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

Wait for a process to finish

Okay, so it seems the answer is -- no, there is no built in tool.

After setting /proc/sys/kernel/yama/ptrace_scope to 0, it is possible to use the strace program. Further switches can be used to make it silent, so that it really waits passively:

strace -qqe '' -p <PID>

How to install a private NPM module without my own registry?

Very simple -

npm config set registry https://path-to-your-registry/

It actually sets registry = "https://path-to-your-registry" this line to /Users/<ur-machine-user-name>/.npmrc

All the value you have set explicitly or have been set by default can be seen by - npm config list

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

How to get the entire document HTML as a string?

You can do

new XMLSerializer().serializeToString(document)

in browsers newer than IE 9

See https://caniuse.com/#feat=xml-serializer

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

How to convert an object to JSON correctly in Angular 2 with TypeScript

Tested and working in Angular 9.0

If you're getting the data using API

array: [];

ngOnInit()    {
this.service.method()
.subscribe(
    data=>
  {
    this.array = JSON.parse(JSON.stringify(data.object));
  }
)

}

You can use that array to print your results from API data in html template.

Like

<p>{{array['something']}}</p>

adb doesn't show nexus 5 device

Here is simple solution for Windows 7 and Nexus 5 on Android 5.

  1. Download the Nexus 5 Drivers from http://androidhost.org/jelry
  2. Extract the zip contents and place all files in a single folder on your desktop.
  3. Connect your device to your computer.
  4. Launch the Device Manager on your PC.
  5. Now you should see the Nexus 5 listed in the hardware list.
  6. Right-click the ‘Nexus 5' line and then click on Update Driver Software.
  7. Next, click the ‘browse my computer’ option.
  8. In the new window click on ‘Browse…’ button.
  9. Go to folder unzipped at step 2. Select the folder where you extract the USB Drivers. Click Next. – make sure to tick the subfolder box too.
  10. Now, the Windows installer will search for Nexus 5 drivers, click Install when asked for permission.
  11. Wait for the process to complete and then check the Device Manager list to confirm that the installation was successful.

Original: http://www.android.gs/download-and-install-google-nexus-5-usb-drivers-adb-fastboot/

Note: do not forget to enable USB debugging on your device :)

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

How should I choose an authentication library for CodeIgniter?

Also take a look at BackendPro

Ultimately you will probably end up writing something custom, but there's nothing wrong with borrowing concepts from DX Auth, Freak Auth, BackendPro, etc.

My experiences with the packaged apps is they are specific to certain structures and I have had problems integrating them into my own applications without requiring hacks, then if the pre-package has an update, I have to migrate them in.

I also use Smarty and ADOdb in my CI code, so no matter what I would always end up making major code changes.

How to pass form input value to php function

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

When is JavaScript synchronous?

"I have been under the impression for that JavaScript was always asynchronous"

You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

         A-Start ------------------------------------------ A-End   
           | B-Start -----------------------------------------|--- B-End   
           |    |      C-Start ------------------- C-End      |      |   
           |    |       |                           |         |      |
           V    V       V                           V         V      V      
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 

We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

How to know if a function is async?

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

Content Security Policy: The page's settings blocked the loading of a resource

I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).

Loading local JSON file

What worked for me is the following:

Input:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript Code:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>

What is the best open XML parser for C++?

pugixml - Light-weight, simple and fast XML parser for C++ Very small (comparable to RapidXML), very fast (comparable to RapidXML), very easy to use (better than RapidXML).