Programs & Examples On #Screen capture

Screen capturing is the act of copying the content of the screen to an image or other data structure, either to a file or memory.

How to prevent Screen Capture in Android

For Java users write this line above your setContentView(R.layout.activity_main);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

For kotlin users

window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)

How to capture the android device screen content?

AFAIK, All of the methods currently to capture a screenshot of android use the /dev/graphics/fb0 framebuffer. This includes ddms. It does require root to read from this stream. ddms uses adbd to request the information, so root is not required as adb has the permissions needed to request the data from /dev/graphics/fb0.

The framebuffer contains 2+ "frames" of RGB565 images. If you are able to read the data, you would have to know the screen resolution to know how many bytes are needed to get the image. each pixel is 2 bytes, so if the screen res was 480x800, you would have to read 768,000 bytes for the image, since a 480x800 RGB565 image has 384,000 pixels.

Capture iOS Simulator video for App Preview

You can do this for free with the following tools. You will need at least one real device (I used an iPhone 5)

Capture the video with the simple, but excellent appshow (note this is a very barebones tool, but it's very easy to learn). This will export at the native device resolution (640x1136).

Resize with ffmpeg. Due to rounding, you can go directly between the resolutions, but you have to oversize and then crop.

ffmpeg -i video.mov -filter:v scale=1084:1924 -c:a copy video_1084.mov
ffmpeg -i video_1084.mov -filter:v "crop=1080:1920:0:0" -c:a copy video_1080.mov

For ipad, you can crop and then add a letterbox. However, cropping like this usually won't yield a video that looks exactly like your app does on the ipad. YMMV.

ffmpeg -i video.mov -filter:v "crop=640:960:0:0" -c:a copy video_640_960.mo
ffmpeg -i video_640_960.mov -filter:v "pad=768:1024:64:32" -c:a copy video_768_1024.mov
ffmpeg -i video_768_1024.mov -filter:v scale=900:1200 -c:a copy video_900_1200.mov

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

How good is Java's UUID.randomUUID?

UUID uses java.security.SecureRandom, which is supposed to be "cryptographically strong". While the actual implementation is not specified and can vary between JVMs (meaning that any concrete statements made are valid only for one specific JVM), it does mandate that the output must pass a statistical random number generator test.

It's always possible for an implementation to contain subtle bugs that ruin all this (see OpenSSH key generation bug) but I don't think there's any concrete reason to worry about Java UUIDs's randomness.

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

How to show shadow around the linearlayout in Android?

Create a new XML by example named "shadow.xml" at DRAWABLE with the following code (you can modify it or find another better):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/middle_grey"/>
        </shape>
    </item>

    <item android:left="2dp"
          android:right="2dp"
          android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white"/>
        </shape>
    </item>

</layer-list>

After creating the XML in the LinearLayout or another Widget you want to create shade, you use the BACKGROUND property to see the efect. It would be something like :

<LinearLayout
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingRight="@dimen/margin_med"
    android:background="@drawable/shadow"
    android:minHeight="?attr/actionBarSize"
    android:gravity="center_vertical">

Laravel form html with PUT method for PUT routes

<form action="{{url('/url_part_in_route').'/'.$parameter_of_update_function_of_resource_controller}}"  method="post">
@csrf
<input type="hidden" name="_method" value="PUT">    //   or @method('put')          
....    //  remained instructions                                                                              
<form>

How to change the Title of the window in Qt?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowTitle("Main Page");
    w.show();
    return a.exec();
}

enter image description here

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

you need to configure this in web.xml as well.Please refer below code.

<taglib>
    <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/lib/c.tld</taglib-location>
</taglib>

Please let me know if you still face any issue.

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

Case insensitive comparison of strings in shell script

For zsh the syntax is slightly different, but still shorter than most answers here:

> str1='mAtCh'
> str2='MaTcH'
> [[ "$str1:u" = "$str2:u" ]] && echo 'Strings Match!'
Strings Match!
>

This will convert both strings to uppercase before the comparison.


Another method makes use zsh's globbing flags, which allows us to directly make use of case-insensitive matching by using the i glob flag:

