Programs & Examples On #Cdi

Java Platform, Enterprise Edition (Java EE) 5 brought dependency injection (DI) with Convention over Configuration to Enterprise JavaBeans (EJB) 3.0. Java EE 6 introduces the flexible and powerful @Inject dependency injection model (JSR-330 and JSR-299) in addition to the already existing @EJB annotation.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Why use @PostConstruct?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.

  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

When I remove AnnotationConfigWebApplicationContext context param from web.xml file This is work

If you have got like param which as shown below you must remove it from web.xml file

<context-param>
    <param-name>contextClass</param-name>
    <param-value>
      org.springframework.web.context.support.AnnotationConfigWebApplicationContext
  </param-value>
</context-param> 

Should I use @EJB or @Inject

The @EJB is used to inject EJB's only and is available for quite some time now. @Inject can inject any managed bean and is a part of the new CDI specification (since Java EE 6).

In simple cases you can simply change @EJB to @Inject. In more advanced cases (e.g. when you heavily depend on @EJB's attributes like beanName, lookup or beanInterface) than in order to use @Inject you would need to define a @Producer field or method.

These resources might be helpful to understand the differences between @EJB and @Produces and how to get the best of them:

Antonio Goncalves' blog:
CDI Part I
CDI Part II
CDI Part III

JBoss Weld documentation:
CDI and the Java EE ecosystem

StackOverflow:
Inject @EJB bean based on conditions

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Composer install error - requires ext_curl when it's actually enabled

In my case I moved from PHP5 to PHP7 and I ve got this error, Simply go to your /bin/php/php7/php.ini , then uncomment extension=php_curl.dll and restart your server, re-run your composer install.

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

ArrayList: how does the size increase?

It will depend on the implementation, but from the Sun Java 6 source code:

int newCapacity = (oldCapacity * 3)/2 + 1;

That's in the ensureCapacity method. Other JDK implementations may vary.

How to use mod operator in bash?

Try the following:

 for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done

The $(( )) syntax does an arithmetic evaluation of the contents.

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

check null,empty or undefined angularjs

if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){

console.log("test is not defined");
}
else{
console.log("test is defined ",$scope.test); 
}

Missing visible-** and hidden-** in Bootstrap v4

Bootstrap v4.1 uses new classnames for hiding columns on their grid system.

For hiding columns depending on the screen width, use d-none class or any of the d-{sm,md,lg,xl}-none classes. To show columns on certain screen sizes, combine the above mentioned classes with d-block or d-{sm,md,lg,xl}-block classes.

Examples are:

_x000D_
_x000D_
<div class="d-lg-none">hide on screens wider than lg</div>_x000D_
<div class="d-none d-lg-block">hide on screens smaller than lg</div>
_x000D_
_x000D_
_x000D_

More of these here.

Char to int conversion in C

Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:

Both the basic source and basic execution character sets shall have the following members:
[...]
the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
[...]
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.

There is no library function to do it for a single char, you would need to build a string first:

int digit_to_int(char d)
{
 char str[2];

 str[0] = d;
 str[1] = '\0';
 return (int) strtol(str, NULL, 10);
}

You could also use the atoi() function to do the conversion, once you have a string, but strtol() is better and safer.

As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

Check and make sure that you do not have another values folder that references theme.styled and does not use AppCompat theme

ie values-v11 folder

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I am using Spring Boot 2.2.6(Windows) and faced the same issue when I tried the run the application: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

What solved my problem:

  1. Create a new user (from the MySQL workbench or a similar GUI which you might be using)
  2. Grant DBA priviledges (Tick the DBA checkbox) also from the GUI
  3. Run the spring boot application.

Or follow the @evg solution to grant privilegdes from command line in Linux env.

How to Pass data from child to parent component Angular

In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.

@Output() public eventName:EventEmitter = new EventEmitter();

to emit this event:

this.eventName.emit(payloadDataObject);

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

I had the problem whereby VB6 IDE would not load the common controls (Sp6)with VB6 install on W7 64bit, specifically comctrl and msmask. I tried all the solutions proposed using regsrv32 (elevated), edited the registry, changing the version number in the vbp etc as proposed by MS and others. All failed. These solutions worked on my other 2 PCS but not this one. Eventually I removed IE11 and all worked properly afterwards. IE10 had never bene installed on thsi PC - we went straight from IE8 to IE11 and have been forced to backtrack to using IE8.

I have to say the simple solution above does not address the problem which is that the VB6 IDE will not load the common controls (using the Components menu selection under Project) - you get an error saying Object not loaded. So this will happen (and I proved this to myself) on any project, new or old that try to use theose common controls that will not load.

So my suggestion to anyone who has this problem is to try the manual register solution using regsrv32 route, then the edit the vbp to change the version, and if these fail uninstall IE11 (and defintely IE10). But this may still not be a 100% solution because if your existing project files ".vbp" contain references to the wrong common controls you need to correct that manually - this is where loading a new project, loading the Components you need inside the IDE, then edit the newly create vbp using notepad and copy the version numbers for the common controls to your existing vbp files.

How to disable mouse scroll wheel scaling with Google Maps API

For someone that wondering how to disable the Javascript Google Map API

It will enable the zooming scroll if you click the map once. And disable after your mouse exit the div.

Here is some example

_x000D_
_x000D_
var map;_x000D_
var element = document.getElementById('map-canvas');_x000D_
function initMaps() {_x000D_
  map = new google.maps.Map(element , {_x000D_
    zoom: 17,_x000D_
    scrollwheel: false,_x000D_
    center: {_x000D_
      lat: parseFloat(-33.915916),_x000D_
      lng: parseFloat(151.147159)_x000D_
    },_x000D_
  });_x000D_
}_x000D_
_x000D_
_x000D_
//START IMPORTANT part_x000D_
//disable scrolling on a map (smoother UX)_x000D_
jQuery('.map-container').on("mouseleave", function(){_x000D_
  map.setOptions({ scrollwheel: false });_x000D_
});_x000D_
jQuery('.map-container').on("mousedown", function() {_x000D_
  map.setOptions({ scrollwheel: true });_x000D_
});_x000D_
//END IMPORTANT part
_x000D_
.big-placeholder {_x000D_
  background-color: #1da261;_x000D_
  height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
  <body>_x000D_
      <div class="big-placeholder">_x000D_
      </div>_x000D_
      _x000D_
      _x000D_
      <!-- START IMPORTANT part -->_x000D_
      <div class="map-container">_x000D_
        <div id="map-canvas" style="min-height: 400px;"></div>  _x000D_
      </div>_x000D_
      <!-- END IMPORTANT part-->_x000D_
      _x000D_
      _x000D_
      _x000D_
      <div class="big-placeholder">_x000D_
      </div>_x000D_
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIjN23OujC_NdFfvX4_AuoGBbkx7aHMf0&callback=initMaps">_x000D_
      </script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Set background image according to screen resolution

Set body css to :

body { 
background: url(../img/background.jpg) no-repeat center center fixed #000; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

}

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

How to use delimiter for csv in python

CSV Files with Custom Delimiters

By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are | and \t.

import csv
data_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='|')
    writer.writerows(data_list)

output:

SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming

Write CSV files with quotes

import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
    writer.writerows(row_list) 

output:

"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"

As you can see, we have passed csv.QUOTE_NONNUMERIC to the quoting parameter. It is a constant defined by the csv module.

csv.QUOTE_NONNUMERIC specifies the writer object that quotes should be added around the non-numeric entries.

There are 3 other predefined constants you can pass to the quoting parameter:

  • csv.QUOTE_ALL - Specifies the writer object to write CSV file with quotes around all the entries.
  • csv.QUOTE_MINIMAL - Specifies the writer object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)
  • csv.QUOTE_NONE - Specifies the writer object that none of the entries should be quoted. It is the default value.
import csv

