Programs & Examples On #Modularity

Modularity describes the degree to which a system’s components may be separated and recombined. It refers to both the tightness of coupling between components, and the degree to which the “rules” of the system architecture enable (or prohibit) the mixing and matching of components.

Response.Redirect with POST instead of Get?

Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.

How can I sanitize user input with PHP?

It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called magic-quotes, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).

What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.

Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.

A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.

Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, json_encode() that will correctly format every bit of data.

And so on and so forth ...

The only case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

Offset a background image from the right using CSS

I found this CSS3 feature helpful:

/* to position the element 10px from the right */
background-position: right 10px top;

As far as I know this is not supported in IE8. In latest Chrome/Firefox it works fine.

See Can I use for details on the supported browsers.

Used source: http://tanalin.com/en/blog/2011/09/css3-background-position/

Update:

This feature is now supported in all major browsers, including mobile browsers.

Create a root password for PHPMyAdmin

Open phpMyAdmin and select the SQL tab. Then type this command:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_root_password');

Also change to this line in config.inc.php:

$cfg['Servers'][$i]['auth_type'] = 'cookie';

To make phpMyAdmin prompts for your MySQL username and password.

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

The Role Manager feature has not been enabled

If you are using ASP.NET Identity UserManager you can get it like this as well:

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

var roles = userManager.GetRoles(User.Identity.GetUserId());

If you have changed key for user from Guid to Int for example use this code:

var roles = userManager.GetRoles(User.Identity.GetUserId<int>());

How to make --no-ri --no-rdoc the default for gem install?

For Windows users, Ruby doesn't set up .gemrc file. So you have to create .gemrc file in your home directory (echo %USERPROFILE%) and put following line in it:

gem: --no-document

As already mentioned in previous answers, don't use --no-ri and --no-rdoc cause its deprecated. See it yourself:

gem help install

How do I install SciPy on 64 bit Windows?

Short answer: Windows 64 bit support is still work in progress at this time. The superpack will certainly not work on a 64-bits Python (but it should work fine on a 32 bits Python, even on Windows 64 bit).

The main issue with Windows 64 bit is that building with mingw-w64 is not stable at this point: it may be our's (NumPy developers) fault, Python's fault or mingw-w64. Most likely a combination of all those :). So you have to use proprietary compilers: anything other than the Microsoft compiler crashes NumPy randomly; for the Fortran compiler, ifort is the one to use. As of today, both NumPy and SciPy source code can be compiled with Visual Studio 2008 and ifort (all tests passing), but building it is still quite a pain, and not well supported by the NumPy build infrastructure.

How to run a stored procedure in oracle sql developer?

Try to execute the procedure like this,

var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

MySQL config file location - redhat linux server

In the docker containers(centos based images) it is located at

/etc/mysql/my.cnf

Display an array in a readable/hierarchical format

if someone needs to view arrays so cool ;) use this method.. this will print to your browser console

function console($obj)
{
    $js = json_encode($obj);
    print_r('<script>console.log('.$js.')</script>');
}

you can use like this..

console($myObject);

Output will be like this.. so cool eh !!

enter image description here

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How do I declare a global variable in VBA?

If this function is in a module/class, you could just write them outside of the function, so it has Global Scope. Global Scope means the variable can be accessed by another function in the same module/class (if you use dim as declaration statement, use public if you want the variables can be accessed by all function in all modules) :

Dim iRaw As Integer
Dim iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1
End Function

Function this_can_access_global()
    iRaw = 2
    iColumn = 2
End Function

Can the Unix list command 'ls' output numerical chmod permissions?

You don't use ls to get a file's permission information. You use the stat command. It will give you the numerical values you want. The "Unix Way" says that you should invent your own script using ls (or 'echo *') and stat and whatever else you like to give the information in the format you desire.

Maven: add a dependency to a jar by relative path

This is working for me: Let's say I have this dependency

<dependency>
    <groupId>com.company.app</groupId>
    <artifactId>my-library</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/my-library.jar</systemPath>
</dependency>

Then, add the class-path for your system dependency manually like this

<Class-Path>libs/my-library-1.0.jar</Class-Path>

Full config:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifestEntries>
                <Build-Jdk>${jdk.version}</Build-Jdk>
                <Implementation-Title>${project.name}</Implementation-Title>
                <Implementation-Version>${project.version}</Implementation-Version>
                <Specification-Title>${project.name} Library</Specification-Title>
                <Specification-Version>${project.version}</Specification-Version>
                <Class-Path>libs/my-library-1.0.jar</Class-Path>
            </manifestEntries>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.company.app.MainClass</mainClass>
                <classpathPrefix>libs/</classpathPrefix>
            </manifest>
        </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/libs/</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

How to hide image broken Icon using only CSS/HTML?

Despite what people are saying here, you don't need JavaScript at all, you don't even need CSS!!

It's actually very doable and simple with HTML only. You can even show a default image if an image doesn't load. Here's how...

This also works on all browsers, even as far back as IE8 (out of 250,000+ visitors to sites I hosted in September 2015, ZERO people used something worse than IE8, meaning this solution works for literally everything).

Step 1: Reference the image as an object instead of an img. When objects fail they don't show broken icons; they just do nothing. Starting with IE8, you can use Object and Img tags interchangeably. You can resize and do all the glorious stuff you can with regular images too. Don't be afraid of the object tag; it's just a tag, nothing big and bulky gets loaded and it doesn't slow down anything. You'll just be using the img tag by another name. A speed test shows they are used identically.

Step 2: (Optional, but awesome) Stick a default image inside that object. If the image you want actually loads in the object, the default image won't show. So for example you could show a list of user avatars, and if someone doesn't have an image on the server yet, it could show the placeholder image... no javascript or CSS required at all, but you get the features of what takes most people JavaScript.

Here is the code...

<object data="avatar.jpg" type="image/jpg">
    <img src="default.jpg" />
</object>

... Yes, it's that simple.

If you want to implement default images with CSS, you can make it even simpler in your HTML like this...

<object class="avatar" data="user21.jpg" type="image/jpg"></object>

...and just add the CSS from this answer -> https://stackoverflow.com/a/32928240/3196360

Can I use Twitter Bootstrap and jQuery UI at the same time?

Although this question specifically mentions jQuery-UI autosuggest feature, the question title is more general: does bootstrap 3 work with jQuery UI? I was having trouble with the jQUI datepicker (pop-up calendar) feature. I solved the datepicker problem and hope the solution will help with other jQUI/BS issues.

I had a difficult time today getting the latest jQueryUI (ver 1.12.1) datepicker to work with bootstrap 3.3.7. What was happening is that the calendar would display but it would not close.

Turned out to be a version problem with jQUI and BS. I was using the latest version of Bootstrap, and found that I had to downgrade to these versions of jQUI and jQuery:

jQueryUI - 1.9.2 (tested - works)
jQuery - 1.9.1 or 2.1.4 (tested - both work. Other vers may work, but these work.)
Bootstrap 3.3.7 (tested - works)