setopt extendedglob
[[ $str1 = (#i)$str2 ]] && echo "Match success"
[[ $str1 = (#i)match ]] && echo "Match success"

Find the most popular element in int[] array

Array elements value should be less than the array length for this one:

public void findCounts(int[] arr, int n) {
    int i = 0;

    while (i < n) {
        if (arr[i] <= 0) {
            i++;
            continue;
        }

        int elementIndex = arr[i] - 1;

        if (arr[elementIndex] > 0) {
            arr[i] = arr[elementIndex];
            arr[elementIndex] = -1;
        }
        else {
            arr[elementIndex]--;
            arr[i] = 0;
            i++;
        }
    }

    Console.WriteLine("Below are counts of all elements");

    for (int j = 0; j < n; j++) {
        Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
    }
}

Time complexity of this will be O(N) and space complexity will be O(1).

Running Facebook application on localhost

I wrote a tutorial about this a while ago.

The most important point is the "Site URL":

Site URL: http://localhost/app_name/

Where the folder structure is something like:

app_name
¦   index.php
¦
+---canvas
¦   ¦   index.php
¦   ¦
¦   +---css
¦           main.css
¦           reset.css
¦
+---src
        facebook.php
        fb_ca_chain_bundle.crt

EDIT:
Kavya: how does the FB server recognize my localhost even without an IP or port??

I don't think this has anything to do with Facebook, I guess since the iframe src parameter is loaded from client-side it'll treat your local URL as if you put it directly on your browser.

For example have a file on your online server with content (e.g. online.php):

<iframe src="http://localhost/test.php" width="100%" height="100%">
    <p>Not supported!</p>
</iframe>

And on your localhost root directory, have the file test.php:

<?php echo "Hello from Localhost!"; ?>

Now visit http://your_domain.com/online.php you will see your localhost file's content!

This is why realtime subscriptions and deauthorize callbacks (just to mention) won't work with localhost URLs! because Facebook will ping (send http requests) to these URLs but obviously Facebook server won't translate those URLs to yours!

Remove a character at a certain position in a string - javascript

Turn the string into array, cut a character at specified index and turn back to string

let str = 'Hello World'.split('')

str.splice(3, 1)
str = str.join('')

// str = 'Helo World'.

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

CSS Image size, how to fill, but not stretch?

CSS solution no JS and no background image:

Method 1 "margin auto" ( IE8+ - NOT FF!):

_x000D_
_x000D_
div{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  position:relative;_x000D_
  overflow:hidden;_x000D_
}_x000D_
div img{_x000D_
  position:absolute; _x000D_
  top:0; _x000D_
  bottom:0; _x000D_
  margin: auto;_x000D_
  width:100%;_x000D_
}
_x000D_
<p>Original:</p>_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
_x000D_
<p>Wrapped:</p>_x000D_
<div>_x000D_
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/

Method 2 "transform" ( IE9+ ):

_x000D_
_x000D_
div{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  position:relative;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
div img{_x000D_
  position:absolute; _x000D_
  width:100%;_x000D_
  top: 50%;_x000D_
  -ms-transform: translateY(-50%);_x000D_
  -webkit-transform: translateY(-50%);_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<p>Original:</p>_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
_x000D_
<p>Wrapped:</p>_x000D_
<div>_x000D_
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/1/

Method 2 can be used to center an image in a fixed width / height container. Both can overflow - and if the image is smaller than the container it will still be centered.

http://jsfiddle.net/5xjr05dt/3/

Method 3 "double wrapper" ( IE8+ - NOT FF! ):

_x000D_
_x000D_
.outer{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  margin: 200px auto; /* just for example */_x000D_
  border: 1px solid red; /* just for example */_x000D_
  /* overflow: hidden; */ /* TURN THIS ON */_x000D_
  position: relative;_x000D_
}_x000D_
.inner { _x000D_
    border: 1px solid green; /* just for example */_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    margin: auto;_x000D_
    display: table;_x000D_
    left: 50%;_x000D_
}_x000D_
.inner img {_x000D_
    display: block;_x000D_
    border: 1px solid blue; /* just for example */_x000D_
    position: relative;_x000D_
    right: 50%;_x000D_
    opacity: .5; /* just for example */_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
     <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/5/

Method 4 "double wrapper AND double image" ( IE8+ ):

_x000D_
_x000D_
.outer{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  margin: 200px auto; /* just for example */_x000D_
  border: 1px solid red; /* just for example */_x000D_
  /* overflow: hidden; */ /* TURN THIS ON */_x000D_
  position: relative;_x000D_
}_x000D_
.inner { _x000D_
    border: 1px solid green; /* just for example */_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    bottom: 0;_x000D_
    display: table;_x000D_
    left: 50%;_x000D_
}_x000D_
.inner .real_image {_x000D_
    display: block;_x000D_
    border: 1px solid blue; /* just for example */_x000D_
    position: absolute;_x000D_
    bottom: 50%;_x000D_
    right: 50%;_x000D_
    opacity: .5; /* just for example */_x000D_
}_x000D_
_x000D_
.inner .placeholder_image{_x000D_
  opacity: 0.1; /* should be 0 */_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <img class="real_image" src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
    <img class="placeholder_image"  src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/26/

  • Method 1 has slightly better support - you have to set the width OR height of image!
  • With the prefixes method 2 also has decent support ( from ie9 up ) - Method 2 has no support on Opera mini!
  • Method 3 uses two wrappers - can overflow width AND height.
  • Method 4 uses a double image ( one as placeholder ) this gives some extra bandwidth overhead, but even better crossbrowser support.

Method 1 and 3 don't seem to work with Firefox

Do you use source control for your database items?

I have used the dbdeploy tool from ThoughtWorks at http://dbdeploy.com/. It encourages the use of migration scripts. Each release, we consolidated the change scripts into a single file to ease understanding and to allow DBAs to 'bless' the changes.

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Hibernate-sequence doesn't exist

You can also put :

@GeneratedValue(strategy = GenerationType.IDENTITY)

And let the DateBase manage the incrementation of the primary key:

AUTO_INCREMENT PRIMARY KEY

MongoDB running but can't connect using shell

I had same problem. In my case MongoDB server wasn't running.

Try to open this in your web browser:

http://localhost:28017

If you can't, this means that you have to start MongoDB server.

Run mongod in another terminal tab. Then in your main tab run mongo which is is the shell that connects to your MongoDB server.

How to get access to job parameters from ItemReader, in Spring Batch?

As was stated, your reader needs to be 'step' scoped. You can accomplish this via the @Scope("step") annotation. It should work for you if you add that annotation to your reader, like the following:

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("foo-reader")
@Scope("step")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }

  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

This scope is not available by default, but will be if you are using the batch XML namespace. If you are not, adding the following to your Spring configuration will make the scope available, per the Spring Batch documentation:

<bean class="org.springframework.batch.core.scope.StepScope" />

How to group pandas DataFrame entries by date in a non-unique column

I'm using pandas 0.16.2. This has better performance on my large dataset:

data.groupby(data.date.dt.year)

Using the dt option and playing around with weekofyear, dayofweek etc. becomes far easier.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Array Length in Java

First of all, length is a property, so it would be arr.length instead of arr.length().

And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.

What is the use of DesiredCapabilities in Selenium WebDriver?

You should read the documentation about DesiredCapabilities. There is also a different page for the ChromeDriver. Javadoc from Capabilities:

Capabilities: Describes a series of key/value pairs that encapsulate aspects of a browser.

Basically, the DesiredCapabilities help to set properties for the WebDriver. A typical usecase would be to set the path for the FirefoxDriver if your local installation doesn't correspond to the default settings.

Finding a substring within a list in Python

Use a simple for loop:

seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'

for text in seq:
    if sub in text:
        print(text)

yields

abc123

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

I had this same problem described in the following way: If I typed

$ git diff

Git simply returned to the prompt with no error.

If I typed

$ git diff <filename>

Git simply returned to the prompt with no error.

Finally, by reading around I noticed that git diff actually calls the mingw64\bin\diff.exe to do the work.

Here's the deal. I'm running Windows and had installed another Bash utility and it changed my path so it no longer pointed to my mingw64\bin directory.

So if you type:

git diff

and it just returns to the prompt you may have this problem.

The actual diff.exe which is run by git is located in your mingw64\bin directory

Finally, to fix this, I actually copied my mingw64\bin directory to the location Git was looking for it in. I tried it and it still didn't work.

Then, I closed my Git Bash window and opened it again went to my same repository that was failing and now it works.

TokenMismatchException in VerifyCsrfToken.php Line 67

I have also faced the same issue and solved it later. first of all execute the artisan command:

php artisan cache:clear

And after that restart the project. Hope it will help.

Postman: sending nested JSON object

Simply add these parameters : In the header option of the request, add Content-Type:application/json

header content-type postman json

and in the body, select Raw format and put your json params like {'guid':'61791957-81A3-4264-8F32-49BCFB4544D8'}

json request postman

I've found the solution on http://www.iminfo.in/post/post-json-postman-rest-client-chrome

docker: executable file not found in $PATH

problem is glibc, which is not part of apline base iamge.

After adding it worked for me :)

Here are the steps to get the glibc

apk --no-cache add ca-certificates wget
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
apk add glibc-2.28-r0.apk

What is your favorite C programming trick?

I always liked dumb preprocessor tricks to make generic container types:

/* list.h */
#ifndef CONTAINER_TYPE
#define CONTAINER_TYPE VALUE_TYPE ## List
#endif
typedef struct CONTAINER_TYPE {
    CONTAINER_TYPE *next;
    VALUE_TYPE v;
} CONTAINER_TYPE;
/* Possibly Lots of functions for manipulating Lists
*/
#undef VALUE_TYPE
#undef CONTAINER_TYPE

Then you can do e.g.:

#define VALUE_TYPE int
#include "list.h"
typedef struct myFancyStructure *myFancyStructureP;
#define VALUE_TYPE myFancyStructureP
#define CONTAINER_TYPE mfs
#include "list.h"

And never write a linked list again. If VALUE_TYPE is always going to be a pointer, then this is an overkill, since a void * would work just as well. But there are often very small structures for which the overhead of indirection often doesn't make sense. Also, you gain type checking (i.e. you might not want to concatenate a linked list of strings with a linked list of doubles, even though both would work in a void * linked list).

Java 8 stream map to list of keys sorted by values

Here is the simple solution with StreamEx

EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();

How do C++ class members get initialized if I don't do it explicitly?

In lieu of explicit initialization, initialization of members in classes works identically to initialization of local variables in functions.

For objects, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object's class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.

For primitive types (pointers, ints, etc), they are not initialized -- they contain whatever arbitrary junk happened to be at that memory location previously.

For references (e.g. std::string&), it is illegal not to initialize them, and your compiler will complain and refuse to compile such code. References must always be initialized.

So, in your specific case, if they are not explicitly initialized:

    int *ptr;  // Contains junk
    string name;  // Empty string
    string *pname;  // Contains junk
    string &rname;  // Compile error
    const string &crname;  // Compile error
    int age;  // Contains junk

Error: Java: invalid target release: 11 - IntelliJ IDEA

I changed file -> project structure -> project settings -> modules In the source tab, I set the Language Level from : 14, or 11, to: "Project Default". This fixed my issue.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Proper way to initialize C++ structs

Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

How do I return a char array from a function?

With Boost:

boost::array<char, 10> testfunc()
{
    boost::array<char, 10> str;

    return str;
}

A normal char[10] (or any other array) can't be returned from a function.

git pull remote branch cannot find remote ref

check your branch on your repo. maybe someone delete it.

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

Conditional statement in a one line lambda function in python?

Yes, you can use the shorthand syntax for if statements.

rate = lambda(t): (200 * exp(-t)) if t > 200 else (400 * exp(-t))

Note that you don't use explicit return statements inlambdas either.

What is the difference between ng-if and ng-show/ng-hide

Fact, that ng-if directive, unlike ng-show, creates its own scope, leads to interesting practical difference:

_x000D_
_x000D_
angular.module('app', []).controller('ctrl', function($scope){_x000D_
  $scope.delete = function(array, item){_x000D_
    array.splice(array.indexOf(item), 1);_x000D_
  }_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app='app' ng-controller='ctrl'>_x000D_
   <h4>ng-if:</h4>_x000D_
   <ul ng-init='arr1 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr1'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
        <button ng-if='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-show:</h4>_x000D_
   <ul ng-init='arr2 = [1,2,3]'>_x000D_
      <li ng-repeat='x in arr2'>_x000D_
        {{show}}_x000D_
        <button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
        <button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
        <button ng-show='show' ng-click='show=!show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
   _x000D_
   <h4>ng-if with $parent:</h4>_x000D_
    <ul ng-init='arr3 = [1,2,3]'>_x000D_
      <li ng-repeat='item in arr3'>_x000D_
        {{show}}_x000D_
        <button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
        <button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
      </li>_x000D_
   </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

At first list, on-click event, show variable, from innner/own scope, is changed, but ng-if is watching on another variable from outer scope with same name, so solution not works. At case of ng-show we have the only one show variable, that is why it works. To fix first attempt, we should reference to show from parent/outer scope via $parent.show.

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

Jinja2 template variable if None Object set a default value

Following this doc you can do this that way:

{{ p.User['first_name']|default('NONE') }}

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

How to define Gradle's home in IDEA?

AFAIK it is GRADLE_HOME not GRADLE_USER_HOME (see gradle installation http://www.gradle.org/installation).

On the other hand I played a bit with Gradle support in Idea 13 Cardea and I think the gradle home is not automatically discover by Idea. If so you can file a issue in youtrack.

Also, if you use gradle 1.6+ you can use the Graldle support for setting the build and wrapper. I think idea automatically discover the wrapper based gradle project.

$ gradle setupBuild --type java-library

$ gradle wrapper

Note: Supported library types: basic, maven, java

Regards

Rollback to an old Git commit in a public repo

Let's say you work on a project and after a day or so. You notice one feature is still giving you errors. But you do not know what change you made that caused the error. So you have to fish previous working commits. To revert to a specific commit:

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 .

Ok, so that commit works for you. No more error. You pinpointed the issue. Now you can go back to latest commit:

git checkout 792d9294f652d753514dc2033a04d742decb82a5 .

And checkout a specific file before it caused the error (in my case I use example Gemfile.lock):

git checkout 8a0fe5191b7dfc6a81833bfb61220d7204e6b0a9 -- /projects/myproject/Gemfile.lock

And this is one way to handle errors you created in commits without realizing the errors until later.

How to do constructor chaining in C#

You use standard syntax (using this like a method) to pick the overload, inside the class:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

then:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Note also:

  • you can chain to constructors on the base-type using base(...)
  • you can put extra code into each constructor
  • the default (if you don't specify anything) is base()

For "why?":

  • code reduction (always a good thing)
  • necessary to call a non-default base-constructor, for example:

    SomeBaseType(int id) : base(id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };

Create a pointer to two-dimensional array

You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];

void test(int row, int col, uint8_t val)

{

   uint8_t* matrix_ptr = l_matrix;
   matrix_ptr [col+y*row] = val; // to assign a value

}

this is what the compiler would have done anyway.

How to run a script file remotely using SSH

Make the script executable by the user "Kev" and then remove the try it running through the command sh kev@server1 /test/foo.sh

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

What does --net=host option in Docker command really do?

  1. you can create your own new network like --net="anyname"
  2. this is done to isolate the services from different container.
  3. suppose the same service are running in different containers, but the port mapping remains same, the first container starts well , but the same service from second container will fail. so to avoid this, either change the port mappings or create a network.

How to change color of the back arrow in the new material theme?

This is what worked for me:

Add the below attributes to your theme.

To change toolbar/actionbar back arrow above api 21

<item name="android:homeAsUpIndicator">@drawable/your_drawable_icon</item>

To change toolbar/actionbar back arrow below api 21

<item name="homeAsUpIndicator">@drawable/your_drawable_icon</item>

To change action mode back arrow

<item name="actionModeCloseDrawable">@drawable/your_drawable_icon</item>

To remove toolbar/actionbar shadow

<item name="android:elevation" tools:targetApi="lollipop">0dp</item>
<item name="elevation">0dp</item>
<!--backward compatibility-->
<item name="android:windowContentOverlay">@null</item>

To change actionbar overflow drawable

<!--under theme-->
<item name="actionOverflowButtonStyle">@style/MenuOverflowStyle</item>

<style name="MenuOverflowStyle" parent="Widget.AppCompat.ActionButton.Overflow">
<item name="srcCompat">@drawable/ic_menu_overflow</item>

Note : 'srcCompat' is used instead of 'android:src' because of vector drawable support for api below 21

How to use UIPanGestureRecognizer to move object? iPhone/iPad

Casting my hat into the ring a couple years later.

Will need to save the beginning center of the image view:

var panBegin: CGPoint.zero

Then update the new center using a transform:

if recognizer.state == .began {
     panBegin = imageView!.center

} else if recognizer.state == .ended {
    panBegin = CGPoint.zero

} else if recognizer.state == .changed {
    let translation = recognizer.translation(in: view)
    let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)

    imageView!.center = panBegin.applying(panOffsetTransform)
}

How to align the checkbox and label in same line in html?

If you are using bootstrap wrap your label and input with a div of a "checkbox" or "checkbox-inline" class.

<li>
    <div class="checkbox">
        <label><input type="checkbox" value="">Option 1</label>
    </div>
</li>

Reference: https://www.w3schools.com/bootstrap/bootstrap_forms_inputs.asp

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

Javascript variable access in HTML

<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];

window.onload = function() {
       //when the document is finished loading, replace everything
       //between the <a ...> </a> tags with the value of splitText
   document.getElementById("myLink").innerHTML=splitText;
} 

</script>

<body>
<a id="myLink" href = test.html></a>
</body>
</html>

How to use FormData for AJAX file upload?

Good morning.

I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.

<input type="file" name="files[]" multiple>

I did not make any modification on FormData.

Create an empty object in JavaScript with {} or new Object()?

Objects

There is no benefit to using new Object(); - whereas {}; can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
        title:  'Frog',
        url:    '/img/picture.jpg',
        width:  300,
        height: 200
      };

Arrays

For arrays, there's similarly almost no benefit to ever using new Array(); over []; - with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined - which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); - it's clunkier than {}; and looks silly.
  2. Always use []; - except when you need to quickly create an "empty" array with a predefined length.

Creating a new ArrayList in Java

Java 8

In order to create a non-empty list of fixed size where different operations like add, remove, etc won't be supported:

List<Integer> fixesSizeList= Arrays.asList(1, 2);

Non-empty mutable list:

List<Integer> mutableList = new ArrayList<>(Arrays.asList(3, 4));

Java 9

With Java 9 you can use the List.of(...) static factory method:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

Java 10

With Java 10 you can use the Local Variable Type Inference:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

Check out more ArrayList examples here.

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

How to "grep" out specific line ranges of a file

Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:

sed "/First Line of Text/,/Last Line of Text/d" filename

which deletes all lines from the first matched line to the last match, including those lines.

Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

deleting rows in numpy array

numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...

Characters allowed in a URL

If you like to give a special kind of experience to the users you could use pushState to bring a wide range of characters to the browser's url:

enter image description here

var u="";var tt=168;
for(var i=0; i< 250;i++){
 var x = i+250*tt;
console.log(x);
 var c = String.fromCharCode(x);
 u+=c; 
}
history.pushState({},"",250*tt+u);

Create SQLite database in android

A simple database example to insert Todo List of day today life in DB and get list of all todo list.

public class MyDatabaseHelper extends SQLiteOpenHelper {

// Logcat tag
private static final String LOG = "DatabaseHelper";

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SQLiteDemoDB";

// Table Names
private static final String TABLE_TODO = "todos";

// column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
private static final String KEY_TODO = "todoDescr";

// *********************************************************************************************
public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_TABLE_TODO);


}

// Upgrading database **************************************************************************
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);


    // Create tables again
    onCreate(db);
}

// Creating Table TABLE_TEAM
String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_TODO + " text, "
        + KEY_CREATED_AT + " text" + ")";


// insert values of todo
public boolean InsertTodoDetails(String todo, String createdAt) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TODO, todo);
    contentValues.put(KEY_CREATED_AT, createdAt);


    long rowInserted = db.insert(TABLE_TODO, null, contentValues);
    db.close();
    return true;
}


// Select values of todo
public Cursor GetAllTodoDetails() {
    SQLiteDatabase db = this.getReadableDatabase();


    String query = "SELECT * FROM " + TABLE_TODO;
    Cursor mcursor = db.rawQuery(query, null);

    if (mcursor != null) {
        mcursor.moveToFirst();
    }

    return mcursor;

}



}

My activity To save and get the record.

public class MyDbActivity extends AppCompatActivity {

    @Bind(R.id.edt_todo)
    EditText edtTodo;
    @Bind(R.id.btn_save)
    Button btnSave;

    MyDatabaseHelper db;
    @Bind(R.id.btn_getTodo)
    Button btnGetTodo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_db);
        ButterKnife.bind(this);

// creating database object
        db = new MyDatabaseHelper(this);


    }

    @OnClick(R.id.btn_save)
    public void onViewClicked() {


        String datetime = "";
        try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            datetime = dateformat.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }

        db.InsertTodoDetails(edtTodo.getText().toString().trim(), datetime);

    }

    @OnClick(R.id.btn_getTodo)
    public void onGetTodoClicked() {
        String todos = "";
        Cursor TodoList = db.GetAllTodoDetails();
        if (TodoList.moveToFirst()) {
            do {
                if (todos.equals("")) {
                    todos = TodoList.getString(TodoList.getColumnIndex("todoDescr"));

                } else {
                    todos = todos + ", " + TodoList.getString(TodoList.getColumnIndex("todoDescr"));
                }
                // do what ever you want here
            } while (TodoList.moveToNext());
        }
        TodoList.close();
        Toast.makeText(this, "" + todos, Toast.LENGTH_SHORT).show();

    }
}

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