row_list = [["SN", "Name", "Contribution"],
             [1, "Linus Torvalds", "Linux Kernel"],
             [2, "Tim Berners-Lee", "World Wide Web"],
             [3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
                        delimiter=';', quotechar='*')
    writer.writerows(row_list)

output:

*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*

Here, we can see that quotechar='*' parameter instructs the writer object to use * as quote for all non-numeric values.

Set element focus in angular way

I prefered to use an expression. This lets me do stuff like focus on a button when a field is valid, reaches a certain length, and of course after load.

<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">

On a complex form this also reduces need to create additional scope variables for the purposes of focusing.

See https://stackoverflow.com/a/29963695/937997

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']

implement in:

df[df.countries.isin(countries)]

implement not in as in of rest countries:

df[df.countries.isin([x for x in np.unique(df.countries) if x not in countries])]

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

This solved my problem. I added this line before the request is made:

System.Net.ServicePointManager.Expect100Continue = false;

It seemed there were a proxy in the way of the server that not supported 100-continue behavior.

How to add action listener that listens to multiple buttons

There is no this pointer in a static method. (I don't believe this code will even compile.)

You shouldn't be doing these things in a static method like main(); set things up in a constructor. I didn't compile or run this to see if it actually works, but give it a try.

public class Calc extends JFrame implements ActionListener {

    private Button button1;

    public Calc()
    {
        super();
        this.setSize(100, 100);
        this.setVisible(true);

        this.button1 = new JButton("1");
        this.button1.addActionListener(this);
        this.add(button1);
    }


    public static void main(String[] args) {

        Calc calc = new Calc();
        calc.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button1)
    }  

}

Store mysql query output into a shell variable

To read the data line-by-line into a Bash array you can do this:

while read -a row
do
    echo "..${row[0]}..${row[1]}..${row[2]}.."
done < <(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p $password)

Or into individual variables:

while read a b c
do
    echo "..${a}..${b}..${c}.."
done < <(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p $password)

Spring Data JPA findOne() change to Optional how to use this?

The method has been renamed to findById(…) returning an Optional so that you have to handle absence yourself:

Optional<Foo> result = repository.findById(…);

result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before

C++ class forward declaration

class tile_tree_apple should be defined in a separate .h file.

tta.h:
#include "tile.h"

class tile_tree_apple : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;}; 
          tile onUse() {return *new tile_tree;};       
};

file tt.h
#include "tile.h"

class tile_tree : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE;};        
};

another thing: returning a tile and not a tile reference is not a good idea, unless a tile is a primitive or very "small" type.

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.

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

no suitable HttpMessageConverter found for response type

If you are using Spring Boot, you might want to make sure you have the Jackson dependency in your classpath. You can do this manually via:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Or you can use the web starter:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Phone number validation Android

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

how to enable sqlite3 for php?

This will drown here, but I fixed my problems with this:

As far as I have found out, there is a faulty file in /usr/local/lib called libsqlite3.so.0 which points to libsqlite3.so.0.8.6. It's been installed through the php7.3-* packages as far as I can tell.

I renamed the file in case it was needed for something. With the command:

cd /usr/local/lib sudo mv libsqlite3.so.0 ./libsqlite3.so.0.back

But you can also just delete it: rm libsqlite3.so.0

The thread that lead me to the answer: link

This solved my problems, and I hope they solve yours as well :)

The calling thread must be STA, because many UI components require this

If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.

If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:

Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);

t.Start();

with ThreadProc being a delegate of type ThreadStart.

What is process.env.PORT in Node.js?

In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that to app.listen, or to app.set('port', ...), and that makes your server able to accept a "what port to listen on" parameter from the environment.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.

How to cancel a pull request on github?

If you sent a pull request on a repository where you don't have the rights to close it, you can delete the branch from where the pull request originated. That will cancel the pull request.

How to establish ssh key pair when "Host key verification failed"

Also sometimes there is situation when you are working on serial console, then checking above command in verbose mode -v will show you /dev/tty does not exists, while it does.

In above case just remove /dev/tty and create a symlink of /dev/ttyS0 to /dev/tty.

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

Why am I getting AttributeError: Object has no attribute

The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error

How to create range in Swift?

func replace(input: String, start: Int,lenght: Int, newChar: Character) -> String {
    var chars = Array(input.characters)

    for i in start...lenght {
        guard i < input.characters.count else{
            break
        }
        chars[i] = newChar
    }
    return String(chars)
}

PHP Error: Function name must be a string