Because I wanted to use a custom theme, I also built a custom download of jQUI (removed a few things like all the interactions, dialog, progressbar and a few effects I don't use) -- and made sure to select "Cupertino" at the bottom as my theme.

I installed them thus:

<head>
...etc...
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/cupertino/jquery-ui-1.9.2.custom.min.css">
<link rel="stylesheet" href="css/bootstrap-3.3.7.min.css">

<!-- <script src="js/jquery-1.9.1.min.js"></script> -->
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script src="js/bootstrap-3.3.7.min.js"></script>
...etc...
</head>

For those interested, the CSS folder looks like this:

[css]
  - bootstrap-3.3.7.min.css
  - font-awesome.min.css
  - style.css
  - [cupertino]
      - jquery-ui-1.9.2.custom.min.css
      [images]
          - ui-bg_diagonals-thick_90_eeeeee_40x40.png
          - ui-bg_glass_100_e4f1fb_1x400.png
          - ui-bg_glass_50_3baae3_1x400.png
          - ui-bg_glass_80_d7ebf9_1x400.png
          - ui-bg_highlight-hard_100_f2f5f7_1x100.png
          - etc (8 more files that were in the downloaded jQUI zip file)

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

What is the difference between POST and GET?

POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.

POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.

Laravel form html with PUT method for PUT routes

Is very easy, you just need to use method_field('PUT') like this:

HTML:

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

or

<form action="{{ route('route_name') }}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Regards!

How to hide/show more text within a certain length (like youtube)

Here's a really simple solution that worked for me,

<span id="text">Extra Text</span>
<span id="more">show more...</span>
<span id="less">show less...</span>

<script>
 $("#text").hide();
 $("#less").hide();
 $("#more").click( function() {
   $("#text").show();
   $("#less").show();
   $("#more").hide();
 });
 $("#less").click( function() {
   $("#text").hide();
   $("#less").hide();
   $("#more").show();
 });
</script>

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

Repair all tables in one go

There is no default command to do that, but you may create a procedure to do the job. It will iterate through rows of information_schema and call REPAIR TABLE 'tablename'; for every row. CHECK TABLE is not yet supported for prepared statements. Here's the example (replace MYDATABASE with your database name):

CREATE DEFINER = 'root'@'localhost'
PROCEDURE MYDATABASE.repair_all()
BEGIN
  DECLARE endloop INT DEFAULT 0;
  DECLARE tableName char(100);
  DECLARE rCursor CURSOR FOR SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`=DATABASE();
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET endloop=1;

  OPEN rCursor;
  FETCH rCursor INTO tableName;

  WHILE endloop = 0 DO
    SET @sql = CONCAT("REPAIR TABLE `", tableName, "`");
    PREPARE statement FROM @sql;
    EXECUTE statement;

    FETCH rCursor INTO tableName;
  END WHILE;

  CLOSE rCursor;
END

getResourceAsStream() vs FileInputStream

getResourceAsStream is the right way to do it for web apps (as you already learned).

The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Add below code in to file d:\xampp\apache\conf\extra\httpd-xampp.conf:

<IfModule alias_module>
...
    Alias / "d:/xampp/my/folder/"
    <Directory "d:/xampp/my/folder">
        AllowOverride AuthConfig Limit
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>

Above config can access from http://127.0.0.1/

Note: someone suggest that replace from Require local to Require all granted but not work for me

<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    # Require local
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Why use Ruby's attr_accessor, attr_reader and attr_writer?

Not all attributes of an object are meant to be directly set from outside the class. Having writers for all your instance variables is generally a sign of weak encapsulation and a warning that you're introducing too much coupling between your classes.

As a practical example: I wrote a design program where you put items inside containers. The item had attr_reader :container, but it didn't make sense to offer a writer, since the only time the item's container should change is when it's placed in a new one, which also requires positioning information.

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

How do I use brew installed Python as the default Python?

Use pyenv instead to install and switch between versions of Python. I've been using rbenv for years which does the same thing, but for Ruby. Before that it was hell managing versions.

Consult pyenv's github page for installation instructions. Basically it goes like this: - Install pyenv using homebrew. brew install pyenv - Add a function to the end of your shell startup script so pyenv can do it's magic. echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

  • Use pyenv to install however many different versions of Python you need. pyenv install 3.7.7.
  • Set the default (global) version to a modern version you just installed. pyenv global 3.7.7.
  • If you work on a project that needs to use a different version of python, look into pyevn local. This creates a file in your project's folder that specifies the python version. Pyenv will look override the global python version with the version in that file.

Android Studio Gradle Already disposed Module

Note: this is purely an IDEA/AS issue, gradlew clean | Build > Clean | Build > Rebuild will just waste your time.

Most of the solutions here are blind stabbings in the dark. Here's what I found to be the root cause:

  1. Some of the .iml files may be missing (maybe because we deleted it), check if the module erroring has .iml.
  2. If it is missing, check if .idea/modules.xml has an entry for that module

While syncing I noticed that IDEA/AS tries to put a new duplicate entry into .idea/modules.xml while there's already one. This duplicate entry is probably disposed of twice while the sync tries to reset the modules in memory.

Quick Solution: In order to make it work the easiest is to delete .idea/modules.xml along with the .iml files. Additionally may worth deleting .idea/modules/ folder if it exists. Restart Android Studio (no need to clear cache) and force a Gradle sync from Gradle view or toolbar to recreate the files.

How to set cursor position in EditText?

If you want to set cursor position in EditText? try these below code

EditText rename;
 String title = "title_goes_here";
 int counts = (int) title.length();
 rename.setSelection(counts);
 rename.setText(title);

How does the modulus operator work?

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Your database name must end with .db also your query strings must have a terminator (;)

Change the location of the ~ directory in a Windows install of Git Bash

I'd share what I did, which works not only for Git, but MSYS/MinGW as well.

The HOME environment variable is not normally set for Windows applications, so creating it through Windows did not affect anything else. From the Computer Properties (right-click on Computer - or whatever it is named - in Explorer, and select Properties, or Control Panel -> System and Security -> System), choose Advanced system settings, then Environment Variables... and create a new one, HOME, and assign it wherever you like.

If you can't create new environment variables, the other answer will still work. (I went through the details of how to create environment variables precisely because it's so dificult to find.)

Is there a limit on how much JSON can hold?

If you are working with ASP.NET MVC, you can solve the problem by adding the MaxJsonLength to your result:

var jsonResult = Json(new
{
    draw = param.Draw,
    recordsTotal = count,
    recordsFiltered = count,
    data = result
}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;

Does the Java &= operator apply & or &&?

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

Override default Spring-Boot application.properties settings in Junit Test

Simple explanation:

If you are like me and you have the same application.properties in src/main/resources and src/test/resources, and you are wondering why the application.properties in your test folder is not overriding the application.properties in your main resources, read on...

If you have application.properties under src/main/resources and the same application.properties under src/test/resources, which application.properties gets picked up, depends on how you are running your tests. The folder structure src/main/resources and src/test/resources, is a Maven architectural convention, so if you run your test like mvnw test or even gradlew test, the application.properties in src/test/resources will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test in Eclipse/STS, the application.properties in src/main/resources will get picked up, as main classpath precedes test classpath.

You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line".

You will see something like this:

XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;

Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)

Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.

select the TOP N rows from a table

From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:

https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#using-offset-and-fetch-to-limit-the-rows-returned

Your query become:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS  
FETCH NEXT 20 ROWS ONLY;  

mean() warning: argument is not numeric or logical: returning NA

The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean() function. Therefore, check your data using str(data.frame&column) function to see what data type you have, and convert it to numeric format if necessary. For example, if your data is Character convert it with as.numeric(data.frame$column), or as a factor with as.numeric(as.character(data.frame$column)). The mean function does not work with types other than numeric.

Open Excel file for reading with VBA without display

A much simpler approach that doesn't involve manipulating active windows:

Dim wb As Workbook
Set wb = Workbooks.Open("workbook.xlsx")
wb.Windows(1).Visible = False

From what I can tell the Windows index on the workbook should always be 1. If anyone knows of any race conditions that would make this untrue please let me know.

Python read-only property

Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some static datasource), the getter-only property is generally the preferred pattern.

Kubernetes service external ip pending

The LoadBalancer ServiceType will only work if the underlying infrastructure supports the automatic creation of Load Balancers and have the respective support in Kubernetes, as is the case with the Google Cloud Platform and AWS. If no such feature is configured, the LoadBalancer IP address field is not populated and still in pending status , and the Service will work the same way as a NodePort type Service

Is it possible to add dynamically named properties to JavaScript object?

ES6 introduces computed property names, which allows you to do

let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}

Conditional formatting, entire row based

To set Conditional Formatting for an ENTIRE ROW based on a single cell you must ANCHOR that single cell's column address with a "$", otherwise Excel will only get the first column correct. Why?

Because Excel is setting your Conditional Format for the SECOND column of your row based on an OFFSET of columns. For the SECOND column, Excel has now moved one column to the RIGHT of your intended rule cell, examined THAT cell, and has correctly formatted column two based on a cell you never intended.

Simply anchor the COLUMN portion of your rule cell's address with "$", and you will be happy

For example: You want any row of your table to highlight red if the last cell of that row does not equal 1.

Select the entire table (but not the headings) "Home" > "Conditional Formatting" > "Manage Rules..." > "New Rule" > "Use a formula to determine which cells to format"

Enter: "=$T3<>1" (no quotes... "T" is the rule cell's column, "3" is its row) Set your formatting Click Apply.

Make sure Excel has not inserted quotes into any part of your formula... if it did, Backspace/Delete them out (no arrow keys please).

Conditional Formatting should be set for the entire table.

Sorting dropdown alphabetically in AngularJS

var module = angular.module("example", []);

module.controller("orderByController", function ($scope) {
    $scope.orderByValue = function (value) {
        return value;
    };

    $scope.items = ["c", "b", "a"];
    $scope.objList = [
        {
            "name": "c"
        }, {
            "name": "b"
        }, {
            "name": "a"
        }];
        $scope.item = "b";
    });

http://jsfiddle.net/Nfv42/65/

Change default icon

you should put your icon on the project folder, before build it

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Check the exact driver name in the ODBC Administrator tool. Press Windows key + R and then:

  • C:\Windows\System32\odbcad32.exe on 32-bit systems
  • C:\Windows\SysWOW64\odbcad32.exe on 64-bit systems

In my case it should have been Microsoft Access Driver (*.mdb, *.accdb) instead of Microsoft Access Driver (*.mdb).

android studio 0.4.2: Gradle project sync failed error

I always remove the .gradle folder from %USERS% folder and start the studio again. When starting the IDE it downloads gradle again with all the dependencies again. Its work PERFECT.

How to get text box value in JavaScript

Your element does not have an ID but just a name. So you could either use getElementsByName() method to get a list of all elements with this name:

var jobValue = document.getElementsByName('txtJob')[0].value  // first element in DOM  (index 0) with name="txtJob"

Or you assign an ID to the element:

<input type="text" name="txtJob" id="txtJob" value="software engineer">

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

I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.

Java: how do I initialize an array size if it's unknown?

**input of list of number for array from single line.

   String input = sc.nextLine();
    String arr[] = input.split(" ");
    int new_arr[] = new int[arr.length];
    for(int i=0; i<arr.length; i++)
    {
         new_arr[i] = Integer.parseInt(arr[i]);
    }

Integer value in TextView

Consider using String#format with proper format specifications (%d or %f) instead.

int value = 10;

textView.setText(String.format("%d",value));

This will handle fraction separator and locale specific digits properly

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case

example:

BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH 
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

How can I generate Javadoc comments in Eclipse?

JAutoDoc:

an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...

Eclipse error: indirectly referenced from required .class files?

In my case it was a result of my adding a new dependency to my pom.xml file.

The new dependency depended on an old version of a library (2.5). That same library was required by another library in my pom.xml, but it required version 3.0.

For some reason, when Maven encounters these conflicts it simply omits the most recent version. In Eclipse when viewing pom.xml you can select the "dependency hierarchy" tab at the bottom to see how dependencies are resolved. Here you will find if the library (and thus class) in question has been omitted for this reason.

In my case it was as simple as locking down the newer version. You can do so by right-clicking the entry - there is an option to lock it down in the context menu.

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Question mark and colon in statement. What does it mean?

This is the conditional operator expression.

(condition) ? [true path] : [false path];

For example

 string value = someBooleanExpression ? "Alpha" : "Beta";

So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".

For a common pitfall that people fall into, see this question in the C# tag wiki.

Overcoming "Display forbidden by X-Frame-Options"

Not mentioned but can help in some instances:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState !== 4) return;
    if (xhr.status === 200) {
        var doc = iframe.contentWindow.document;
        doc.open();
        doc.write(xhr.responseText);
        doc.close();
    }
}
xhr.open('GET', url, true);
xhr.send(null);

How to obtain the last index of a list?

the best and fast way to obtain last index of a list is using -1 for number of index , for example:

my_list = [0, 1, 'test', 2, 'hi']
print(my_list[-1])

out put is : 'hi'. index -1 in show you last index or first index of the end.

SQL Server Restore Error - Access is Denied

I had a similar problem. I tried to restore a 2005 .bak file, and i received exactly the same error. I selected the overwrite option as well to no avail.

my solution was to grant the SQL user access to the directory in question, by going to the folder and editing the access rights through the property screen.

Normalize data in pandas

Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)

I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):

def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):    
    if low=='min':
        low=min(s)
    elif low=='abs':
        low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
    if hi=='max':
        hi=max(s)
    elif hi=='abs':
        hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))

    if center=='mid':
        center=(max(s)+min(s))/2
    elif center=='avg':
        center=mean(s)
    elif center=='median':
        center=median(s)

    s2=[x-center for x in s]
    hi=hi-center
    low=low-center
    center=0.

    r=[]

    for x in s2:
        if x<low:
            r.append(0.)
        elif x>hi:
            r.append(1.)
        else:
            if x>=center:
                r.append((x-center)/(hi-center)*0.5+0.5)
            else:
                r.append((x-low)/(center-low)*0.5+0.)

    if insideout==True:
        ir=[(1.-abs(z-0.5)*2.) for z in r]
        r=ir

    rr =[x-(x-0.5)*shrinkfactor for x in r]    
    return rr

This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:

#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]

It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:

#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]

So now "2" which is closest to the center, defined as "1" is the highest value.

Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.

How to sort a HashMap in Java

Seems like you might want a treemap.

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

You can pass in a custom comparator to it if that applies.

How to generate a range of numbers between two numbers?

-- Generate Numeric Range
-- Source: http://www.sqlservercentral.com/scripts/Miscellaneous/30397/

CREATE TABLE #NumRange(
    n int
)

DECLARE @MinNum int
DECLARE @MaxNum int
DECLARE @I int

SET NOCOUNT ON

SET @I = 0
WHILE @I <= 9 BEGIN
    INSERT INTO #NumRange VALUES(@I)
    SET @I = @I + 1
END


SET @MinNum = 1
SET @MaxNum = 1000000

SELECT  num = a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000)
FROM    #NumRange a
CROSS JOIN #NumRange b
CROSS JOIN #NumRange c
CROSS JOIN #NumRange d
CROSS JOIN #NumRange e
WHERE   a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000) BETWEEN @MinNum AND @MaxNum
ORDER BY a.n +
    (b.n * 10) +
    (c.n * 100) +
    (d.n * 1000) +
    (e.n * 10000) 

DROP TABLE #NumRange

How To fix white screen on app Start up?

This is my AppTheme on an example app:

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

As you can see, I have the default colors and then I added the android:windowIsTranslucent and set it to true.

As far as I know as an Android Developer, this is the only thing you need to set in order to hide the white screen on the start of the application.

Android ListView with onClick items

You should definitely extend you ArrayListAdapter and implement this in your getView() method. The second parameter (a View) should be inflated if it's value is null, take advantage of it and set it an onClickListener() just after inflating.

Suposing it's called your second getView()'s parameter is called convertView:

convertView.setOnClickListener(new View.OnClickListener() {
  public void onClick(final View v) {
    if (isSamsung) {
      final Intent intent = new Intent(this, SamsungInfo.class);
      startActivity(intent);
    }
    else if (...) {
      ...
    }
  }
}

If you want some info on how to extend ArrayListAdapter, I recommend this link.

How to check for DLL dependency?

Please search "depends.exe" in google, it's a tiny utility to handle this.

Deep copy, shallow copy, clone

The terms "shallow copy" and "deep copy" are a bit vague; I would suggest using the terms "memberwise clone" and what I would call a "semantic clone". A "memberwise clone" of an object is a new object, of the same run-time type as the original, for every field, the system effectively performs "newObject.field = oldObject.field". The base Object.Clone() performs a memberwise clone; memberwise cloning is generally the right starting point for cloning an object, but in most cases some "fixup work" will be required following a memberwise clone. In many cases attempting to use an object produced via memberwise clone without first performing the necessary fixup will cause bad things to happen, including the corruption of the object that was cloned and possibly other objects as well. Some people use the term "shallow cloning" to refer to memberwise cloning, but that's not the only use of the term.

A "semantic clone" is an object which is contains the same data as the original, from the point of view of the type. For examine, consider a BigList which contains an Array> and a count. A semantic-level clone of such an object would perform a memberwise clone, then replace the Array> with a new array, create new nested arrays, and copy all of the T's from the original arrays to the new ones. It would not attempt any sort of deep-cloning of the T's themselves. Ironically, some people refer to the of cloning "shallow cloning", while others call it "deep cloning". Not exactly useful terminology.

While there are cases where truly deep cloning (recursively copying all mutable types) is useful, it should only be performed by types whose constituents are designed for such an architecture. In many cases, truly deep cloning is excessive, and it may interfere with situations where what's needed is in fact an object whose visible contents refer to the same objects as another (i.e. a semantic-level copy). In cases where the visible contents of an object are recursively derived from other objects, a semantic-level clone would imply a recursive deep clone, but in cases where the visible contents are just some generic type, code shouldn't blindly deep-clone everything that looks like it might possibly be deep-clone-able.

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

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

Guys I just found a solution. Given that TortoiseSVN works the way we want, I tried to install it under Linux - which means, running on Wine. Surprisingly it works! All you have to do is:

  1. Add files you want to skip commit by running: "svn changelist 'ignore-on-commit' ".
  2. Use TortoiseSVN to commit: "~/.wine/drive_c/Program\ Files/TortoiseSVN/bin/TortoiseProc.exe /command:commit /path:'
  3. The files excluded will be unchecked for commit by default, while other modified files will be checked. This is exactly the same as under Windows. Enjoy!

(The reason why need to exclude files by CLI is because the menu entry for doing that was not found, not sure why. Any way, this works great!)

Java Embedded Databases Comparison

neo4j is:

an embedded, disk-based, fully transactional Java persistence engine that stores data structured in graphs rather than in tables

I haven't had a chance to try it yet - but it looks very promising. Note this is not an SQL database - your object graph is persisted for you - so it might not be appropriate for your existing app.

Selectors in Objective-C?

Selectors are an efficient way to reference methods directly in compiled code - the compiler is what actually assigns the value to a SEL.

Other have already covered the second part of your q, the ':' at the end matches a different signature than what you're looking for (in this case that signature doesn't exist).

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

it is due to incompatibility.

please upgrade classpath("com.android.tools.build:gradle:4.0.1") in build.gradle file under android folder.

GROUP BY with MAX(DATE)

SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

How to get just one file from another branch

Another way is to create a patch with the differences and apply it in the master branch For instance. Let's say the last commit before you started working on app.js is 00000aaaaa and the commit containg the version you want is 00000bbbbb

The you run this on the experiment branch:

git diff 00000aaaaa 00000bbbbb app.js > ~/app_changes.git

This will create a file with all the differences between those two commits for app.js that you can apply wherever you want. You can keep that file anywhere outside the project

Then, in master you just run:

git apply ~/app_changes.git

now you are gonna see the changes in the projects as if you had made them manually.

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 

Use of exit() function

Bad programming practice. Using a goto function is a complete no no in C programming.
Also include header file stdlib.h by writing #include <iostream.h>for using exit() function. Also remember that exit() function takes an integer argument . Use exit(0) if the program completed successfully and exit(-1) or exit function with any non zero value as the argument if the program has error.

How to install .MSI using PowerShell

You can use:

msiexec /i "c:\package.msi"

You can also add some more optional parameters. There are common msi parameters and parameters which are specific for your installer. For common parameters just call msiexec

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

TABLE:
ID NAME
1  Peter
2  John
3  Greg
4  Peter

SELECT *
FROM TABLE
ORDER BY NAME

= 
3 Greg
2 John
1 Peter
4 Peter

SELECT Count(ID), NAME
FROM TABLE
GROUP BY NAME

= 
1 Greg
1 John 
2 Peter

SELECT NAME
FROM TABLE
GROUP BY NAME
HAVING Count(ID) > 1

=
Peter

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

Modulo operator with negative values

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

How to import local packages without gopath

You can use replace

go mod init example.com/my/foo

foo/go.mod

module example.com/my/foo

go 1.14

replace example.com/my/bar => /path/to/bar

require example.com/my/bar v1.0.0

foo/main.go

package main
import "example.com/bar"

func main() {
    bar.MyFunc()
}

bar/go.mod

module github.com/my/bar

go 1.14

bar/fn.go

package github.com/my/bar

import "fmt"

func MyFunc() {
    fmt.Printf("hello")
}

Importing a local package is just like importing an external pacakge

except inside the go.mod file you replace that external package name with a local folder.

The path to the folder can be full or relative /path/to/bar or ../bar

how to get the child node in div using javascript

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

Can not connect to local PostgreSQL

I was getting this same error (it turns out it was an error with postmaster.pid. Here's how I got postgres up and running again (credit to Ricardo Burillo for the fix):

$ rm /usr/local/var/postgres/postmaster.pid 
$ pg_resetxlog -f /usr/local/var/postgres

What does \u003C mean?

It's a unicode character. In this case \u003C and \u003E mean :

U+003C < Less-than sign

U+003E > Greater-than sign

See a list here

How do you get the process ID of a program in Unix or Linux using Python?

The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.

import os

program_pid = 0
program_name = "notepad.exe"

task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
    try:
        if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
            program_pid = int(line[29:34])
            break
    except:
        pass

print(program_pid)

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

What is the difference between require and require-dev sections in composer.json?

From the composer site (it's clear enough)

require#

Lists packages required by this package. The package will not be installed unless those requirements can be met.

require-dev (root-only)#

Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev part would be ignored.

Also check this answer posted by the author and this post as well.

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

Failed binder transaction when putting an bitmap dynamically in a widget

See my answer in this thread.

intent.putExtra("Some string",very_large_obj_for_binder_buffer);

You are exceeding the binder transaction buffer by transferring large element(s) from one activity to another activity.

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

Why is php not running?

You need to add the semicolon to the end of all php things like echo, functions, etc.

change <?php phpinfo() ?> to <?php phpinfo(); ?>

If that does not work, use php's function ini_set to show errors: ini_set('display_errors', 1);

Fatal error: Out of memory, but I do have plenty of memory (PHP)

For my case, this error was triggered because of a huge select query (hundreds of thousands of returned results).

It arose immediately after adding millions of records in my Database to test the scalability of WordPress, so it was the only probable reason for me.

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

How to import existing Git repository into another?

See Basic example in this article and consider such mapping on repositories:

  • A <-> YYY,
  • B <-> XXX

After all activity described in this chapter (after merging), remove branch B-master:

$ git branch -d B-master

Then, push changes.

It works for me.

mkdir -p functionality in Python

I think Asa's answer is essentially correct, but you could extend it a little to act more like mkdir -p, either:

import os

def mkdir_path(path):
    if not os.access(path, os.F_OK):
        os.mkdirs(path)

or

import os
import errno

def mkdir_path(path):
    try:
        os.mkdirs(path)
    except os.error, e:
        if e.errno != errno.EEXIST:
            raise

These both handle the case where the path already exists silently but let other errors bubble up.

Python : List of dict, if exists increment a dict value, if not append a new dict

This always works fine for me:

for url in list_of_urls:
    urls.setdefault(url, 0)
    urls[url] += 1

How to search for a part of a word with ElasticSearch

I am using this and got I worked

"query": {
        "query_string" : {
            "query" : "*test*",
            "fields" : ["field1","field2"],
            "analyze_wildcard" : true,
            "allow_leading_wildcard": true
        }
    }

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Check if a process is running or not on Windows with Python

If can't rely on the process name like python scripts which will always have python.exe as process name. If found this method very handy

import psutil
psutil.pid_exists(pid)

check docs for further info http://psutil.readthedocs.io/en/latest/#psutil.pid_exists

How to scale a BufferedImage

AffineTransformOp offers the additional flexibility of choosing the interpolation type.

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp = 
   new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

The fragment shown illustrates resampling, not cropping; this related answer addresses the issue; some related examples are examined here.

Postgres could not connect to server

Had the same problem. Upgrading DB did the trick! postgresql-upgrade-database

How do you find the sum of all the numbers in an array in Java?

A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.

So the award for the fastest short and sweet code goes to -

int[] nums = {1,2,3};
int sum =  Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);

Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .

Crystal Reports 13 And Asp.Net 3.5

I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:

  1. Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.

  2. You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS

  3. Make sure you setup FULL TRUST permission on your root folder

  4. The LOCAL SERVICE permission must be setup on your application pool

  5. Make sure the aspnet_client folder exists on your root folder.

If you can make sure all the 5 points above, your Crystal Report should work without any fuss.

Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.

Good luck!

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

SQL Server Linked Server Example Query

If you still find issue with <server>.<database>.<schema>.<table>

Enclose server name in []

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

In our case, the reason that the c++ version bson was not found was because we were behind a corporate proxy and something in the BSON build process needs to reach out to fetch files. When we looked in node_modules/bson/builderror.log, we saw an error like this:

gyp WARN install got an error, rolling back install gyp ERR! configure error gyp ERR! stack Error: connect ECONNREFUSED gyp ERR! stack at errnoException (net.js:904:11) gyp ERR! stack at Object.afterConnect [as oncomplete] (net.js:895:19)

Which suggested that the proxy might be the issue. Setting the http_proxy and https_proxy environment variables solved it.

Sorry for reawakening comments on this, but I wanted to post this for anyone else that hits this in the future since this thread was very helpful in solving our issue.

case statement in SQL, how to return multiple variables?

CASE by definition only returns a single value. Ever.

It also (almost always) short circuits, which means if your first condition is met no other checks are run.

Loop through all the resources in a .resx file

The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.

Alternatively, you can use reflection to loop through these names.

Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
    BindingFlags.NonPublic | 
    BindingFlags.Static | 
    BindingFlags.GetProperty);

foreach (PropertyInfo info in resourceProps)
{
    string name = info.Name;
    object value = info.GetValue(null, null);  // object can be an image, a string whatever
    // do something with name and value
}

This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".

The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.

How can I use the apply() function for a single column?

For a single column better to use map(), like this:

df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9



df['a'] = df['a'].map(lambda a: a / 2.)

      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

Recommended date format for REST GET API

Check this article for the 5 laws of API dates and times HERE:

  • Law #1: Use ISO-8601 for your dates
  • Law #2: Accept any timezone
  • Law #3: Store it in UTC
  • Law #4: Return it in UTC
  • Law #5: Don’t use time if you don’t need it

More info in the docs.

How to use zIndex in react-native

You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.

The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

React-Native: Application has not been registered error

In my case there's this line in MainActivity.java which was missed when I used react-native-rename cli (from NPM)

protected String getMainComponentName() {
    return "AwesomeApp";
}

Obviously ya gotta rename it to your app's name.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How do I get the size of a java.sql.ResultSet?

Today, I used this logic why I don't know getting the count of RS.

int chkSize = 0;
if (rs.next()) {
    do {  ..... blah blah
        enter code here for each rs.
        chkSize++;
    } while (rs.next());
} else {
    enter code here for rs size = 0 
}
// good luck to u.

jquery how to catch enter key and change event to tab

Building from Ben's plugin this version handles select and you can pass an option to allowSubmit. ie. $("#form").enterAsTab({ 'allowSubmit': true}); This will allow enter to submit the form if the submit button is handling the event.

(function( $ ){
    $.fn.enterAsTab = function( options ) {  
    var settings = $.extend( {
       'allowSubmit': false
    }, options);
    this.find('input, select').live("keypress", {localSettings: settings}, function(event) {
        if (settings.allowSubmit) {
        var type = $(this).attr("type");
        if (type == "submit") {
            return true;
        } 
    }
    if (event.keyCode == 13 ) {
        var inputs =   $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])");
        var idx = inputs.index(this);
        if (idx == inputs.length - 1) {
           idx = -1;
       } else {
           inputs[idx + 1].focus(); // handles submit buttons
      }
        try {
            inputs[idx + 1].select();
            }
        catch(err) {
            // handle objects not offering select
            }
        return false;
    }
});
  return this;
};
})( jQuery );

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

String.Format like functionality in T-SQL?

At the moment this doesn't really exist (although you can of course write your own). There is an open connect bug for it: https://connect.microsoft.com/SQLServer/Feedback/Details/3130221, which as of this writing has just 1 vote.

Insert a line break in mailto body

I would suggest you try the html tag <br>, in case your marketing application will recognize it.

I use %0D%0A. This should work as long as the email is HTML formatted.

<a href="mailto:[email protected]?subject=Subscribe&body=Lastame%20%3A%0D%0AFirstname%20%3A"><img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"></a>

You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.

A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Funnily enough the MySQL workbench solved it for me. In the Administration tab -> Users and Privileges, the user was listed with an error. Using the delete option solved the problem.

How can I read inputs as numbers?

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

UILabel with text of two different colors

Having a UIWebView or more than one UILabel could be considered overkill for this situation.

My suggestion would be to use TTTAttributedLabel which is a drop-in replacement for UILabel that supports NSAttributedString. This means you can very easily apply differents styles to different ranges in a string.

How to terminate script execution when debugging in Google Chrome?

There are many appropiate solution to this problem as mentioned above in this post, but i have found a small hack that can be inserrted in the script or pasted in the Chromes console (debugger) to achieve it:

jQuery(window).keydown(function(e) { if (e.keyCode == 123) debugger; });

This will cause execution to be paused when you hit F12.

How to reset radiobuttons in jQuery so that none is checked

Where you have: <input type="radio" name="enddate" value="1" />

After value= "1" you can also just add unchecked =" false" />

The line will then be:

<input type="radio" name="enddate" value="1" unchecked =" false" />

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Replace forward slash "/ " character in JavaScript string?

Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -

react-native - Fit Image in containing View, not the whole screen size

Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:

image: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
},

How to write hello world in assembler under Windows?

Unless you call some function this is not at all trivial. (And, seriously, there's no real difference in complexity between calling printf and calling a win32 api function.)

Even DOS int 21h is really just a function call, even if its a different API.

If you want to do it without help you need to talk to your video hardware directly, likely writing bitmaps of the letters of "Hello world" into a framebuffer. Even then the video card is doing the work of translating those memory values into DisplayPort/HDMI/DVI/VGA signals.

Note that, really, none of this stuff all the way down to the hardware is any more interesting in ASM than in C. A "hello world" program boils down to a function call. One nice thing about ASM is that you can use any ABI you want fairly easily; you just need to know what that ABI is.

Make ABC Ordered List Items Have Bold Style

As an alternative and superior solution, you could use a custom counter in a before element. It involves no extra HTML markup. A CSS reset should be used alongside it, or at least styling removed from the ol element (list-style-type: none, reset margin), otherwise the element will have two counters.

<ol>
    <li>First line</li>
    <li>Second line</li>
</ol>

CSS:

ol {
    counter-reset: my-badass-counter;
}
ol li:before {
    content: counter(my-badass-counter, upper-alpha);
    counter-increment: my-badass-counter;
    margin-right: 5px;
    font-weight: bold;
}

An example: http://jsfiddle.net/xpAMU/1/

How to store values from foreach loop into an array?

Try

$items = array_values ( $group_membership );

@angular/material/index.d.ts' is not a module

This can be solved by writing full path, for example if you want to include MatDialogModule follow:

Prior to @angular/material 9.x.x

import { MatDialogModule } from "@angular/material";
//leading to error mentioned

As per @angular/material 9.x.x

import { MatDialogModule } from "@angular/material/dialog";
//works fine 

Official change log breaking change reference: https://github.com/angular/components/blob/master/CHANGELOG.md#material-9

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

Propagate all arguments in a bash shell script

#!/usr/bin/env bash
while [ "$1" != "" ]; do
  echo "Received: ${1}" && shift;
done;

Just thought this may be a bit more useful when trying to test how args come into your script

How do I compare 2 rows from the same table (SQL Server)?

You can join a table to itself as many times as you require, it is called a self join.

An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

SELECT a.SelfJoinTableID
FROM   dbo.SelfJoinTable a
       INNER JOIN dbo.SelfJoinTable b
         ON a.SelfJoinTableID = b.SelfJoinTableID
       INNER JOIN dbo.SelfJoinTable c
         ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE  a.Status = 'Status to filter a'
       AND b.Status = 'Status to filter b'
       AND c.Status = 'Status to filter c' 

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

Add context path to Spring Boot application

We can set it using WebServerFactoryCustomizer. This can be added directly in the spring boot main method class which starts up the Spring ApplicationContext.

@Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
      webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/demo");
}

How to force view controller orientation in iOS 8?

For me, the top level VC needed to implement the orientation overrides. Using VC's down the stack will have no effect if the top VC is not implementing.

VC-main
    |
    -> VC 2
        |
        -> VC 3

Only VC-Main is listened to, essentially in my testing.

Swift: Convert enum value to String?

A swift 3 and above example if using Ints in Enum

public enum ECategory : Int{
        case Attraction=0, FP, Food, Restroom, Popcorn, Shop, Service, None;
        var description: String {
            return String(describing: self)
        }
    }

let category = ECategory.Attraction
let categoryName = category.description //string Attraction

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

On select change, get data attribute value

$('#foo option:selected').data('id');

Define global constants

While the approach with having a AppSettings class with a string constant as ApiEndpoint works, it is not ideal since we wouldn't be able to swap this real ApiEndpoint for some other values at the time of unit testing.

We need to be able to inject this api endpoints into our services (think of injecting a service into another service). We also do not need to create a whole class for this, all we want to do is to inject a string into our services being our ApiEndpoint. To complete the excellent answer by pixelbits, here is the complete code as to how it can be done in Angular 2:

First we need to tell Angular how to provide an instance of our ApiEndpoint when we ask for it in our app (think of it as registering a dependency):

bootstrap(AppComponent, [
        HTTP_PROVIDERS,
        provide('ApiEndpoint', {useValue: 'http://127.0.0.1:6666/api/'})
]);         


And then in the service we inject this ApiEndpoint into the service constructor and Angular will provide it for us based on our registration above:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable, Inject} from 'angular2/core';  // * We import Inject here
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http, 
                @Inject('ApiEndpoint') private apiEndpoint: string) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(`${this.apiEndpoint}/messages`)
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    } 
    // the rest of the code...
}

How to make custom error pages work in ASP.NET MVC 4

In web.config add this under system.webserver tag as below,

<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <remove statusCode="500"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
  <error statusCode="500" responseMode="ExecuteURL"path="/Error/ErrorPage"/>
</httpErrors>

and add a controller as,

public class ErrorController : Controller
{
    //
    // GET: /Error/
    [GET("/Error/NotFound")]
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;

        return View();
    }

    [GET("/Error/ErrorPage")]
    public ActionResult ErrorPage()
    {
        Response.StatusCode = 500;

        return View();
    }
}

and add their respected views, this will work definitely I guess for all.

This solution I found it from: Neptune Century

How to return values in javascript

I would prefer a callback solution: Working fiddle here: http://jsfiddle.net/canCu/

function myFunction(value1,value2,value3, callback) {

    value2 = 'somevalue2'; //to return
    value3 = 'somevalue3'; //to return

    callback( value2, value3 );

}

var value1 = 1;
var value2 = 2;
var value3 = 3;

myFunction(value1,value2,value3, function(value2, value3){
    if (value2 && value3) {
        //Do some stuff
        alert( value2 + '-' + value3 );
    }    
});

Inversion of Control vs Dependency Injection

Since all the answers emphasize on theory I would like to demonstrate with an example first approach:

Suppose we are building an application which contains a feature to send SMS confirmation messages once the order has been shipped. We will have two classes, one is responsible for sending the SMS (SMSService), and another responsible for capturing user inputs (UIHandler), our code will look as below:

public class SMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
    }
}

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        SMSService _SMSService = new SMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

Above implementation is not wrong but there are few issues:
-) Suppose On development environment, you want to save SMSs sent to a text file instead of using SMS gateway, to achieve this; we will end up changing the concrete implementation of (SMSService) with another implementation, we are losing flexibility and forced to rewrite the code in this case.
-) We’ll end up mixing responsibilities of classes, our (UIHandler) should never know about the concrete implementation of (SMSService), this should be done outside the classes using “Interfaces”. When this is implemented, it will give us the ability to change the behavior of the system by swapping the (SMSService) used with another mock service which implements the same interface, this service will save SMSs to a text file instead of sending to mobileNumber.

To fix the above issues we use Interfaces which will be implemented by our (SMSService) and the new (MockSMSService), basically the new Interface (ISMSService) will expose the same behaviors of both services as the code below:

public interface ISMSService
{
    void SendSMS(string phoneNumber, string body);
}

Then we will change our (SMSService) implementation to implement the (ISMSService) interface:

public class SMSService : ISMSService
{
    public void SendSMS(string mobileNumber, string body)
    {
        SendSMSUsingGateway(mobileNumber, body);
    }

    private void SendSMSUsingGateway(string mobileNumber, string body)
    {
        /*implementation for sending SMS using gateway*/
        Console.WriteLine("Sending SMS using gateway to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

Now we will be able to create new mock up service (MockSMSService) with totally different implementation using the same interface:

public class MockSMSService :ISMSService
{
    public void SendSMS(string phoneNumber, string body)
    {
        SaveSMSToFile(phoneNumber,body);
    }

    private void SaveSMSToFile(string mobileNumber, string body)
    {
        /*implementation for saving SMS to a file*/
        Console.WriteLine("Mocking SMS using file to mobile: 
        {0}. SMS body: {1}", mobileNumber, body);
    }
}

At this point, we can change the code in (UIHandler) to use the concrete implementation of the service (MockSMSService) easily as below:

public class UIHandler
{
    public void SendConfirmationMsg(string mobileNumber)
    {
        ISMSService _SMSService = new MockSMSService();
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

We have achieved a lot of flexibility and implemented separation of concerns in our code, but still we need to do a change on the code base to switch between the two SMS Services. So we need to implement Dependency Injection.

To achieve this, we need to implement a change to our (UIHandler) class constructor to pass the dependency through it, by doing this, the code which uses the (UIHandler) can determine which concrete implementation of (ISMSService) to use:

public class UIHandler
{
    private readonly ISMSService _SMSService;

    public UIHandler(ISMSService SMSService)
    {
        _SMSService = SMSService;
    }

    public void SendConfirmationMsg(string mobileNumber)
    {
        _SMSService.SendSMS(mobileNumber, "Your order has been shipped successfully!");
    }
}

Now the UI form which will talk with class (UIHandler) is responsible to pass which implementation of interface (ISMSService) to consume. This means we have inverted the control, the (UIHandler) is no longer responsible to decide which implementation to use, the calling code does. We have implemented the Inversion of Control principle which DI is one type of it.

The UI form code will be as below:

class Program
{
    static void Main(string[] args)
    {
        ISMSService _SMSService = new MockSMSService(); // dependency

        UIHandler _UIHandler = new UIHandler(_SMSService);
        _UIHandler.SendConfirmationMsg("96279544480");

        Console.ReadLine();
    }
}

How to compare two dates in php

you can try something like:

        $date1 = date_create('2014-1-23'); // format of yyyy-mm-dd
        $date2 = date_create('2014-2-3'); // format of yyyy-mm-dd
        $dateDiff = date_diff($date1, $date2);
        var_dump($dateDiff);

You can then access the difference in days like this $dateDiff->d;

How to ensure that there is a delay before a service is started in systemd?

Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.

For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):

[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'

Simply replace nc -z -v -w1 localhost 443 with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.

For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.

How I can check whether a page is loaded completely or not in web driver?

You can take a screenshot and save the rendered page in a location and you can check the screenshot if the page loaded completely without broken images

Proper way to handle multiple forms on one page in Django

A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):

if request.method == 'POST':
    bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
    if bannedphraseform.is_valid():
        bannedphraseform.save()
else:
    bannedphraseform = BannedPhraseForm(prefix='banned')

if request.method == 'POST' and not bannedphraseform.is_valid():
    expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
    bannedphraseform = BannedPhraseForm(prefix='banned')
    if expectedphraseform.is_valid():
        expectedphraseform.save()

else:
    expectedphraseform = ExpectedPhraseForm(prefix='expected')

Finding last occurrence of substring in string, replacing that

To replace from the right:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

In use:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'

database attached is read only

You need to go to the new folder properties > security tab, and give permissions to the SQL user that has rights on the DATA folder from the SQL server installation folder.

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

Android Studio - Gradle sync project failed

I know this is an old thread but I ended up here with the same issue.

I solved it by comparing the dependencies classpath in the build.gradle script(Project) to the installed version.

The error message was pointing to the following folder

C:\Program Files\Android\android-studio3 preview\gradle\m2repository\com\android\tools\build\gradle

It turned out that the alpha2 version was installed but the classpath was still pointing to alpaha1. A simple change to the classpath ('com.android.tools.build:gradle:3.0.0-alpha2') was all that was needed.

This may not help everyone, but I do hope it help most people out.

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

Gson - convert from Json to a typed ArrayList<T>

Your JSON sample is:

{
    "status": "ok",
    "comment": "",
    "result": {
    "id": 276,
    "firstName": "mohamed",
    "lastName": "hussien",
    "players": [
            "player 1",
            "player 2",
            "player 3",
            "player 4",
            "player 5"
    ]
}

so if you want to save arraylist of modules in your SharedPrefrences so :

1- will convert your returned arraylist for json format using this method

public static String toJson(Object jsonObject) {
    return new Gson().toJson(jsonObject);
}

2- Save it in shared prefreneces

PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));

3- to retrieve it at any time get JsonString from Shared preferences like that

String playersString= PreferencesUtils.getInstance(this).getString("players");

4- convert it again to array list

public static Object fromJson(String jsonString, Type type) {
    return new Gson().fromJson(jsonString, type);
}

ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString,
                    new TypeToken<ArrayList<String>>() {
                    }.getType());

this solution also doable if you want to parse ArrayList of Objects Hope it's help you by using Gson Library .

How to create a box when mouse over text in pure CSS?

You can write like this:

CSS

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;

}
span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
}
p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
}

p:hover span{
    display:block;
}

HTML

<p>Hover here<span>some text here ?</span></p>

Check this http://jsfiddle.net/UNs9J/1/

Spring RestTemplate GET with parameters

OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

How to unload a package without restarting R

You can try all you want to remove a package (and all the dependencies it brought in alongside) using unloadNamespace() but the memory footprint will still persist. And no, detach("package:,packageName", unload=TRUE, force = TRUE) will not work either.

From a fresh new console or Session > Restart R check memory with the pryr package:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

Check my sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

Let's load the Seurat package and check the new memory footprint:

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

Let's use unloadNamespace() to remove everything:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

Now check sessionInfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

Check the memory footprint:

pryr::mem_used()

# 173 MB

Link to screen-cast demonstration

Eclipse : Maven search dependencies doesn't work

Use https://search.maven.org/ manually with the prefix fc: to search for class names. Both Netbeans and Eclipse seem to be too stupid to use that search interface and the gigabytes of downloaded repository indexes seem to not contain any class information. Total waste of disk space. Those IDE projects are so badly maintained lately, I wish they would move development to GitHub.

Join two data frames, select all columns from one and some columns from the other

Here is the code snippet that does the inner join and select the columns from both dataframe and alias the same column to different column name.

emp_df  = spark.read.csv('Employees.csv', header =True);
dept_df = spark.read.csv('dept.csv', header =True)


emp_dept_df = emp_df.join(dept_df,'DeptID').select(emp_df['*'], dept_df['Name'].alias('DName'))
emp_df.show()
dept_df.show()
emp_dept_df.show()
Output  for 'emp_df.show()':

+---+---------+------+------+
| ID|     Name|Salary|DeptID|
+---+---------+------+------+
|  1|     John| 20000|     1|
|  2|    Rohit| 15000|     2|
|  3|    Parth| 14600|     3|
|  4|  Rishabh| 20500|     1|
|  5|    Daisy| 34000|     2|
|  6|    Annie| 23000|     1|
|  7| Sushmita| 50000|     3|
|  8| Kaivalya| 20000|     1|
|  9|    Varun| 70000|     3|
| 10|Shambhavi| 21500|     2|
| 11|  Johnson| 25500|     3|
| 12|     Riya| 17000|     2|
| 13|    Krish| 17000|     1|
| 14| Akanksha| 20000|     2|
| 15|   Rutuja| 21000|     3|
+---+---------+------+------+

Output  for 'dept_df.show()':
+------+----------+
|DeptID|      Name|
+------+----------+
|     1|     Sales|
|     2|Accounting|
|     3| Marketing|
+------+----------+

Join Output:
+---+---------+------+------+----------+
| ID|     Name|Salary|DeptID|     DName|
+---+---------+------+------+----------+
|  1|     John| 20000|     1|     Sales|
|  2|    Rohit| 15000|     2|Accounting|
|  3|    Parth| 14600|     3| Marketing|
|  4|  Rishabh| 20500|     1|     Sales|
|  5|    Daisy| 34000|     2|Accounting|
|  6|    Annie| 23000|     1|     Sales|
|  7| Sushmita| 50000|     3| Marketing|
|  8| Kaivalya| 20000|     1|     Sales|
|  9|    Varun| 70000|     3| Marketing|
| 10|Shambhavi| 21500|     2|Accounting|
| 11|  Johnson| 25500|     3| Marketing|
| 12|     Riya| 17000|     2|Accounting|
| 13|    Krish| 17000|     1|     Sales|
| 14| Akanksha| 20000|     2|Accounting|
| 15|   Rutuja| 21000|     3| Marketing|
+---+---------+------+------+----------+

ruby LoadError: cannot load such file

I just came across a similar problem. Try

require './st.rb'

This should do the trick.

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Uses of Action delegate in C#

I used the action delegate like this in a project once:

private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { 
            {typeof(TextBox), c => ((TextBox)c).Clear()},
            {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
            {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
            {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
            {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
            {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
    };

which all it does is store a action(method call) against a type of control so that you can clear all the controls on a form back to there defaults.

How to clear memory to prevent "out of memory error" in excel vba?

If you operate on a large dataset, it is very possible that arrays will be used. For me creating a few arrays from 500 000 rows and 30 columns worksheet caused this error. I solved it simply by using the line below to get rid of array which is no longer necessary to me, before creating another one:

Erase vArray

Also if only 2 columns out of 30 are used, it is a good idea to create two 1-column arrays instead of one with 30 columns. It doesn't affect speed, but there will be a difference in memory usage.

How to call an action after click() in Jquery?

setTimeout may help out here

$("#message_link").click(function(){
   setTimeout(function() {
       if (some_conditions...){
           $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
       }
   }, 100);
});

That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.

Find a line in a file and remove it

    public static void deleteLine() throws IOException {
        RandomAccessFile file = new RandomAccessFile("me.txt", "rw");
        String delete;
        String task="";
        byte []tasking;
        while ((delete = file.readLine()) != null) {
            if (delete.startsWith("BAD")) {
                continue;
            }
            task+=delete+"\n";
        }
        System.out.println(task);
        BufferedWriter writer = new BufferedWriter(new FileWriter("me.txt"));
        writer.write(task);
        file.close();
        writer.close();
    }

Disable activity slide-in animation when launching new activity?

Apply

startActivity(new Intent(FirstActivity.this,SecondActivity.class));

then

overridePendingTransition(0, 0);

This will stop the animation.

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

Requested bean is currently in creation: Is there an unresolvable circular reference?

i encountered this error in quite a stupid way

@Autowired
// private Bean bean;

public void myMethod() {
  return;
}

what happened is that I commented a line for some reason and left the annotation which made spring think that the method needs to be autowired

CSS/HTML: What is the correct way to make text italic?

I'd say use <em> to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...

If you're emphasizing text for ANY reason, you could use <em>, or a class that italicizes your text.

It's OK to break the rules sometimes!

Explanation of <script type = "text/template"> ... </script>

It's a way of adding text to HTML without it being rendered or normalized.

It's no different than adding it like:

 <textarea style="display:none"><span>{{name}}</span></textarea>

How to get an array of specific "key" in multidimensional array without looping

PHP 5.5+

Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.

PHP < 5.3

Wordpress 3.1+

In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.

PHP < 5.3

If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

Bootstrap modal opening on page load

I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.

With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.

<script type="text/javascript">
$('#memberModal').modal('show');
</script>

How can I submit form on button click when using preventDefault()?

Ok, first e.preventDefault(); it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this

$('#subscription_order_form').submit(function(e){
    $.ajax({
     url: $(this).attr('action'),
     data : $(this).serialize(),
     success : function (data){

      }
   });
    e.preventDefault();
});

How to fix curl: (60) SSL certificate: Invalid certificate chain

First off, you should be wary of urls that throw SSL errors. That being said, you can suppress certificate errors in curl with

curl -k https://insecure.url/content-i-really-really-trust

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

Possible cases for Javascript error: "Expected identifier, string or number"

This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example

class Dojo implements Sensei {
     console.log('Hi'); // ERROR Identifier expected.
     constructor(){}
}

Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

What causes java.lang.IncompatibleClassChangeError?

My answer, I believe, will be Intellij specific.

I had rebuilt clean, even going as far as to manually delete the "out" and "target" dirs. Intellij has a "invalidate caches and restart", which sometimes clears odd errors. This time it didn't work. The dependency versions all looked correct in the project settings->modules menu.

The final answer was to manually delete my problem dependency from my local maven repo. An old version of bouncycastle was the culprit(I knew I had just changed versions and that would be the problem) and although the old version showed up no where in what was being built, it solved my problem. I was using intellij version 14 and then upgraded to 15 during this process.

must declare a named package eclipse because this compilation unit is associated to the named module

Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.

Quick fix:

  1. Create a package eg. helloWorld inside the src folder.
  2. Move helloWorld.java file in that package. Just drag and drop on the package. Error should disappear.

Explanation:

  • My Eclipse version: 2020-09 (4.17.0)
  • My Java version: Java 15, 2020-09-15

Latest version of Eclipse required java11 or above. The module feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules

When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java file. If you select don't create then module-info.java will not create and your project will free from this issue.

Best practice is while crating project, after giving project name. Click on next button instead of finish. On next page at the bottom it ask for creation of module-info.java file. Select or deselect as per need.

If selected: (by default) click on finish button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.

If deselect: No issue