Convert XML to JSON (and back) using Javascript

I would personally recommend this tool. It is an XML to JSON converter.

It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

It also takes the XML attributes into considerations.

var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
var json = xml2json(xml); 

console.log(json); 
// prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’

Here's an online demo!

Run JavaScript code on window close or page refresh?

The event is called beforeunload, so you can assign a function to window.onbeforeunload.

How can I get the file name from request.FILES?

NOTE if you are using python 3.x:

request.FILES is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile'] you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:

list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
    filename = f.name
    list.append(filename)

of course one can squeeze the whole thing in one line, but this is easy to understand

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

You can't with inline styling alone. Do not recommend reimplementing CSS features in JavaScript we already have a language that is extremely powerful and incredibly fast built for this use case -- CSS. So use it! Made Style It to assist.

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      .intro:hover {
        color: red;
      }

    `,
      <p className="intro">CSS-in-JS made simple -- just Style It.</p>
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        .intro:hover {
          color: red;
        }
      `}

      <p className="intro">CSS-in-JS made simple -- just Style It.</p>
    </Style>
  }
}

export default Intro;

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

Serializing PHP object to JSON

Change to your variable types private to public

This is simple and more readable.

For example

Not Working;

class A{
   private $var1="valuevar1";
   private $var2="valuevar2";
   public function tojson(){
    return json_encode($this)
   }
}