A useful explanation to how braces are used (in addition to Filip Ekberg's useful answer, above) can be found in the short paper Parenthesis in Programming Languages.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

Just modify the connection string with the following code in the application.properties file.


spring.datasource.url=jdbc:mysql://localhost:3301/Db?
   useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=
   false&serverTimezone=UTC

Changing a specific column name in pandas DataFrame

pandas version 0.23.4

df.rename(index=str,columns={'old_name':'new_name'},inplace=True)

For the record:

omitting index=str will give error replace has an unexpected argument 'columns'

Git branching: master vs. origin/master vs. remotes/origin/master

One clarification (and a point that confused me):

"remotes/origin/HEAD is the default branch" is not really correct.

remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.

Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.

How do I connect to an MDF database file?

Alternative solution, where you can have the database in the folder you want inside the solution. That worked for me:

.ConnectionString(@"Data Source=LocalDB)\MSSQLLocalDB;
                    AttachDbFilename="+AppDomain.CurrentDomain.BaseDirectory+"Folder1\\Folder2\\SampleDatabase.mdf" + ";
                    Integrated Security=True;")

How to determine if a decimal/double is an integer?

Using int.TryParse will yield these results:

        var shouldBeInt = 3;

        var shouldntBeInt = 3.1415;

        var iDontWantThisToBeInt = 3.000f;

        Console.WriteLine(int.TryParse(shouldBeInt.ToString(), out int parser)); // true

        Console.WriteLine(int.TryParse(shouldntBeInt.ToString(), out parser)); // false

        Console.WriteLine(int.TryParse(iDontWantThisToBeInt.ToString(), out parser)); // true, even if I don't want this to be int

        Console.WriteLine(int.TryParse("3.1415", out  parser)); // false

        Console.WriteLine(int.TryParse("3.0000", out parser)); // false

        Console.WriteLine(int.TryParse("3", out parser)); // true

        Console.ReadKey();

How to normalize a histogram in MATLAB?

The area of abcd`s PDF is not one, which is impossible like pointed out in many comments. Assumptions done in many answers here

  1. Assume constant distance between consecutive edges.
  2. Probability under pdf should be 1. The normalization should be done as Normalization with probability, not as Normalization with pdf, in histogram() and hist().

Fig. 1 Output of hist() approach, Fig. 2 Output of histogram() approach

enter image description here enter image description here

The max amplitude differs between two approaches which proposes that there are some mistake in hist()'s approach because histogram()'s approach uses the standard normalization. I assume the mistake with hist()'s approach here is about the normalization as partially pdf, not completely as probability.

Code with hist() [deprecated]

Some remarks

  1. First check: sum(f)/N gives 1 if Nbins manually set.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%http://stackoverflow.com/a/5321546/54964
N=10000;
Nbins=50;
[f,x]=hist(randn(N,1),Nbins); % create histogram from ND

%METHOD 4: Count Densities, not Sums!
figure(3)
dx=diff(x(1:2)); % width of bin
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND with dx
% 1.0000
bar(x, f/sum(f));hold on
plot(x,g,'r');hold off

Output is in Fig. 1.

Code with histogram()

Some remarks

  1. First check: a) sum(f) is 1 if Nbins adjusted with histogram()'s Normalization as probability, b) sum(f)/N is 1 if Nbins is manually set without normalization.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%%METHOD 5: with histogram()
% http://stackoverflow.com/a/38809232/54964
N=10000;

figure(4);
h = histogram(randn(N,1), 'Normalization', 'probability') % hist() deprecated!
Nbins=h.NumBins;
edges=h.BinEdges; 
x=zeros(1,Nbins);
f=h.Values;
for counter=1:Nbins
    midPointShift=abs(edges(counter)-edges(counter+1))/2; % same constant for all
    x(counter)=edges(counter)+midPointShift;
end
dx=diff(x(1:2)); % constast for all
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND
% Use if Nbins manually set
%new_area=sum(f)/N % diff of consecutive edges constant
% Use if histogarm() Normalization probability
new_area=sum(f)
% 1.0000
% No bar() needed here with histogram() Normalization probability
hold on;
plot(x,g,'r');hold off

Output in Fig. 2 and expected output is met: area 1.0000.

Matlab: 2016a
System: Linux Ubuntu 16.04 64 bit
Linux kernel 4.6

How can I output UTF-8 from Perl?

do in your shell: $ env |grep LANG

This will probably show that your shell is not using a utf-8 locale.

Pandas group-by and sum

If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()

Fruit   Name       Number
Apples  Bob        16
Apples  Mike        9
Apples  Steve      10
Grapes  Bob        35
Grapes  Tom        87
Grapes  Tony       15
Oranges Bob        67
Oranges Mike       57
Oranges Tom        15
Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()

               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

Why Does OAuth v2 Have Both Access and Refresh Tokens?

While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation. Another point missing in discussion is from rfc6749#page-55

"For example, the authorization server could employ refresh token rotation in which a new refresh token is issued with every access token refresh response.The previous refresh token is invalidated but retained by the authorization server. If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

Disable vertical scroll bar on div overflow: auto

These two CSS properties can be used to hide the scrollbars:

overflow-y: hidden; // hide vertical
overflow-x: hidden; // hide horizontal

What does the term "canonical form" or "canonical representation" in Java mean?

The word "canonical" is just a synonym for "standard" or "usual". It doesn`t have any Java-specific meaning.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

Asynchronous Function Call in PHP

cURL is going to be your only real choice here (either that, or using non-blocking sockets and some custom logic).

This link should send you in the right direction. There is no asynchronous processing in PHP, but if you're trying to make multiple simultaneous web requests, cURL multi will take care of that for you.

Can I use jQuery to check whether at least one checkbox is checked?

$("#show").click(function() {
    var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
        if(count_checked == 0) 
        {
            alert("Please select any record to delete.");
            return false;
        }
        if(count_checked == 1) {
            alert("Record Selected:"+count_checked);

        } else {
            alert("Record Selected:"+count_checked);
          }
});

How do I find out what is hammering my SQL Server?

You can run the SQL Profiler, and filter by CPU or Duration so that you're excluding all the "small stuff". Then it should be a lot easier to determine if you have a problem like a specific stored proc that is running much longer than it should (could be a missing index or something).

Two caveats:

  • If the problem is massive amounts of tiny transactions, then the filter I describe above would exclude them, and you'd miss this.
  • Also, if the problem is a single, massive job (like an 8-hour analysis job or a poorly designed select that has to cross-join a billion rows) then you might not see this in the profiler until it is completely done, depending on what events you're profiling (sp:completed vs sp:statementcompleted).

But normally I start with the Activity Monitor or sp_who2.

How can I convert a std::string to int?

The possible options are described below:

1. First option: sscanf()

    #include <cstdio>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        if(sscanf(str.c_str(), "%d", &i) != 1)
            // error management

        // string -> float
        if(sscanf(str.c_str(), "%f", &f) != 1)
            // error management

        // string -> double 
        if(sscanf(str.c_str(), "%lf", &d) != 1)
            // error management

This is an error (also shown by cppcheck) because "scanf without field width limits can crash with huge input data on some versions of libc" (see here, and here).

2. Second option: std::sto*()

    #include <iostream>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        try {
            // string -> integer
            int i = std::stoi(str);

            // string -> float
            float f = std::stof(str);

            // string -> double 
            double d = std::stod(str);
        } catch (...) {
            // error management
        }   

This solution is short and elegant, but it is available only on on C++11 compliant compilers.

3. Third option: sstreams

    #include <string>
    #include <sstream>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        std::istringstream ( str ) >> i;

        // string -> float
        std::istringstream ( str ) >> f;

        // string -> double 
        std::istringstream ( str ) >> d;

        // error management ??

However, with this solution is hard to distinguish between bad input (see here).

4. Fourth option: Boost's lexical_cast

    #include <boost/lexical_cast.hpp>
    #include <string>

        std::string str;

        try {
            int i = boost::lexical_cast<int>( str.c_str());
            float f = boost::lexical_cast<int>( str.c_str());
            double d = boost::lexical_cast<int>( str.c_str());
            } catch( boost::bad_lexical_cast const& ) {
                // Error management
        }

However, this is just a wrapper of sstream, and the documentation suggests to use sstream for better error management (see here).

5. Fifth option: strto*()

This solution is very long, due to error management, and it is described here. Since no function returns a plain int, a conversion is needed in case of integer (see here for how this conversion can be achieved).

6. Sixth option: Qt

    #include <QString>
    #include <string>

        bool ok;
        std::string;

        int i = QString::fromStdString(str).toInt(&ok);
        if (!ok)
            // Error management

        float f = QString::fromStdString(str).toFloat(&ok);
        if (!ok)
            // Error management 

        double d = QString::fromStdString(str).toDouble(&ok);
        if (!ok)
    // Error management     

Conclusions

Summing up, the best solution is C++11 std::stoi() or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.

Why does pycharm propose to change method to static

I agree with the answers given here (method does not use self and therefore could be decorated with @staticmethod).

I'd like to add that you maybe want to move the method to a top-level function instead of a static method inside a class. For details see this question and the accepted answer: python - should I use static methods or top-level functions

Moving the method to a top-level function will fix the PyCharm warning, too.

Detecting installed programs via registry

An application does not need to have any registry entry. In fact, many applications do not need to be installed at all. U3 USB sticks are a good example; the programs on them just run from the file system.

As noted, most good applications can be found via their uninstall registry key though. This is actually a pair of keys, per-user and per-machine (HKCU/HKLM - Piskvor mentioned only the HKLM one). It does not (always) give you the install directory, though.

If it's in HKCU, then you have to realise that HKEY_CURRENT_USER really means "Current User". Other users have their own HKCU entries, and their own installed software. You can't find that. Reading every HKEY_USERS hive is a disaster on corporate networks with roaming profiles. You really don't want to fetch 1000 accounts from your remote [US|China|Europe] office.

Even if an application is installed, and you know where, it may not have the same "version" notion you have. The best source is the "version" resource in the executables. That's indeed a plural, so you have to find all of them, extract version resources from all and in case of a conflict decid on something reasonable.

So - good luck. There are dozes of ways to fail.

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

How can I check whether an array is null / empty?

An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.

How to change the size of the font of a JLabel to take the maximum size

label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));

taken from How to Use HTML in Swing Components

What is a JavaBean exactly?

JavaBeans are Java classes which adhere to an extremely simple coding convention. All you have to do is to

  1. implement the java.io.Serializable interface - to save the state of an object
  2. use a public empty argument constructor - to instantiate the object
  3. provide public getter/setter methods - to get and set the values of private variables (properties).

Detecting attribute change of value of an attribute I made

You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

The code here is

$(function() {  
  // Here you register for the event and do whatever you need to do.
  $(document).on('data-attribute-changed', function() {
    var data = $('#contains-data').data('mydata');
    alert('Data changed to: ' + data);
  });

  $('#button').click(function() {
    $('#contains-data').data('mydata', 'foo');
    // Whenever you change the attribute you will user the .trigger
    // method. The name of the event is arbitrary
    $(document).trigger('data-attribute-changed');
  });

   $('#getbutton').click(function() {
    var data = $('#contains-data').data('mydata');
    alert('Data is: ' + data);
  });
});

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Format in other syntax is possible in this way