It is Working;

class A{
   public $var1="valuevar1";
   public $var2="valuevar2";
   public function tojson(){
    return json_encode($this)
   }
}

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I ran into the same problem while installing a package via npm.

After creating the npm folder manually in C:\Users\UserName\AppData\Roaming\ that particular error was gone, but it gave similar multiple errors as it tried to create additional directories in the npm folder and failed. The issue was resolved after running the command prompt as an administrator.

Passing base64 encoded strings in URL

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

Do I really need to encode '&' as '&amp;'?

if & is used in html then you should escape it

If & is used in javascript strings e.g. an alert('This & that'); or document.href you don't need to use it.

If you're using document.write then you should use it e.g. document.write(<p>this &amp; that</p>)

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

What is the difference between int, Int16, Int32 and Int64?

They both are indeed synonymous, However i found the small difference between them,

1)You cannot use Int32 while creatingenum

enum Test : Int32
{ XXX = 1   // gives you compilation error
}

enum Test : int
{ XXX = 1   // Works fine
}

2) Int32 comes under System declaration. if you remove using.System you will get compilation error but not in case for int

How to encode a string in JavaScript for displaying in HTML?

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))

jQuery form input select by id

For example like this:

var value = $("#a").find("#b").val()

How to track untracked content?

I just had the same problem. The reason was because there was a subfolder that contained a ".git" folder. Removing it made git happy.

Read properties file outside JAR file

I have an example of doing both by classpath or from external config with log4j2.properties

package org.mmartin.app1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;


public class App1 {
    private static Logger logger=null; 
    private static final String LOG_PROPERTIES_FILE = "config/log4j2.properties";
    private static final String  CONFIG_PROPERTIES_FILE = "config/config.properties";

    private Properties properties= new Properties();

    public App1() {
        System.out.println("--Logger intialized with classpath properties file--");
        intializeLogger1();
        testLogging();
        System.out.println("--Logger intialized with external file--");
        intializeLogger2();
        testLogging();
    }




    public void readProperties()  {
        InputStream input = null;
        try {
            input = new FileInputStream(CONFIG_PROPERTIES_FILE);
            this.properties.load(input);
        } catch (IOException e) {
            logger.error("Unable to read the config.properties file.",e);
            System.exit(1);
        }
    }

    public void printProperties() {
        this.properties.list(System.out);
    }

    public void testLogging() {
        logger.debug("This is a debug message");
        logger.info("This is an info message");
        logger.warn("This is a warn message");
        logger.error("This is an error message");
        logger.fatal("This is a fatal message");
        logger.info("Logger's name: "+logger.getName());
    }


    private void intializeLogger1() {
        logger = LogManager.getLogger(App1.class);
    }
    private void intializeLogger2() {
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        File file = new File(LOG_PROPERTIES_FILE);
        // this will force a reconfiguration
        context.setConfigLocation(file.toURI());
        logger = context.getLogger(App1.class.getName());
    }

    public static void main(String[] args) {
        App1 app1 = new App1();
        app1.readProperties();
        app1.printProperties();
    }
}


--Logger intialized with classpath properties file--
[DEBUG] 2018-08-27 10:35:14.510 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.513 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.513 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.513 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.513 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.514 [main] App1 - Logger's name: org.mmartin.app1.App1
--Logger intialized with external file--
[DEBUG] 2018-08-27 10:35:14.524 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.525 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.525 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.525 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - Logger's name: org.mmartin.app1.App1
-- listing properties --
dbpassword=password
database=localhost
dbuser=user

The 'json' native gem requires installed build tools

I have found that the error is sometimes caused by a missing library.

so If you install RDOC first by running

gem install rdoc

then install rails with:

gem install rails

then go back and install the devtools as mentioned before with:

1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install

then try installing json

which culminate with you finally being able to run

rails new project_name - without errors.

good luck

angularjs ng-style: background-image isn't working

The syntax is changed for Angular 2 and above:

[ngStyle]="{'background-image': 'url(path)'}"

Getting attribute using XPath

How could I get the value of lang (where lang=eng in book title), for the first element?

Use:

/*/book[1]/title/@lang

This means:

Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

To get just the string value of this attribute use the standard XPath function string():

string(/*/book[1]/title/@lang)

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt") and String.class.getClassLoader().getResourceAsStream("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

Read this article for more detailed information about that particular problem.