[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")

How to uninstall / completely remove Oracle 11g (client)?

Assuming a Windows installation, do please refer to this:

http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php

  • Uninstall all Oracle components using the Oracle Universal Installer (OUI).
  • Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
  • Delete any references to Oracle services left behind in the following part of the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora* It should be pretty obvious which ones relate to Oracle.
  • Reboot your machine.
  • Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
  • Delete the "C:\Program Files\Oracle" directory.
  • Empty the contents of your "C:\temp" directory.
  • Empty your recycle bin.

Calling additional attention to some great comments that were left here:

  • Be careful when following anything listed here (above or below), as doing so may remove or damage any other Oracle-installed products.
  • For 64-bit Windows (x64), you need also to delete the HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE key from the registry.
  • Clean-up by removing any related shortcuts that were installed to the Start Menu.
  • Clean-up environment variables:
    • Consider removing %ORACLE_HOME%.
    • Remove any paths no longer needed from %PATH%.

This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.

Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.

(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)

Rails 3.1 and Image Assets

You'll want to change the extension of your css file from .css.scss to .css.scss.erb and do:

background-image:url(<%=asset_path "admin/logo.png"%>);

You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.

In production, make sure

rm -rf public/assets    
bundle exec rake assets:precompile RAILS_ENV=production

happens upon deployment.

JavaScript/jQuery to download file via POST with JSON data

I have been awake for two days now trying to figure out how to download a file using jquery with ajax call. All the support i got could not help my situation until i try this.

Client Side

_x000D_
_x000D_
function exportStaffCSV(t) {_x000D_
   _x000D_
    var postData = { checkOne: t };_x000D_
    $.ajax({_x000D_
        type: "POST",_x000D_
        url: "/Admin/Staff/exportStaffAsCSV",_x000D_
        data: postData,_x000D_
        success: function (data) {_x000D_
            SuccessMessage("file download will start in few second..");_x000D_
            var url = '/Admin/Staff/DownloadCSV?data=' + data;_x000D_
            window.location = url;_x000D_
        },_x000D_
       _x000D_
        traditional: true,_x000D_
        error: function (xhr, status, p3, p4) {_x000D_
            var err = "Error " + " " + status + " " + p3 + " " + p4;_x000D_
            if (xhr.responseText && xhr.responseText[0] == "{")_x000D_
                err = JSON.parse(xhr.responseText).Message;_x000D_
            ErrorMessage(err);_x000D_
        }_x000D_
    });_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Server Side

 [HttpPost]
    public string exportStaffAsCSV(IEnumerable<string> checkOne)
    {
        StringWriter sw = new StringWriter();
        try
        {
            var data = _db.staffInfoes.Where(t => checkOne.Contains(t.staffID)).ToList();
            sw.WriteLine("\"First Name\",\"Last Name\",\"Other Name\",\"Phone Number\",\"Email Address\",\"Contact Address\",\"Date of Joining\"");
            foreach (var item in data)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\"",
                    item.firstName,
                    item.lastName,
                    item.otherName,
                    item.phone,
                    item.email,
                    item.contact_Address,
                    item.doj
                    ));
            }
        }
        catch (Exception e)
        {

        }
        return sw.ToString();

    }

    //On ajax success request, it will be redirected to this method as a Get verb request with the returned date(string)
    public FileContentResult DownloadCSV(string data)
    {
        return File(new System.Text.UTF8Encoding().GetBytes(data), System.Net.Mime.MediaTypeNames.Application.Octet, filename);
        //this method will now return the file for download or open.
    }

Good luck.

grant remote access of MySQL database from any IP address

In website panels like cPanel you may add a single % (percentage sign) in allowed hostnames to access your MySQL database.

By adding a single % you can access your database from any IP or website even from desktop applications.

iPhone App Development on Ubuntu

There are several way to do it, may decide to go the native way by downloading a VM application for linux and the install Mac OS in your VM and then download the Xcode application for mac But the true is i tried this path but it was really long so i decide to get sencha touch and phonegap for mobile phone,here the sencha-touch is a javascript framework that will help you in developing the interfaces and the phonegap is also javascript library which will help to access the feature of your Iphone or any oher mobile platform I'm using sencha-touch and phonegap ,its really work for me

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Reverting single file in SVN to a particular revision

svn revert filename 

this should revert a single file.

How can I get a user's media from Instagram without authenticating as a user?

This works using a simple ajax call and iterating image paths.

        var name = "nasa";
        $.get("https://www.instagram.com/" + name + "/?__a=1", function (data, status) {
            console.log('IG_NODES', data.user.media.nodes);
            $.each(data.user.media.nodes, function (n, item) {
                console.log('ITEMS', item.display_src);
                $('body').append(
                    "<div class='col-md-4'><img class='img-fluid d-block' src='" + item.display_src + "'></div>"
                );
            });
        })

How do I search for names with apostrophe in SQL Server?

SELECT *   FROM Header  WHERE userID LIKE '%' + CHAR(39) + '%' 

Getting today's date in YYYY-MM-DD in Python?

Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

This module is clever enough to understand what you mean.

Just do pip install arrow.

Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternative approaches to dealing with dates in Python. That's mostly what I meant to suggest.

Make Div Draggable using CSS

You can take a look at HTML 5, but I don't think you can restrict the area within you can drag it, just the destination:

http://www.w3schools.com/html/html5_draganddrop.asp

And if you don't mind using some great library, I would encourage you to try Dragula.

Opacity of div's background without affecting contained element in IE 8?

The opacity style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.

The CSS is fairly simple:

.myelement {
    background: rgba(200, 54, 54, 0.5);
}

...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity value.

See this page for more info: http://css-tricks.com/rgba-browser-support/

The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.

The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.

To use CSS3Pie for backgrounds, you need to add a specific -pie-background declaration to your CSS, as well as the PIE behavior style, so your stylesheet would end up looking like this:

.myelement {
    background: rgba(200, 54, 54, 0.5);
    -pie-background:  rgba(200, 54, 54, 0.5);
    behavior: url(PIE.htc);
}

Hope that helps.

[EDIT]

For what it's worth, as others have mentioned, you can use IE's filter style, with the gradient keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)

Calling Java from Python

Pyjnius.

Docs: http://pyjnius.readthedocs.org/en/latest/

Github: https://github.com/kivy/pyjnius

From the github page:

A Python module to access Java classes as Python classes using JNI.

PyJNIus is a "Work In Progress".

Quick overview

>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world') Hello world

>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> print stack.pop() world
>>> print stack.pop() hello

NameError: uninitialized constant (rails)

I had the same error. Turns out in my hasty scaffolding I left out the model.rb file.

python: sys is not defined

In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.

In Python, how do I convert all of the items in a list to floats?

I had to extract numbers first from a list of float strings:

   df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')

then each convert to a float:

   ad=[]
   for z in range(len(df4)):
      ad.append([float(i) for i in df4['sscore'][z]])

in the end assign all floats to a dataframe as float64:

   df4['fscore'] = np.array(ad,dtype=float)

Pretty printing XML with javascript

XMLSpectrum formats XML, supports attribute indentation and also does syntax-highlighting for XML and any embedded XPath expressions:

XMLSpectrum formatted XML

XMLSpectrum is an open source project, coded in XSLT 2.0 - so you can run this server-side with a processor such as Saxon-HE (recommended) or client-side using Saxon-CE.

XMLSpectrum is not yet optimised to run in the browser - hence the recommendation to run this server-side.

Maven with Eclipse Juno

From Eclipse

  • Go to Help
  • Eclipse Marketplace
  • Search for m2e or maven integration for eclipse
  • click on Install against - 'Maven Integration for Eclipse (Juno and newer) 1.4'
  • Restart and Enjoy!!!

Why can't I make a vector of references?

As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.

You can do something like the following:

vector<int*> iarray;
int default_item = 0; // for handling out-of-range exception

int& get_item_as_ref(unsigned int idx) {
   // handling out-of-range exception
   if(idx >= iarray.size()) 
      return default_item;
   return reinterpret_cast<int&>(*iarray[idx]);
}

Adding minutes to date time in PHP

I don't know why the approach set as solution didn't work for me. So I'm posting here what worked for me in hope it can help anybody:

$startTime = date("Y-m-d H:i:s");

//display the starting time
echo '> '.$startTime . "<br>";

//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));

//display the converted time
echo '> '.$convertedTime;

Is it possible to CONTINUE a loop from an exception?

In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.