Warning for users of Tomcat 7 and below

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

As a result, you have to be extra careful when using ClassLoader.getResourceAsStream() or Class.getResourceAsStream() on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt") actually calls classLoader.getResourceAsStream("resource.txt") (the leading / is stripped).

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

The order of keys in dictionaries

>>> print sorted(d.keys())
['a', 'b', 'c']

Use the sorted function, which sorts the iterable passed in.

The .keys() method returns the keys in an arbitrary order.

Install Node.js on Ubuntu

Now you can simply install with:

sudo apt-get install nodejs
sudo apt-get install npm

Make sure you have the Python and C interpreters/compilers preinstalled. If not, perform:

sudo apt-get install python g++ make

Add items to comboBox in WPF

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I faced this Issue multiple times and they're all solved by disabling Instant Run.

How to use a findBy method with comparative criteria

The class Doctrine\ORM\EntityRepository implements Doctrine\Common\Collections\Selectable API.

The Selectable interface is very flexible and quite new, but it will allow you to handle comparisons and more complex criteria easily on both repositories and single collections of items, regardless if in ORM or ODM or completely separate problems.

This would be a comparison criteria as you just requested as in Doctrine ORM 2.3.2:

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('prize', 200));

$result = $entityRepository->matching($criteria);

The major advantage in this API is that you are implementing some sort of strategy pattern here, and it works with repositories, collections, lazy collections and everywhere the Selectable API is implemented.

This allows you to get rid of dozens of special methods you wrote for your repositories (like findOneBySomethingWithParticularRule), and instead focus on writing your own criteria classes, each representing one of these particular filters.

How do I do logging in C# without using 3rd party libraries?

You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

And here's the sample from MSDN:

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}

How to change legend title in ggplot

Since you have two densitys I imagine you may be wanting to set your own colours with scale_fill_manual.

If so you can do:

df <- data.frame(x=1:10,group=c(rep("a",5),rep("b",5)))

legend_title <- "OMG My Title"

ggplot(df, aes(x=x, fill=group)) + geom_density(alpha=.3) +   
    scale_fill_manual(legend_title,values=c("orange","red"))

enter image description here

Rounding a double to turn it into an int (java)

public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}

Sending HTTP Post request with SOAP action using org.apache.http

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

How to drop all tables from a database with one SQL query?

The simplest way is to drop the whole database and create it once again:

drop database db_name
create database db_name

That's all.

How to replace space with comma using sed?

I know it's not exactly what you're asking, but, for replacing a comma with a newline, this works great:

tr , '\n' < file

How to use '-prune' option of 'find' in sh?

Prune is a do not recurse at any directory switch.

From the man page

If -depth is not given, true; if the file is a directory, do not descend into it. If -depth is given, false; no effect.

Basically it will not desend into any sub directories.

Take this example:

You have the following directories

  • /home/test2
  • /home/test2/test2

If you run find -name test2:

It will return both directories

If you run find -name test2 -prune:

It will return only /home/test2 as it will not descend into /home/test2 to find /home/test2/test2

Eclipse: Set maximum line length for auto formatting?

I use the Eclipse version called Mars which works with Java 7.

Go to Preferences -> Java -> Code Style -> Formatter

Click on the Edit Button shown in the right side of "Active Profile" drop down

Tabs: "Line wrapping"

Field: "Maximum line width", Set the desired value (Default value set to 120) to increase/decrease the line length in the editor

Note: Remember to rename the Active profile to the name of your choice, as the default Eclipse profile won't accept your changes.

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

How to test which port MySQL is running on and whether it can be connected to?

netstat -tlpn

It will show the list something like below:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1393/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1859/master
tcp        0      0 123.189.192.64:7654     0.0.0.0:*               LISTEN      2463/monit
tcp        0      0 127.0.0.1:24135         0.0.0.0:*               LISTEN      21450/memcached
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      16781/mysqld

Use as root for all details. The -t option limits the output to TCP connections, -l for listening ports, -p lists the program name and -n shows the numeric version of the port instead of a named version.

In this way you can see the process name and the port.

Proper use of 'yield return'

I tend to use yield-return when I calculate the next item in the list (or even the next group of items).

Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.

Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In your particular example, you have the full list of products, so I'd use Version 2.

How can I parse a YAML file from a Linux shell script?

It's possible to pass a small script to some interpreters, like Python. An easy way to do so using Ruby and its YAML library is the following:

$ RUBY_SCRIPT="data = YAML::load(STDIN.read); puts data['a']; puts data['b']"
$ echo -e '---\na: 1234\nb: 4321' | ruby -ryaml -e "$RUBY_SCRIPT"
1234
4321

, wheredata is a hash (or array) with the values from yaml.

As a bonus, it'll parse Jekyll's front matter just fine.

ruby -ryaml -e "puts YAML::load(open(ARGV.first).read)['tags']" example.md

Row Offset in SQL Server

I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.

The table has the following:

ID, KeyId, Rank

The same rank will be assigned for more than one KeyId.

SQL is select top 2 * from Table1 where Rank >= @Rank and ID > @Id

For the first time I pass 0 for both. The second time pass 1 & 14. 3rd time pass 2 and 6....

The value of the 10th record Rank & Id is passed to the next

11  21  1
14  22  1
7   11  1
6   19  2
12  31  2
13  18  2

This will have the least stress on the system

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

If you're OK with using a library that writes the SQL for you, then you can use Upsert (currently Ruby and Python only):

Pet.upsert({:name => 'Jerry'}, :breed => 'beagle')
Pet.upsert({:name => 'Jerry'}, :color => 'brown')

That works across MySQL, Postgres, and SQLite3.

It writes a stored procedure or user-defined function (UDF) in MySQL and Postgres. It uses INSERT OR REPLACE in SQLite3.

How to convert integer into date object python?

This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime() which is (IMHO) easier to read and perhaps the preferred way to do this conversion.

import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

What is the difference between docker-compose ports vs expose

Ports This section is used to define the mapping between the host server and Docker container.

ports:
   - 10005:80

It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.

Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.

They can use

http://{host IP}:10005

something like this

EXPOSE This is exclusively used to define the port on which application is running inside the docker container.

You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port

Declare an array in TypeScript

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

This PL*SQL will write to DBMS_OUTPUT a script that will drop each constraint that does not have delete cascade and recreate it with delete cascade.

NOTE: running the output of this script is AT YOUR OWN RISK. Best to read over the resulting script and edit it before executing it.

DECLARE
      CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
        select * from user_cons_columns
            where constraint_name = theCons and owner = theOwner
            order by position;
      firstCol BOOLEAN := TRUE;
    begin
        -- For each constraint
        FOR cons IN (select * from user_constraints
            where delete_rule = 'NO ACTION'
            and constraint_name not like '%MODIFIED_BY_FK'  -- these constraints we do not want delete cascade
            and constraint_name not like '%CREATED_BY_FK'
            order by table_name)
        LOOP
            -- Drop the constraint
            DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
            -- Re-create the constraint
            DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME 
                                        || ' FOREIGN KEY (');
            firstCol := TRUE;
            -- For each referencing column
            FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
            LOOP
                IF(firstCol) THEN
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT(') REFERENCES ');

            firstCol := TRUE;
            -- For each referenced column
            FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
            LOOP
                IF(firstCol) THEN
                    DBMS_OUTPUT.PUT(consCol.OWNER);
                    DBMS_OUTPUT.PUT('.');
                    DBMS_OUTPUT.PUT(consCol.TABLE_NAME);        -- This seems a bit of a kluge.
                    DBMS_OUTPUT.PUT(' (');
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT_LINE(')  ON DELETE CASCADE  ENABLE VALIDATE;');
        END LOOP;
    end;

How to fix java.net.SocketException: Broken pipe?

I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.