You also need to SELECT INTO a variable inside your BEGIN block:

SELECT attr INTO v_attr FROM attribute_table...

Obviously you must declare v_attr as well...

How to restart a single container with docker-compose

The answer's here are talking about the reflection of the change on the docker-compose.yml file.

But what if I want to incorporate the changes I have done in my code, and I believe that will be only possible by rebuilding the image and that I do with following commands

1. docker container stop

docker stop container-id

2. docker container removal

docker rm container-id

3. docker image removal

docker rmi image-id

4. compose the container again

docker-compose up container-name

How can I loop through all rows of a table? (MySQL)

    Use this:

    $stmt = $user->runQuery("SELECT * FROM tbl WHERE ID=:id");
    $stmt->bindparam(":id",$id);
    $stmt->execute();

        $stmt->bindColumn("a_b",$xx);
        $stmt->bindColumn("c_d",$yy);


    while($rows = $stmt->fetch(PDO::FETCH_BOUND))
    {
        //---insert into new tble
    }   

@Autowired - No qualifying bean of type found for dependency at least 1 bean

In your controller class, just add @ComponentScan("package") annotation. In my case the package name is com.shoppingcart.So i wrote the code as @ComponentScan("com.shoppingcart") and it worked for me.

Angular JS POST request not sending JSON data

$http({
    url: '/api/user',
    method: "POST",
    data: angular.toJson(yourData)
}).success(function (data, status, headers, config) {
    $scope.users = data.users;
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

how to move elasticsearch data from one server to another

If you simply need to transfer data from one elasticsearch server to another, you could also use elasticsearch-document-transfer.

Steps:

  1. Open a directory in your terminal and run
    $ npm install elasticsearch-document-transfer.
  2. Create a file config.js
  3. Add the connection details of both elasticsearch servers in config.js
  4. Set appropriate values in options.js
  5. Run in the terminal
    $ node index.js

Lost connection to MySQL server during query?

I was getting this error with a "broken pipe" when I tried to do bulk inserts with millions of records. I ended up solving this by chunking my data into smaller batch sizes and then running an executemany command with the mysql cursor for each of the inserts I needed to do. This solved the problem and didn't seem to affect the performance in any noticeable way.

eg.

def chunks(data):
    for i in range(0, len(data), CHUNK_SIZE):
        yield data[i:i + CHUNK_SIZE]


def bulk_import(update_list):
    new_list = list(chunks(update_list))
    for batch in new_list:
         cursor.execute(#SQL STATEMENT HERE)

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

Open file by its full path in C++

For those who are getting the path dynamicly... e.g. drag&drop:

Some main constructions get drag&dropped file with double quotes like:

"C:\MyPath\MyFile.txt"

Quick and nice solution is to use this function to remove chars from string:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
} 

string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );

myAbsolutepath now contains just C:\MyPath\MyFile.txt

The function needs these libraries: <iostream> <algorithm> <cstring>.
The function was based on this answer.

Working Fiddle: http://ideone.com/XOROjq

"unrecognized selector sent to instance" error in Objective-C

I think you should use the void, instead of the IBAction in return type. because you defined a button programmatically.

Difference between the Apache HTTP Server and Apache Tomcat?

  1. Apache is a general-purpose http server, which supports a number of advanced options that Tomcat doesn't.
  2. Although Tomcat can be used as a general purpose http server, you can also set up Apache and Tomcat to work together with Apache serving static content and forwarding the requests for dynamic content to Tomcat.

Salt and hash a password in Python

I don' want to resurrect an old thread, but... anyone who wants to use a modern up to date secure solution, use argon2.

https://pypi.python.org/pypi/argon2_cffi

It won the the password hashing competition. ( https://password-hashing.net/ ) It is easier to use than bcrypt, and it is more secure than bcrypt.

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

Try this, It worked for me

SELECT * FROM (
            SELECT
                [Code],
                [Name],
                [CategoryCode],
                [CreatedDate],
                [ModifiedDate],
                [CreatedBy],
                [ModifiedBy],
                [IsActive],
                ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
            FROM MasterTable
          ) a
        WHERE rownumber = 1 

How to switch position of two items in a Python list?

for i in range(len(arr)):
    if l[-1] > l[i]:
        l[-1], l[i] = l[i], l[-1]
        break

as a result of this if last element is greater than element at position i then they both get swapped .

Extract source code from .jar file

AndroChef Java Decompiler produces very good code that you can use directly in your projects...

<img>: Unsafe value used in a resource URL context

The most elegant way to fix this: use pipe. Here is example (my blog). So you can then simply use url | safe pipe to bypass the security.

<iframe [src]="url | safe"></iframe>

Refer to the documentation on npm for details: https://www.npmjs.com/package/safe-pipe

How to create a label inside an <input> element?

<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">

Add an onblur event too.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Test if a command outputs an empty string

Sometimes you want to save the output, if it's non-empty, to pass it to another command. If so, you could use something like

list=`grep -l "MY_DESIRED_STRING" *.log `
if [ $? -eq 0 ]
then
    /bin/rm $list
fi

This way, the rm command won't hang if the list is empty.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Using Tomcat 7 under Linux, this did the trick.

String certificatesTrustStorePath = "/etc/alternatives/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Under Linux, $JAVA_HOME is not always setup, but usually /etc/alternatives/jre points to $JAVA_HOME/jre

How to get the current location in Google Maps Android API v2?

the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.

this is answer is completely from this guide on google developers

so here is step by step guide:

  1. implement all this in your map activity

    MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

  2. in your onCreate:

    private GoogleMap mMap;
    private Context context;
    private TextView txtStartPoint,txtEndPoint;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastKnownLocation;
    private LatLng mDefaultLocation;
    private CameraPosition mCameraPosition;
    private boolean mLocationPermissionGranted;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    context = this;
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();
    mGoogleApiClient.connect();
    }
    
  3. in your onConnected :

    SupportMapFragment mapFragment = (SupportMapFragment)     getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);
    
  4. in your onMapReady :

    @Override
    public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    
    // Do other setup activities here too, as described elsewhere in this tutorial.
    
    // Turn on the My Location layer and the related control on the map.
    updateLocationUI();
    
    // Get the current location of the device and set the position of the map.
    getDeviceLocation();
    }
    
  5. and these two are methods in onMapReady :

    private void updateLocationUI() {
      if (mMap == null) {
        return;
    }
    
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    }
    
    if (mLocationPermissionGranted) {
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    } else {
        mMap.setMyLocationEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        mLastKnownLocation = null;
    }
    }
    
    private void getDeviceLocation() {
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    }
    
    if (mLocationPermissionGranted) {
        mLastKnownLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);
    }
    
    // Set the map's camera position to the current location of the device.
    float DEFAULT_ZOOM = 15;
    if (mCameraPosition != null) {
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
    } else if (mLastKnownLocation != null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(mLastKnownLocation.getLatitude(),
                        mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
    } else {
        Log.d("pouya", "Current location is null. Using defaults.");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
    }
    }
    

this is very fast , smooth and effective. hope this helps

Uncaught TypeError: undefined is not a function while using jQuery UI

And if you have this problem in slider or slideshow you must use jquery.easing.1.3:

<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>

How to get the full URL of a Drupal page?

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Twitter Bootstrap scrollable table rows and fixed header

Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/

Usage:

$('selector').fixedHeaderTable({ fixedColumn: 1 });

Set the fixedColumn option if you want any number of columns to be also fixed for horizontal scrolling.

EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.

EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)

Simple DateTime sql query

SELECT * 
  FROM TABLENAME 
 WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
   AND [DateTime] <= '2011-05-25 3:35:04 AM'

If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

data.matrix(SFI)

From ?data.matrix:

Description:

 Return the matrix obtained by converting all the variables in a
 data frame to numeric mode and then binding them together as the
 columns of a matrix.  Factors and ordered factors are replaced by
 their internal codes.

Angles between two n-dimensional vectors in Python

import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

Populating a database in a Laravel migration file

This should do what you want.

public function up()
{
    DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}

Java Minimum and Maximum values in Array

Here you haven't print the max and min values. Print the max and min values in the getMaxVal and getMin val methods or after the call. This is the output.

Enter the numbers now.
5
Max: 5
Min: 0
3
Max: 5
Min: 0
7
Max: 7
Min: 0
3
Max: 7
Min: 0
90
Max: 90
Min: 0
43
Max: 90
Min: 0
100
Max: 100
Min: 0
45
Max: 100
Min: 0
23
Max: 100
Min: 0
22
Max: 100
Min: 3
These are the numbers you have entered.
5 3 7 3 90 43 100 45 23 22

Also when you are declaring an array, it has all 0s initially.

Upgrade version of Pandas

try

pip3 install --upgrade pandas

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

Just remove

 <authorization>
      <deny users="?"/>
    </authorization>

from your web.config file

that did for me

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The following worked for me

import java.time.*;
import java.time.format.*;

public class Times {

  public static void main(String[] args) {
    final String dateTime = "2012-02-22T02:06:58.147Z";
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
    System.out.println(parsed.toLocalDateTime());
  }
}

and gave me output as

2012-02-22T02:06:58.147

jQuery loop over JSON result from AJAX Success?

If you use Fire Fox, just open up a console (use F12 key) and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

Java substring: 'string index out of range'

I"m guessing i'm getting this error because the string is trying to substring a Null value. But wouldn't the ".length() > 0" part eliminate that issue?

No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
    value = "_";
} else if (itemdescription.length() <= 38) {
    value = itemdescription;
} else { 
    value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);

Might be a good place for a utility function if you do that a lot...

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

Why does it work in Chrome and not Firefox?

The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS requests returning a status of 401 still send the subsequent request.

Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.

How can I get the OPTIONS request to send and respond consistently?

Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.

How to initialize a list with constructor?

You can initialize it just like any list:

public List<ContactNumber> ContactNumbers { get; set; }

public Human(int id)
{
    Id = id;
    ContactNumbers = new List<ContactNumber>();
}

public Human(int id, string address, string name) :this(id)
{
    Address = address;
    Name = name;
    // no need to initialize the list here since you're
    // already calling the single parameter constructor
}       

However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:

public List<ContactNumber> ContactNumbers { get; private set; }

How do I use this JavaScript variable in HTML?

Try this:

<body>
    <div id="divMsg"></div>
</body>
<script>
    var name = prompt("What's your name?");
    var lengthOfName = name.length;
    document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>

Iterate keys in a C++ map

You are looking for map_keys, with it you can write things like

BOOST_FOREACH(const key_t key, the_map | boost::adaptors::map_keys)
{
  // do something with key
}

OS X Terminal UTF-8 issues

In my case, simply using the uxterm command instead of xterm solved the problem. It's available in /opt/X11/bin/uxterm by installing the XQuartz package provided by Apple.

What are the basic rules and idioms for operator overloading?

Common operators to overload

Most of the work in overloading operators is boiler-plate code. That is little wonder, since operators are merely syntactic sugar, their actual work could be done by (and often is forwarded to) plain functions. But it is important that you get this boiler-plate code right. If you fail, either your operator’s code won’t compile or your users’ code won’t compile or your users’ code will behave surprisingly.

Assignment Operator

There's a lot to be said about assignment. However, most of it has already been said in GMan's famous Copy-And-Swap FAQ, so I'll skip most of it here, only listing the perfect assignment operator for reference:

X& X::operator=(X rhs)
{
  swap(rhs);
  return *this;
}

Bitshift Operators (used for Stream I/O)

The bitshift operators << and >>, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications. For guidance overloading as bit-manipulation operators, see the section below on Binary Arithmetic Operators. For implementing your own custom format and parsing logic when your object is used with iostreams, continue.

The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax specifies no restriction on whether they should be members or non-members. Since they change their left argument (they alter the stream’s state), they should, according to the rules of thumb, be implemented as members of their left operand’s type. However, their left operands are streams from the standard library, and while most of the stream output and input operators defined by the standard library are indeed defined as members of the stream classes, when you implement output and input operations for your own types, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions. The canonical forms of the two are these:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream

  return os;
}

std::istream& operator>>(std::istream& is, T& obj)
{
  // read obj from stream

  if( /* no valid object of T found in stream */ )
    is.setstate(std::ios::failbit);

  return is;
}

When implementing operator>>, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.

Function call operator

The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit this argument of member functions. Other than this, it can be overloaded to take any number of additional arguments, including zero.

Here's an example of the syntax:

class foo {
public:
    // Overloaded call operator
    int operator()(const std::string& y) {
        // ...
    }
};

Usage:

foo f;
int a = f("hello");

Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.

Comparison operators

The binary infix comparison operators should, according to the rules of thumb, be implemented as non-member functions1. The unary prefix negation ! should (according to the same rules) be implemented as a member function. (but it is usually not a good idea to overload it.)

The standard library’s algorithms (e.g. std::sort()) and types (e.g. std::map) will always only expect operator< to be present. However, the users of your type will expect all the other operators to be present, too, so if you define operator<, be sure to follow the third fundamental rule of operator overloading and also define all the other boolean comparison operators. The canonical way to implement them is this:

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return  operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}

The important thing to note here is that only two of these operators actually do anything, the others are just forwarding their arguments to either of these two to do the actual work.

The syntax for overloading the remaining binary boolean operators (||, &&) follows the rules of the comparison operators. However, it is very unlikely that you would find a reasonable use case for these2.

1 As with all rules of thumb, sometimes there might be reasons to break this one, too. If so, do not forget that the left-hand operand of the binary comparison operators, which for member functions will be *this, needs to be const, too. So a comparison operator implemented as a member function would have to have this signature:

bool operator<(const X& rhs) const { /* do actual comparison with *this */ }

(Note the const at the end.)

2 It should be noted that the built-in version of || and && use shortcut semantics. While the user defined ones (because they are syntactic sugar for method calls) do not use shortcut semantics. User will expect these operators to have shortcut semantics, and their code may depend on it, Therefore it is highly advised NEVER to define them.

Arithmetic Operators

Unary arithmetic operators

The unary increment and decrement operators come in both prefix and postfix flavor. To tell one from the other, the postfix variants take an additional dummy int argument. If you overload increment or decrement, be sure to always implement both prefix and postfix versions. Here is the canonical implementation of increment, decrement follows the same rules:

class X {
  X& operator++()
  {
    // do actual increment
    return *this;
  }
  X operator++(int)
  {
    X tmp(*this);
    operator++();
    return tmp;
  }
};

Note that the postfix variant is implemented in terms of prefix. Also note that postfix does an extra copy.2

Overloading unary minus and plus is not very common and probably best avoided. If needed, they should probably be overloaded as member functions.