That was my reason. might lead you to check one more point when this issue

  public void postRequest()  {


        Security.insertProviderAt(Conscrypt.newProvider(), 1);

        System.out.println("mediafilename-->>" + mediaFileName);
        String[] dirarray = mediaFileName.split("/");
        String file_name = dirarray[6];
        //Thread.sleep(10000);

        RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
        OkHttpClient okHttpClient = new OkHttpClient();
//        ExecutorService executor = newFixedThreadPool(20);
//        Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
        Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
//        Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

//

                call.cancel();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();

                    }
                });
                e.printStackTrace();

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            System.out.println(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });


                System.out.println("Response ; " + response.body().toString());
//                Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
                System.out.println(response);

            }
        });

Chrome DevTools Devices does not detect device when plugged in

None of the mentioned answers worked for me. However, what worked for me is port forwarding. Steps detailed here:

  1. Ensure you have adb installed (steps here for windowd, mac, ubuntu)
  2. Ensure you have chrome running on your mobile device
  3. On your PC, run the following from command line:

    adb forward tcp:9222 localabstract:chrome_devtools_remote

  4. On running the above command, accept the authorization on your mobile phone. Below is the kind of output I see on my laptop:

    $:/> adb forward tcp:9222 localabstract:chrome_devtools_remote

    * daemon not running. starting it now on port 5037 *

    * daemon started successfully *

  5. Now open your chrome and enter 'localhost:9222' and you shall see the active tab to inspect.

Here is the source for this approach

Default values in a C Struct

How about something like:

struct foo bar;
update(init_id(42, init_dont_care(&bar)));

with:

struct foo* init_dont_care(struct foo* bar) {
  bar->id = dont_care;
  bar->route = dont_care;
  bar->backup_route = dont_care;
  bar->current_route = dont_care;
  return bar;
}

and:

struct foo* init_id(int id, struct foo* bar) {
  bar->id = id;
  return bar;
}

and correspondingly:

struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);

In C++, a similar pattern has a name which I don't remember just now.

EDIT: It's called the Named Parameter Idiom.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Go to your build settings and switch the target's settings to ENABLE_BITCODE = YES for now.

Initialization of all elements of an array to one default value in C++?

C++11 has another (imperfect) option:

std::array<int, 100> a;
a.fill(-1);

What are enums and why are they useful?

In my experience I have seen Enum usage sometimes cause systems to be very difficult to change. If you are using an Enum for a set of domain-specific values that change frequently, and it has a lot of other classes and components that depend on it, you might want to consider not using an Enum.

For example, a trading system that uses an Enum for markets/exchanges. There are a lot of markets out there and it's almost certain that there will be a lot of sub-systems that need to access this list of markets. Every time you want a new market to be added to your system, or if you want to remove a market, it's possible that everything under the sun will have to be rebuilt and released.

A better example would be something like a product category type. Let's say your software manages inventory for a department store. There are a lot of product categories, and many reasons why this list of categories could change. Managers may want to stock a new product line, get rid of other product lines, and possibly reorganize the categories from time to time. If you have to rebuild and redeploy all of your systems simply because users want to add a product category, then you've taken something that should be simple and fast (adding a category) and made it very difficult and slow.

Bottom line, Enums are good if the data you are representing is very static over time and has a limited number of dependencies. But if the data changes a lot and has a lot of dependencies, then you need something dynamic that isn't checked at compile time (like a database table).

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

The usage of the Hardware acceleration depends on the System Image you choose on the emulator.

So,

  1. Go to AVD manager, create virtual device, select hardware, click next.

  2. Choose the System Image that does not require HAXM (hardware acceleration) for running. (That is appears at the right bottom of System image window.)

Note: for other systems that require HAXM, there no way to run them without hardware acceleration.

How to open CSV file in R when R says "no such file or directory"?

In my case this very problem was raised by wrong spelling, lower case 'c:' instead of upper case 'C:' in the path. I corrected spelling and problem vanished.

Add alternating row color to SQL Server Reporting services report

Could someone explain the logic behind turning rest of the fields to false in below code (from above post)

One thing I noticed is that neither of the top two methods have any notion of what color the first row should be in a group; the group will just start with the opposite color from the last line of the previous group. I wanted my groups to always start with the same color...the first row of each group should always be white, and the next row colored.

The basic concept was to reset the toggle when each group starts, so I added a bit of code:

Private bOddRow As Boolean
'*************************************************************************
'-- Display green-bar type color banding in detail rows
'-- Call from BackGroundColor property of all detail row textboxes
'-- Set Toggle True for first item, False for others.
'*************************************************************************
'
Function AlternateColor(ByVal OddColor As String, _
                  ByVal EvenColor As String, ByVal Toggle As Boolean) As String
         If Toggle Then bOddRow = Not bOddRow
         If bOddRow Then 
                Return OddColor
         Else
                 Return EvenColor
         End If
 End Function
 '
 Function RestartColor(ByVal OddColor As String) As String
         bOddRow = True
         Return OddColor
 End Function

So I have three different kinds of cell backgrounds now:

  1. First column of data row has =Code.AlternateColor("AliceBlue", "White", True) (This is the same as the previous answer.)
  2. Remaining columns of data row have =Code.AlternateColor("AliceBlue", "White", False) (This, also, is the same as the previous answer.)
  3. First column of grouping row has =Code.RestartColor("AliceBlue") (This is new.)
  4. Remaining columns of grouping row have =Code.AlternateColor("AliceBlue", "White", False) (This was used before, but no mention of it for grouping row.)

This works for me. If you want the grouping row to be non-colored, or a different color, it should be fairly obvious from this how to change it around.

Please feel free to add comments about what could be done to improve this code: I'm brand new to both SSRS and VB, so I strongly suspect that there's plenty of room for improvement, but the basic idea seems sound (and it was useful for me) so I wanted to throw it out here.

Implicit function declarations in C

Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc).

Edit: no, I was wrong about int for the arguments. Instead it passes whatever type the argument is. So it could be an int or a double or a char*. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.

For more details look up K&R C.

MISCONF Redis is configured to save RDB snapshots

I too was facing the same issue. Both the answers (the most upvoted one and the accepted one) just give a temporary fix for the same.

Moreover, the config set stop-writes-on-bgsave-error no is a horrible way to over look this error, since what this option does is stop redis from notifying that writes have been stopped and to move on without writing the data in a snapshot. This is simply ignoring this error. Refer this

As for setting dir in config in redis-cli, once you restart the redis service, this shall get cleared too and the same error shall pop up again. The default value of dir in redis.conf is ./ , and if you start redis as root user, then ./ is / to which write permissions aren't granted, and hence the error.

The best way is to set the dir parameter in redis.conf file and set proper permissions to that directory. Most of the debian distributions shall have it in /etc/redis/redis.conf

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

How do I parse JSON into an int?

The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer

function getInt(arr, prop) {
    var int;
    for (var i=0 ; i<arr.length ; i++) {
        int = parseInt(arr[i][prop])
            arr[i][prop] = int;
    }
    return arr;
  }

the function just go thru the array and return all elements of the object of your selection as an integer

Algorithm to return all combinations of k elements from n

Since programming language is not mentioned I am assuming that lists are OK too. So here's an OCaml version suitable for short lists (non tail-recursive). Given a list l of elements of any type and an integer n it will return a list of all possible lists containing n elements of l if we assume that the order of the elements in the outcome lists is ignored, i.e. list ['a';'b'] is the same as ['b';'a'] and will reported once. So size of resultant list will be ((List.length l) Choose n).

The intuition of the recursion is the following: you take the head of the list and then make two recursive calls:

  • recursive call 1 (RC1): to the tail of the list, but choose n-1 elements
  • recursive call 2 (RC2): to the tail of the list, but choose n elements

to combine the recursive results, list-multiply (please bear the odd name) the head of the list with the results of RC1 and then append (@) the results of RC2. List-multiply is the following operation lmul:

a lmul [ l1 ; l2 ; l3] = [a::l1 ; a::l2 ; a::l3]

lmul is implemented in the code below as

List.map (fun x -> h::x)

Recursion is terminated when the size of the list equals the number of elements you want to choose, in which case you just return the list itself.

So here's a four-liner in OCaml that implements the above algorithm:

    let rec choose l n = match l, (List.length l) with                                 
    | _, lsize  when n==lsize  -> [l]                                
    | h::t, _ -> (List.map (fun x-> h::x) (choose t (n-1))) @ (choose t n)   
    | [], _ -> []    

How to add the JDBC mysql driver to an Eclipse project?

You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

Determine if variable is defined in Python

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.

How to display my application's errors in JSF?

You also have to include the FormID in your call to addMessage().

 FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));

This should do the trick.

Regards.

How to force uninstallation of windows service

You don't have to restart your machine. Start cmd or PowerShell in elevated mode.

sc.exe queryex <SERVICE_NAME>

Then you'll get some info. A PID number will show.

taskkill /pid <SERVICE_PID> /f

Where /f is to force stop.

Now you can install or launch your service.

If you can decode JWT, how are they secure?

Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.

Hide the privateKey in a secure location in your server and never tell anyone the privateKey.

Node.js + Nginx - What now?

Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.

  • serve the request
  • forward the request to another server

    server{
     server_name mydomain.com sub.mydomain.com;
    
     location /{ 
      proxy_pass http://127.0.0.1:8000;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }
    
     location /static/{
       alias /my/static/files/path;
     }
    

    }

Server the request

With this configuration, when the request url is mydomain.com/static/myjs.js it returns the myjs.js file in /my/static/files/path folder. When you configure nginx to serve static files, it handles the request itself.

forward the request to another server

When the request url is mydomain.com/dothis nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.

When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.

If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I had the same problem of "Unable to ping server at localhost:1099" while I was using intellij 2016 version.

However, as soon as I upgraded it to 2017 version(Ultimate 2017.1) which is installed using "ideaIU-2017.1.exe" the problem disappeared.

setHintTextColor() in EditText

Use this to change the hint color. -

editText.setHintTextColor(getResources().getColor(R.color.white));

Solution for your problem -

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3){
        //do something
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        //do something
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        if(arg0.toString().length() <= 0) //check if length is equal to zero
            tv.setHintTextColor(getResources().getColor(R.color.white));
    }
});

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

Found a swap file by the name

.MERGE_MSG.swp is open in your git, you just need to delete this .swp file. In my case I used following command and it worked fine.

rm .MERGE_MSG.swp

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;
}

DEMO

Make DateTimePicker work as TimePicker only in WinForms

Add below event to DateTimePicker

Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
    e.Handled = True
End Sub

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Set a default parameter value for a JavaScript function

The answer is yes. In fact, there are many languages who support default parameters. Python is one of them:

def(a, enter="Hello"):
   print(a+enter)

Even though this is Python 3 code due to the parentheses, default parameters in functions also work in JS.

For example, and in your case:

_x000D_
_x000D_
function read_file(file, deleteAfter=false){_x000D_
  console.log(deleteAfter);_x000D_
}_x000D_
_x000D_
read_file("test.txt");
_x000D_
_x000D_
_x000D_

But sometimes you don't really need default parameters.

You can just define the variable right after the start of the function, like this:

_x000D_
_x000D_
function read_file(file){_x000D_
  var deleteAfter = false;_x000D_
  console.log(deleteAfter);_x000D_
}_x000D_
_x000D_
read_file("test.txt");
_x000D_
_x000D_
_x000D_

In both of my examples, it returns the same thing. But sometimes they actually could be useful, like in very advanced projects.

So, in conclusion, default parameter values can be used in JS. But it is almost the same thing as defining a variable right after the start of the function. However, sometimes they are still very useful. As you have may noticed, default parameter values take 1 less line of code than the standard way which is defining the parameter right after the start of the function.

EDIT: And this is super important! This will not work in IE. See documentation. So with IE you have to use the "define variable at top of function" method. Default parameters won't work in IE.

How to use template module with different set of variables?

With Ansible 2.x you can use vars: with tasks.

Template test.j2:

mkdir -p {{myTemplateVariable}}

Playbook:

- template: src=test.j2 dest=/tmp/File1
  vars:
    myTemplateVariable: myDirName

- template: src=test.j2 dest=/tmp/File2
  vars:
    myTemplateVariable: myOtherDir

This will pass different myTemplateVariable values into test.j2.

Long vs Integer, long vs int, what to use and when?

Long is the Object form of long, and Integer is the object form of int.

The long uses 64 bits. The int uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).

You should use long and int, except where you need to make use of methods inherited from Object, such as hashcode. Java.util.collections methods usually use the boxed (Object-wrapped) versions, because they need to work for any Object, and a primitive type, like int or long, is not an Object.

Another difference is that long and int are pass-by-value, whereas Long and Integer are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long or Integer (it's not, they're immutable without using JNI code), there would be another reason to use one over the other.

A final difference is that a Long or Integer could be null.

GCC -fPIC option

Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.

E.g. jumps would be generated as relative rather than absolute.

Pseudo-assembly:

PIC: This would work whether the code was at address 100 or 1000

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP

Non-PIC: This will only work if the code is at address 100

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP

EDIT: In response to comment.

If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.

How to remove class from all elements jquery

This just removes the highlight class from everything that has the edgetoedge class:

$(".edgetoedge").removeClass("highlight");

I think you want this:

$(".edgetoedge .highlight").removeClass("highlight");

The .edgetoedge .highlight selector will choose everything that is a child of something with the edgetoedge class and has the highlight class.

Disable Laravel's Eloquent timestamps

You can temporarily disable timestamps

$timestamps = $user->timestamps;
$user->timestamps=false;   // avoid view updating the timestamp

$user->last_logged_in_at = now();
$user->save();

$user->timestamps=$timestamps;   // restore timestamps

Add padding to HTML text input field

HTML

<div class="FieldElement"><input /></div>
<div class="searchIcon"><input type="submit" /></div>

For Other Browsers:

.FieldElement input {
width: 413px;
border:1px solid #ccc;
padding: 0 2.5em 0 0.5em;
}

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

For IE:

.FieldElement input {
width: 380px;
border:0;
}

.FieldElement {
 border:1px solid #ccc;
 width: 455px;     
 }

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

Throwing exceptions in a PHP Try Catch block

To rethrow do

 throw $e;

not the message.

Java: print contents of text file to screen

For those new to Java and wondering why Jiri's answer doesn't work, make sure you do what he says and handle the exception or else it won't compile. Here's the bare minimum:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        for (String line; (line = br.readLine()) != null;) {
            System.out.print(line);
        }
        br.close()
    }
}

How to read a file and write into a text file?

    An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)

'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).


An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!

'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo

From Here

Reading and writing environment variables in Python?

Try using the os module.

import os

os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'

# Open child processes via os.system(), popen() or fork() and execv()

someVariable = int(os.environ['DEBUSSY'])

See the Python docs on os.environ. Also, for spawning child processes, see Python's subprocess docs.

How to pass a null variable to a SQL Stored Procedure from C#.net code

I use a method to convert to DBNull if it is null

    // Converts to DBNull, if Null
    public static object ToDBNull(object value)
    {
        if (null != value)
            return value;
        return DBNull.Value;
    }

So when setting the parameter, just call the function

    sqlComm.Parameters.Add(new SqlParameter("@NoteNo", LibraryHelper.ToDBNull(NoteNo)));

This will ensure any nulls, get changed to DBNull.Value, else it will stay the same.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:

  1. merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
  2. merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
  3. merge [-c M[,N...] | -r N:M ...] SOURCE[@REV] [WCPATH]
  4. merge --reintegrate SOURCE[@REV] [WCPATH]

Subversion before 1.5 only allowed the first 2 formats.

Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.

TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.

When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.

Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.

And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)

What are the differences between "git commit" and "git push"?

A very crude analogy: if we compare git commit to saving an edited file, then git push would be copying that file to another location.

Please don't take this analogy out of this context -- committing and pushing are not quite like saving an edited file and copying it. That said, it should hold for comparisons sake.

PHP: cannot declare class because the name is already in use

try to use use include_onceor require_once instead of include or require