2 Also note that the postfix variant does more work and is therefore less efficient to use than the prefix variant. This is a good reason to generally prefer prefix increment over postfix increment. While compilers can usually optimize away the additional work of postfix increment for built-in types, they might not be able to do the same for user-defined types (which could be something as innocently looking as a list iterator). Once you got used to do i++, it becomes very hard to remember to do ++i instead when i is not of a built-in type (plus you'd have to change code when changing a type), so it is better to make a habit of always using prefix increment, unless postfix is explicitly needed.

Binary arithmetic operators

For the binary arithmetic operators, do not forget to obey the third basic rule operator overloading: If you provide +, also provide +=, if you provide -, do not omit -=, etc. Andrew Koenig is said to have been the first to observe that the compound assignment operators can be used as a base for their non-compound counterparts. That is, operator + is implemented in terms of +=, - is implemented in terms of -= etc.

According to our rules of thumb, + and its companions should be non-members, while their compound assignment counterparts (+= etc.), changing their left argument, should be a member. Here is the exemplary code for += and +; the other binary arithmetic operators should be implemented in the same way:

class X {
  X& operator+=(const X& rhs)
  {
    // actual addition of rhs to *this
    return *this;
  }
};
inline X operator+(X lhs, const X& rhs)
{
  lhs += rhs;
  return lhs;
}

operator+= returns its result per reference, while operator+ returns a copy of its result. Of course, returning a reference is usually more efficient than returning a copy, but in the case of operator+, there is no way around the copying. When you write a + b, you expect the result to be a new value, which is why operator+ has to return a new value.3 Also note that operator+ takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator= taking its argument per copy.

The bit manipulation operators ~ & | ^ << >> should be implemented in the same way as the arithmetic operators. However, (except for overloading << and >> for output and input) there are very few reasonable use cases for overloading these.

3 Again, the lesson to be taken from this is that a += b is, in general, more efficient than a + b and should be preferred if possible.

Array Subscripting

The array subscript operator is a binary operator which must be implemented as a class member. It is used for container-like types that allow access to their data elements by a key. The canonical form of providing these is this:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Unless you do not want users of your class to be able to change data elements returned by operator[] (in which case you can omit the non-const variant), you should always provide both variants of the operator.

If value_type is known to refer to a built-in type, the const variant of the operator should better return a copy instead of a const reference:

class X {
  value_type& operator[](index_type idx);
  value_type  operator[](index_type idx) const;
  // ...
};

Operators for Pointer-like Types

For defining your own iterators or smart pointers, you have to overload the unary prefix dereference operator * and the binary infix pointer member access operator ->:

class my_ptr {
        value_type& operator*();
  const value_type& operator*() const;
        value_type* operator->();
  const value_type* operator->() const;
};

Note that these, too, will almost always need both a const and a non-const version. For the -> operator, if value_type is of class (or struct or union) type, another operator->() is called recursively, until an operator->() returns a value of non-class type.

The unary address-of operator should never be overloaded.

For operator->*() see this question. It's rarely used and thus rarely ever overloaded. In fact, even iterators do not overload it.


Continue to Conversion Operators

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

Dynamically updating css in Angular 2

To use % instead of px or em with @Gaurav's answer, it's just

<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Difference in Months between two dates in JavaScript

Consider each date in terms of months, then subtract to find the difference.

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

This will get you the difference of months between the two dates, ignoring the days.

javascript regular expression to check for IP addresses

If you want something more readable than regex for ipv4 in modern browsers you can go with

function checkIsIPV4(entry) {
  var blocks = entry.split(".");
  if(blocks.length === 4) {
    return blocks.every(function(block) {
      return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
    });
  }
  return false;
}

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

Read input stream twice

How about:

if (stream.markSupported() == false) {

        // lets replace the stream object
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        stream.close();
        stream = new ByteArrayInputStream(baos.toByteArray());
        // now the stream should support 'mark' and 'reset'

    }

MySQL my.cnf file - Found option without preceding group

I had this problem when I installed MySQL 8.0.15 with the community installer. The my.ini file that came with the installer did not work correctly after it had been edited. I did a full manual install by downloading that zip folder. I was able to create my own my.ini file containing only the parameters that I was concerned about and it worked.

  1. download zip file from MySQL website
  2. unpack the folder into C:\program files\MySQL\MySQL8.0
  3. within the MySQL8.0 folder that you unpacked the zip folder into, create a text file and save it as my.ini
  4. include the parameters in that my.ini file that you are concerned about. so something like this(just ensure that there is already a folder created for the datadir or else initialization won't work):

    [mysqld]
    basedire=C:\program files\MySQL\MySQL8.0
    datadir=D:\MySQL\Data
    ....continue with whatever parameters you want to include
    
  5. initialize the data directory by running these two commands in the command prompt:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --default-file=C:\program files\MySQL\MySQL8.0\my.ini --initialize
    
  6. install the MySQL server as a service by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --install --default-file=C:\program files\MySQL\MySQL8.0\my.ini
    
  7. finally, start the server for the first time by running these two commands:

    cd C:\program files\MySQL\MySQL8.0\bin
    mysqld --console
    

Why does configure say no C compiler found when GCC is installed?

try yum groupinstall "Development Tools"

if the installation is success then you will have a full set of development tools. Such as gcc, g++, make, ld ect. After that you can try the compilation of Code Blocks again.

Since yum is deprecated you can use dnf instead:

dnf groupinstall "Development Tools"

Switch statement equivalent in Windows batch file

I searched switch / case in batch files today and stumbled upon this. I used this solution and extended it with a goto exit.

IF "%1"=="red" echo "one selected" & goto exit
IF "%1"=="two" echo "two selected" & goto exit
...

echo "Options: [one | two | ...]

:exit 

Which brings in the default state (echo line) and no extra if's when the choice is found.

Which is the preferred way to concatenate a string in Python?

While somewhat dated, Code Like a Pythonista: Idiomatic Python recommends join() over + in this section. As does PythonSpeedPerformanceTips in its section on string concatenation, with the following disclaimer:

The accuracy of this section is disputed with respect to later versions of Python. In CPython 2.5, string concatenation is fairly fast, although this may not apply likewise to other Python implementations. See ConcatenationTestCode for a discussion.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Maybe a bit late, but I found this answer looking over the internet. It could help others with the same problem.

$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

Now you should be able to log in as root in phpmyadmin.

(Found here.)

Find row in datatable with specific id

Try avoiding unnecessary loops and go for this if needed.

string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
    //your logic goes here
}
else
{
    //your logic goes here
}

If you want to search by specific ID then there should be a primary key in a table.

Firebase: how to generate a unique numeric ID for key?

Adding to the @htafoya answer. The code snippet will be

const getTimeEpoch = () => {
    return new Date().getTime().toString();                             
}

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

  1. First make sure you have MinGW installed.
  2. From MinGW installation manager check if you have the mingw32-make package installed.
  3. Check if you have added the MinGW bin folder to your PATH. type PATH in your command line and look for the folder. Or on windows 10 go to Control Panel\System and Security\System --> Advanced system settings --> Environment Variables --> System Variables find Path variable, select, Edit and check if it is there. If not just add it!
  4. As explained here, create a new file in any of your PATH folders. For example create mingwstartup.bat in the MinGW bin folder. write the line doskey make=mingw32-make.exe inside, save and close it.
  5. open Registry Editor by running regedit. As explained here in HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER go to \Software\Microsoft\Command Processor right click on the right panel New --> Expandable String Value and name it AutoRun. double click and enter the path to your .bat file as the Value data (e.g. "C:\MinGW\bin\mingwstartup.bat") the result should look like this:

enter image description here

now every time you open a new terminal make command will run the mingw32-make.exe. I hope it helps.

P.S. If you don't want to see the commands of the .bat file to be printed out to the terminal put @echo off at the top of the batch file.

Double border with different color

Maybe use outline property

    <div class="borders">
      Hello
    </div>

    .borders{
    border: 1px solid grey; 
    outline: 2px solid white;
     }

https://jsfiddle.net/Ivan5646/5eunf13f/

How do I save a String to a text file using Java?

I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.

How can I copy the output of a command directly into my clipboard?

I usually run this command when I have to copy my ssh-key:

cat ~/.ssh/id_rsa.pub | pbcopy

ctrl+v anywhere else.

Count items in a folder with PowerShell

Only Files

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

Only Folders

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

Both

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}

Angular - How to apply [ngStyle] conditions

You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You can send the file and data over in one request using the multipart/form-data content type:

In many applications, it is possible for a user to be presented with a form. The user will fill out the form, including information that is typed, generated by user input, or included from files that the user has selected. When the form is filled out, the data from the form is sent from the user to the receiving application.

The definition of MultiPart/Form-Data is derived from one of those applications...

From http://www.faqs.org/rfcs/rfc2388.html:

"multipart/form-data" contains a series of parts. Each part is expected to contain a content-disposition header [RFC 2183] where the disposition type is "form-data", and where the disposition contains an (additional) parameter of "name", where the value of that parameter is the original field name in the form. For example, a part might contain a header:

Content-Disposition: form-data; name="user"

with the value corresponding to the entry of the "user" field.

You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.

The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.

Git 'fatal: Unable to write new index file'

Here is what worked for me:

Context:

  1. Building a project on a server

  2. git status returns a HEAD detached at <commit-SHA>

  3. What ever operation I did locally, I had this error. More specifically:

    • git checkout
    • git reset HEAD --hard

Solution

  1. Simply removed file <work-dir>/.git/index.
  2. A git status would indicate that all files in the projet are not tracked (no surprise here).
  3. git reset HEAD --hard
  4. Back to HEAD detached at <commit-SHA> when doing a git status, but then you should be able to
  5. git checkout <some-branch>

and you're back on track!

!! IMPORTANT !!

This works only because I am "merly" building. No precious modification has been performed on the code. If you are actually in "dev-time", then I would recommand to save your work first or go for another method.

Hope it will help :).

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

Jackson serialization: ignore empty values (or null)

You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

What is object slicing?

Third match in google for "C++ slicing" gives me this Wikipedia article http://en.wikipedia.org/wiki/Object_slicing and this (heated, but the first few posts define the problem) : http://bytes.com/forum/thread163565.html

So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets "sliced off".

If those links don't give enough info for a "good answer" please edit your question to let us know what more you're looking for.

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

Getting the last revision number in SVN?

I think you are looking for

svn info -r HEAD

Can you shell to that command?

You'll probably need to supply login credentials with the repository as well.

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

How to open remote files in sublime text 3

On macOS, one option is to install FUSE for macOS and use sshfs to mount a remote directory:

mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir

Some caveats apply with mounting network volumes, so YMMV.

How can I parse a String to BigDecimal?

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

MySQL: Check if the user exists and drop it

in terminal do:

sudo mysql -u root -p

enter the password.

select user from mysql.user;

now delete the user 'the_username'

DROP USER the_unername;

replace 'the_username' with the user that you want to delete.

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

Add / Change parameter of URL and redirect to the new URL

i would suggest a little change to @Lajos's answer... in my particular situation i could potentially have a hash as part of the url, which will cause problems for parsing the parameter that we're inserting with this method after the redirect.

function setGetParameter(paramName, paramValue) {
    var url = window.location.href.replace(window.location.hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName));
        var suffix = url.substring(url.indexOf(paramName));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    }else {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + paramValue;
        else
            url += "&" + paramName + "=" + paramValue;
    }
    url += window.location.hash;
    window.location.href = url;
}

Remove the last chars of the Java String variable

path = path.substring(0, path.length() - 5);

HTML5 phone number validation with pattern

How about this? /(7|8|9)\d{9}/

It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.

Change language of Visual Studio 2017 RC

I didn't find a complete answer here

Firstly

You should install your preferred language

  1. Open the Visual Studio Installer.
  2. In installed products click on plus Dropdown menu
  3. click edit
  4. then click on language packs
  5. choose you preferred language and finally click on install

Secondly

  1. Go to Tools -> Options

    2.Select International Settings in Environment

    3.click on Menu and select you preferred language

    4.Click on Ok

    5.restart visual studio

Get Absolute Position of element within the window in wpf

To get the absolute position of an UI element within the window you can use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d));

If you are within an User Control, and simply want relative position of the UI element within that control, simply use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));

position.X -= controlPosition.X;
position.Y -= controlPosition.Y;

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).

// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

npm ERR! Error: EPERM: operation not permitted, rename

Not package.json, but for whatever reason, my node_modules/ had become read-only. Resetting that fixed this.

Equivalent of String.format in jQuery

Way past the late season but I've just been looking at the answers given and have my tuppence worth:

Usage:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

Method:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

Result:

"aalert" is not defined
3.14 3.14 a{2}bc foo

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

Find Java classes implementing an interface

I really like the reflections library for doing this.

It provides a lot of different types of scanners (getTypesAnnotatedWith, getSubTypesOf, etc), and it is dead simple to write or extend your own.

Check if cookies are enabled

You cannot in the same page's loading set and check if cookies is set you must perform reload page:

  • PHP run at Server;
  • cookies at client.
  • cookies sent to server only during loading of a page.
  • Just created cookies have not been sent to server yet and will be sent only at next load of the page.

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Set NA to 0 in R

To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.

For instance, adding two columns (A and B) together from a data frame dfr:

temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')

When I do this I throw away the intermediate afterwards with remove/rm.

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

How to get the path of the batch script in Windows?

You can use %~dp0, d means the drive only, p means the path only, 0 is the argument for the full filename of the batch file.

For example if the file path was C:\Users\Oliver\Desktop\example.bat then the argument would equal C:\Users\Oliver\Desktop\, also you can use the command set cpath=%~dp0 && set cpath=%cpath:~0,-1% and use the %cpath% variable to remove the trailing slash.

Mongoose: Get full list of users

My Solution

User.find()
        .exec()
        .then(users => {
            const response = {
                count: users.length,
                users: users.map(user => {

                    return {
                        _id: user._id,
                        // other property
                    }

                })

            };
            res.status(200).json(response);
        }).catch(err => {
        console.log(err);
        res.status(500).json({
            success: false
        })
    })

Remove non-ASCII characters from CSV

I tried all the solutions and nothing worked. The following, however, does:

tr -cd '\11\12\15\40-\176'

Which I found here:

https://alvinalexander.com/blog/post/linux-unix/how-remove-non-printable-ascii-characters-file-unix

My problem needed it in a series of piped programs, not directly from a file, so modify as needed.

Validate Dynamically Added Input fields

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate();
    });

    function addInput() {

        var indexVal = $("#index").val();
        var index = parseInt(indexVal) + 1
        var obj = '<input id="list'+index+'" name=list['+index+']  class="required" />'
        $("#parent").append(obj);

        $("#list"+index).rules("add", "required");
        $("#index").val(index)
    }
</script>

<form id="commentForm" method="get" action="">
    <input type="hidden" name="index" name="list[1]" id="index" value="1">
    <p id="parent">
        <input id="list1"  class="required" />
    </p>
    <input class="submit" type="submit" value="Submit"/>
    <input type="button" value="add" onClick="addInput()" />
</form>

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

Since your integer array cannot contain a value larger than Integer.MAX_VALUE and smaller than Integer.MIN_VALUE your code works across all edge cases.

localhost refused to connect Error in visual studio

I ran into a similar problem when I started working this morning, using Visual Studio Community 2019, Debug configuration. The IIS Express (Google Chrome) site was unreachable. When I terminated program execution via the red stop button in Visual Studio, I was rewarded with a windows error message stating "process with an id of 4### is not running".

The computer had been left on overnight.

I looked through the answers here and the solutions looked complicated. I tried closing and reopening the solution, restarting Visual Studio and, finally, restarting the computer.

Restarting the computer resolved my issue. I did not delete any files or change any other settings.

Java Compare Two Lists

Using java 8 removeIf

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.

I can also recommend this blog post for other solutions:

http://www.kianryan.co.uk/2013/03/orphaned-child/

Code:

public class Child
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Heading { get; set; }
    //Add other properties here.

    [Key, Column(Order = 1)]
    public int ParentId { get; set; }

    public virtual Parent Parent { get; set; }
}

Format y axis as percent

I'm late to the game but I just realize this: ax can be replaced with plt.gca() for those who are not using axes and just subplots.

Echoing @Mad Physicist answer, using the package PercentFormatter it would be:

import matplotlib.ticker as mtick

plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))
#if you already have ticks in the 0 to 1 range. Otherwise see their answer

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

This happens when you are trying to run application on emulator. Emulator does not have shared google maps library.

How to write a caption under an image?

CSS

#images{
    text-align:center;
    margin:50px auto; 
}
#images a{
    margin:0px 20px;
    display:inline-block;
    text-decoration:none;
    color:black;
 }

HTML

<div id="images">
    <a href="http://xyz.com/hello">
        <img src="hello.png" width="100px" height="100px">
        <div class="caption">Caption 1</div>
    </a>
    <a href="http://xyz.com/hi">
        <img src="hi.png" width="100px" height="100px"> 
        <div class="caption">Caption 2</div>
    </a>
</div>?

?A fiddle is here.