Using ExcelDataReader to read Excel data starting from a particular cell

I found this useful to read from a specific column and row:

FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;         
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();

"echo -n" prints "-n"

When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

try this=> numpy.array(r) or numpy.array(yourvariable) followed by the command to compare whatever you wish to.

ImportError: No module named model_selection

Adding some info to the previous answer from @linusg :

sklearn keeps a release history of all its changes. Think of checking it from time to time. Here is the link to the documentation.

As you can see in the documentation for the version 0.18, a new module was created called model_selection. Therefore it didn't exist in previous versions.

Update sklearn and it will work !

How to check in Javascript if one element is contained within another

Take a look at Node#compareDocumentPosition.

function isDescendant(ancestor,descendant){
    return ancestor.compareDocumentPosition(descendant) & 
        Node.DOCUMENT_POSITION_CONTAINS;
}

function isAncestor(descendant,ancestor){
    return descendant.compareDocumentPosition(ancestor) & 
        Node.DOCUMENT_POSITION_CONTAINED_BY;
}

Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.

Not supported in IE<=8.

How to run ~/.bash_profile in mac terminal

No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.

~ is the default path for .bash_profile

How to send POST request?

If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2

urllib2.urlopen(url, body)

See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

Access parent DataContext from DataTemplate

I had problems with the relative source in Silverlight. After searching and reading I did not find a suitable solution without using some additional Binding library. But, here is another approach for gaining access to the parent DataContext by directly referencing an element of which you know the data context. It uses Binding ElementName and works quite well, as long as you respect your own naming and don't have heavy reuse of templates/styles across components:

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content={Binding MyLevel2Property}
              Command={Binding ElementName=level1Lister,
                       Path=DataContext.MyLevel1Command}
              CommandParameter={Binding MyLevel2Property}>
      </Button>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

This also works if you put the button into Style/Template:

<Border.Resources>
  <Style x:Key="buttonStyle" TargetType="Button">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="Button">
          <Button Command={Binding ElementName=level1Lister,
                                   Path=DataContext.MyLevel1Command}
                  CommandParameter={Binding MyLevel2Property}>
               <ContentPresenter/>
          </Button>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</Border.Resources>

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding MyLevel2Property}" 
              Style="{StaticResource buttonStyle}"/>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

At first I thought that the x:Names of parent elements are not accessible from within a templated item, but since I found no better solution, I just tried, and it works fine.

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I got a shortcut for Idle (Python GUI).

  • Click on Window icon at the bottom left or use Window Key (only Python 2), you will see Idle (Python GUI) icon
  • Right click on the icon then more
  • Open File Location
  • A new window will appears, and you will see the shortcut of Idle (Python GUI)
  • Right click, hold down and pull out to desktop to create a shortcut of Python GUI on desktop.

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

Is it possible to use an input value attribute as a CSS selector?

It is possible, if you're using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs -- which includes most modern browsers except IE9.

For instance, to change the text of an input from black to green when the correct answer is entered:

_x000D_
_x000D_
input {_x000D_
  color: black;_x000D_
}_x000D_
input:valid {_x000D_
  color: green;_x000D_
}
_x000D_
<p>Which country has fifty states?</p>_x000D_
_x000D_
<input type="text" pattern="^United States$">
_x000D_
_x000D_
_x000D_

How to sort by column in descending order in Spark SQL?

It's in org.apache.spark.sql.DataFrame for sort method:

df.sort($"col1", $"col2".desc)

Note $ and .desc inside sort for the column to sort the results by.

PHP form - on submit stay on same page

Friend. Use this way, There will be no "Undefined variable message" and it will work fine.

<?php
    if(isset($_POST['SubmitButton'])){
        $price = $_POST["price"];
        $qty = $_POST["qty"];
        $message = $price*$qty;
    }

        ?>

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <form action="#" method="post">
            <input type="number" name="price"> <br>
            <input type="number" name="qty"><br>
            <input type="submit" name="SubmitButton">
        </form>
        <?php echo "The Answer is" .$message; ?>

    </body>
    </html>

How to pass command line argument to gnuplot?

The answer of Jari Laamanen is the best solution. I want just explain how to use more than 1 input parameter with shell variables:

output=test1.png
data=foo.data
gnuplot -e "datafile='${data}'; outputname='${output}'" foo.plg

and foo.plg:

set terminal png
set outputname 
f(x) = sin(x)
plot datafile

As you can see,more parameters are passed with semi colons (like in bash scripts), but string variables NEED to be encapsuled with ' ' (gnuplot syntax, NOT Bash syntax)

MySQL: View with Subquery in the FROM Clause Limitation

Couldn't your query just be written as:

SELECT u1.name as UserName from Message m1, User u1 
  WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3

That should also help with the known speed issues with subqueries in MySQL

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

jQuery remove all list items from an unordered list

$("ul").empty() works fine. Is there some other error?

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('ul').empty()_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
  <li>test</li>_x000D_
  <li>test</li>_x000D_
</ul>_x000D_
_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/infernalbadger/D5ss8/

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

This answer is updated for Xcode 11.

App Store Connect currently asks for images in the following categories:

enter image description here

iPhone 6.5" Display

This is 1242 x 2688 pixels. You can create this size image using the iPhone 11 Pro Max simulator.

iPhone 5.5" Display

This is 1242 x 2208 pixels. You can create this size image using the iPhone 8 Plus simulator.

iPad Pro (3rd gen) 12.9" Display

That is 2048 x 2732 pixels. You can create this size image using the iPad Pro (12.9-inch) (3rd generation) simulator.

iPad Pro (2nd gen) 12.9" Display

That is 2048 x 2732 pixels. This is the exact same size as the iPad Pro (12.9-inch) (3rd generation), so most people can use the same screenshots here. But see this.

Notes

  • Use File > New Screen Shot (Command+S) in the simulator to save a screenshot to the desktop. On a real device press Sleep/Wake+Home on the iPhone/iPad (images available in Photo app)
  • The pixel dimensions above are the full screen portrait orientation sizes. You shouldn't include the status bar, so you can either paste background color over the status bar text and icons or crop them out and scale the image back up.
  • See this link for more details.

Convert string to Time

This gives you the needed results:

string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM"  string

You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

What is the difference between dict.items() and dict.iteritems() in Python2?

If you have

dict = {key1:value1, key2:value2, key3:value3,...}

In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

  • Lists as mutable snapshots: d.items() -> list(d.items())
  • Iterator objects: d.iteritems() -> iter(d.items())

The tuples are the same. You compared tuples in each so you get same.

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.

How to match hyphens with Regular Expression?

The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.

Thus:

  • [-] matches a hyphen.
  • [abc-] matches a, b, c or a hyphen.
  • [-abc] matches a, b, c or a hyphen.
  • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

How to clear out session on log out

I use following to clear session and clear aspnet_sessionID:

HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

How to get the PID of a process by giving the process name in Mac OS X ?

You can try this

pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)

How do I run Visual Studio as an administrator by default?

For Windows 8

  1. right click on the shortcut
  2. click on properties
  3. click on the "Shortcut" tab
  4. click on Advanced

You will find Run As administrator (Checkbox)

PHP 7 RC3: How to install missing MySQL PDO

I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.

Hope this helps!

Set height 100% on absolute div

Instead of using the body, using html worked for me:

html {
   min-height:100%;
   position: relative;
}

div {
   position: absolute;

   top: 0px;
   bottom: 0px;
   right: 0px;
   left: 0px;
}

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

MySQL - select data from database between two dates

Maybe use in between better. It worked for me to get range then filter it

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

C++ IDE for Macs

Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.

Clion from JetBrains, also is available now, and uses Cmake as project model.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

How to set proper codeigniter base url?

this is for server nd live site i apply in hostinger.com and its working fine

1st : $config['base_url'] = 'http://yoursitename.com'; (in confing.php)

2) : src="<?=base_url()?>assest/js/wow.min.js" (in view file )

3) : href="<?php echo base_url()?>index.php/Mycontroller/Method" (for url link or method calling )