Programs & Examples On #Pls 00103

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

What is a smart pointer and when should I use one?

Let T be a class in this tutorial Pointers in C++ can be divided into 3 types :

1) Raw pointers :

T a;  
T * _ptr = &a; 

They hold a memory address to a location in memory. Use with caution , as programs become complex hard to keep track.

Pointers with const data or address { Read backwards }

T a ; 
const T * ptr1 = &a ; 
T const * ptr1 = &a ;

Pointer to a data type T which is a const. Meaning you cannot change the data type using the pointer. ie *ptr1 = 19 ; will not work. But you can move the pointer. ie ptr1++ , ptr1-- ; etc will work. Read backwards : pointer to type T which is const

  T * const ptr2 ;

A const pointer to a data type T . Meaning you cannot move the pointer but you can change the value pointed to by the pointer. ie *ptr2 = 19 will work but ptr2++ ; ptr2-- etc will not work. Read backwards : const pointer to a type T

const T * const ptr3 ; 

A const pointer to a const data type T . Meaning you cannot either move the pointer nor can you change the data type pointer to be the pointer. ie . ptr3-- ; ptr3++ ; *ptr3 = 19; will not work

3) Smart Pointers : { #include <memory> }

Shared Pointer:

  T a ; 
     //shared_ptr<T> shptr(new T) ; not recommended but works 
     shared_ptr<T> shptr = make_shared<T>(); // faster + exception safe

     std::cout << shptr.use_count() ; // 1 //  gives the number of " 
things " pointing to it. 
     T * temp = shptr.get(); // gives a pointer to object

     // shared_pointer used like a regular pointer to call member functions
      shptr->memFn();
     (*shptr).memFn(); 

    //
     shptr.reset() ; // frees the object pointed to be the ptr 
     shptr = nullptr ; // frees the object 
     shptr = make_shared<T>() ; // frees the original object and points to new object

Implemented using reference counting to keep track of how many " things " point to the object pointed to by the pointer. When this count goes to 0 , the object is automatically deleted , ie objected is deleted when all the share_ptr pointing to the object goes out of scope. This gets rid of the headache of having to delete objects which you have allocated using new.

Weak Pointer : Helps deal with cyclic reference which arises when using Shared Pointer If you have two objects pointed to by two shared pointers and there is an internal shared pointer pointing to each others shared pointer then there will be a cyclic reference and the object will not be deleted when shared pointers go out of scope. To solve this , change the internal member from a shared_ptr to weak_ptr. Note : To access the element pointed to by a weak pointer use lock() , this returns a weak_ptr.

T a ; 
shared_ptr<T> shr = make_shared<T>() ; 
weak_ptr<T> wk = shr ; // initialize a weak_ptr from a shared_ptr 
wk.lock()->memFn() ; // use lock to get a shared_ptr 
//   ^^^ Can lead to exception if the shared ptr has gone out of scope
if(!wk.expired()) wk.lock()->memFn() ;
// Check if shared ptr has gone out of scope before access

See : When is std::weak_ptr useful?

Unique Pointer : Light weight smart pointer with exclusive ownership. Use when pointer points to unique objects without sharing the objects between the pointers.

unique_ptr<T> uptr(new T);
uptr->memFn(); 

//T * ptr = uptr.release(); // uptr becomes null and object is pointed to by ptr
uptr.reset() ; // deletes the object pointed to by uptr 

To change the object pointed to by the unique ptr , use move semantics

unique_ptr<T> uptr1(new T);
unique_ptr<T> uptr2(new T);
uptr2 = std::move(uptr1); 
// object pointed by uptr2 is deleted and 
// object pointed by uptr1 is pointed to by uptr2
// uptr1 becomes null 

References : They can essentially be though of as const pointers, ie a pointer which is const and cannot be moved with better syntax.

See : What are the differences between a pointer variable and a reference variable in C++?

r-value reference : reference to a temporary object   
l-value reference : reference to an object whose address can be obtained
const reference : reference to a data type which is const and cannot be modified 

Reference : https://www.youtube.com/channel/UCEOGtxYTB6vo6MQ-WQ9W_nQ Thanks to Andre for pointing out this question.

Passing headers with axios POST request

This might be helpful,

_x000D_
_x000D_
const data = {_x000D_
  email: "[email protected]",_x000D_
  username: "me"_x000D_
};_x000D_
_x000D_
const options = {_x000D_
  headers: {_x000D_
      'Content-Type': 'application/json',_x000D_
  }_x000D_
};_x000D_
_x000D_
axios.post('http://path', data, options)_x000D_
 .then((res) => {_x000D_
   console.log("RESPONSE ==== : ", res);_x000D_
 })_x000D_
 .catch((err) => {_x000D_
   console.log("ERROR: ====", err);_x000D_
 })
_x000D_
_x000D_
_x000D_ Note: All status codes above 400 will be caught in the Axios catch block. Also, headers are optional for the post method in Axios

Blockquote

Blockquote

How to alter a column and change the default value?

Try this

ALTER TABLE `table_name` CHANGE `column_name` `column_name` data_type  NULL DEFAULT '';

like this

ALTER TABLE `drivers_meta` CHANGE `driving_license` `driving_license` VARCHAR(30) NULL DEFAULT '';

How to set or change the default Java (JDK) version on OS X?

  1. Add the following line of code to your .zshrc (or bash_profile):

alias j='f(){ export JAVA_HOME=/usr/libexec/java_home -v $1 };f'

  1. Save to session:

$ source .zshrc

  1. Run command (e.g. j 13, j14, j1.8...)

$ j 1.8

Explanation This is parameterised so you do not need to update the script like other solutions posted. If you do not have the JVM installed you are told. Sample cases below:

/Users/user/IDE/project $ j 1.8
/Users/user/IDE/project $ java -version
openjdk version "1.8.0_265"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_265-b01)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.265-b01, mixed mode)
/Users/user/IDE/project $ j 13
/Users/user/IDE/project $ java -version
openjdk version "13.0.2" 2020-01-14
OpenJDK Runtime Environment (build 13.0.2+8)
OpenJDK 64-Bit Server VM (build 13.0.2+8, mixed mode, sharing)
/Users/user/IDE/project $ j 1.7
Unable to find any JVMs matching version "1.7".

How to use mouseover and mouseout in Angular 6

To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave


**app.component.html**

    <div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
      <span *ngIf="!changeText">Hide</span>
      <span *ngIf="changeText">Show</span>
    </div>

**app.component.ts**

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

Using both Python 2.x and Python 3.x in IPython Notebook

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p

Where is debug.keystore in Android Studio

I got this problem. The debug.keystore file was missing. So the only step that created a correct file for me was creating a new Android project in Android Studio.

It created me a new debug.keystore under path C:\Users\username\.android\.

This solution probably works only when you have not created any projects yet.

Heap vs Binary Search Tree (BST)

Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels, whereas BST guarantees order (from "left" to "right"). If you want sorted elements, go with BST.

CSS: auto height on containing div, 100% height on background div inside containing div

Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.

Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)

#container {
  height:500px;
  min-height:500px;
}

List<T> OrderBy Alphabetical Order

you can use linq :) using :

System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();

Is there a "do ... until" in Python?

I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:

finished = False
while not finished:
    ... do something...
    finished = evaluate_end_condition()

Can you find all classes in a package using reflection?

In general class loaders do not allow for scanning through all the classes on the classpath. But usually the only used class loader is UrlClassLoader from which we can retrieve the list of directories and jar files (see getURLs) and open them one by one to list available classes. This approach, called class path scanning, is implemented in Scannotation and Reflections.

Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:

// package-info.java
@IndexSubclasses
package my.package;

// your code
Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");

Notice that no additional setup is needed as the scanning is fully automated thanks to Java compiler automatically discovering any processors found on the classpath.

What's the difference between JavaScript and JScript?

JScript is the Microsoft implementation of Javascript

How to know/change current directory in Python shell?

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

Can an int be null in Java?

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I know there are plenty of answers here, but I think git reset --soft HEAD~1 deserves some attention, because it let you keep changes in the last local (not pushed) commit while solving the diverged state. I think this is a more versatile solution than pull with rebase, because the local commit can be reviewed and even moved to another branch.

The key is using --soft, instead of the harsh --hard. If there is more than 1 commit, a variation of HEAD~x should work. So here are all the steps that solved my situation (I had 1 local commit and 8 commits in the remote):

1) git reset --soft HEAD~1 to undo local commit. For the next steps, I've used the interface in SourceTree, but I think the following commands should also work:

2) git stash to stash changes from 1). Now all the changes are safe and there's no divergence anymore.

3) git pull to get the remote changes.

4) git stash pop or git stash apply to apply the last stashed changes, followed by a new commit, if wanted. This step is optional, along with 2), when want to trash the changes in local commit. Also, when want to commit to another branch, this step should be done after switching to the desired one.

Setting ANDROID_HOME enviromental variable on Mac OS X

1) Open base profile :

open  ~/.bash_profile

2) Add below line in base profile :

export PATH=${PATH}:/Users/<username>/Library/Android/sdk/build-tools/27.0.3

Save and close base profile.

For me 27.0.3 working great.

PHP substring extraction. Get the string before the first '/' or the whole string

What about this :

substr($mystring.'/', 0, strpos($mystring, '/'))

Simply add a '/' to the end of mystring so you can be sure there is at least one ;)

c# Image resizing to different size while preserving aspect ratio

Just generalizing it down to aspect ratios and sizes, image stuff can be done outside of this function

public static d.RectangleF ScaleRect(d.RectangleF dest, d.RectangleF src, 
  bool keepWidth, bool keepHeight)  
{
    d.RectangleF destRect = new d.RectangleF();

    float sourceAspect = src.Width / src.Height;
    float destAspect = dest.Width / dest.Height;

    if (sourceAspect > destAspect)
    {
        // wider than high keep the width and scale the height
        destRect.Width = dest.Width;
        destRect.Height = dest.Width / sourceAspect;

        if (keepHeight)
        {
            float resizePerc = dest.Height / destRect.Height;
            destRect.Width = dest.Width * resizePerc;
            destRect.Height = dest.Height;
        }
    }
    else
    {
        // higher than wide – keep the height and scale the width
        destRect.Height = dest.Height;
        destRect.Width = dest.Height * sourceAspect;

        if (keepWidth)
        {
            float resizePerc = dest.Width / destRect.Width;
            destRect.Width = dest.Width;
            destRect.Height = dest.Height * resizePerc;
        }

    }

    return destRect;
}

Command line input in Python

Just Taking Input

the_input = raw_input("Enter input: ")

And that's it.

Moreover, if you want to make a list of inputs, you can do something like:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))

In that case, you'll be asked for data 10 times to store 9 items in a list.

Output:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']

You can search that list the fundamental way with something like (after making that list):

if '2' in a:
    print "Found"

else: print "Not found."

You can replace '2' with "raw_input()" like this:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"

Taking Raw Data From Input File via Commandline Interface

If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line

In command line interface:

example.py < input.txt

Hope that helps.

passing argument to DialogFragment

as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle.

the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments().

basically, what you do is set up a bundle with all your Parcelable items and send them on.
in turn, your Fragment will get those items in it's onCreate and do it's magic to them.

the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.

ReferenceError: $ is not defined

jQuery is a JavaScript library, The purpose of jQuery is to make code much easier to use JavaScript.

The jQuery syntax is tailor-made for selecting, A $ sign to define/access jQuery.

Its in declaration sequence must be on top then any other script included which uses jQuery

Correct position to jQuery declaration :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
_x000D_
_x000D_
_x000D_

Above example will work perfectly because jQuery library is initialized before any other library which is using jQuery functions, including $

But if you apply it somewhere else, jQuery functions will not initialize in browser DOM and it will not able to identify any code related to jQuery, and its code starts with $ sign, so you will receive $ is not a function error.

Incorrect position for jQuery declaration:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    console.log('hi from jQuery!');_x000D_
});
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Above code will not work because, jQuery is not declared on the top of any library which uses jQuery ready function.

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Responsive Google Map?

in the iframe tag, you can easily add width='100%' instead of the preset value giving to you by the map

like this:

 <iframe src="https://www.google.com/maps/embed?anyLocation" width="100%" height="400" frameborder="0" style="border:0;" allowfullscreen=""></iframe>

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

how to use javascript Object.defineProperty

Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

What are the differences between Mustache.js and Handlebars.js?

One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.

This is barely mentioned in the GitHub README, where there's one line for it:

Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.

However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.

This has an effect on the way you can use # variables as conditionals.

For example in Mustache you can do this:

{{#variable}}<span class="text">{{variable}}</span>{{/variable}}

It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:

  • use {{this}} instead
  • use a parent path, i.e., {{../variable}} to get back out to relevant scope
  • define a child variable value within the parent variable object

More details on this, if you want them, here.

How to return a specific element of an array?

(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:

array3[i]=e1

Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

error, string or binary data would be truncated when trying to insert

Kevin Pope's comment under the accepted answer was what I needed.

The problem, in my case, was that I had triggers defined on my table that would insert update/insert transactions into an audit table, but the audit table had a data type mismatch where a column with VARCHAR(MAX) in the original table was stored as VARCHAR(1) in the audit table, so my triggers were failing when I would insert anything greater than VARCHAR(1) in the original table column and I would get this error message.

Mvn install or Mvn package

Also you should note that if your project is consist of several modules which are dependent on each other, you should use "install" instead of "package", otherwise your build will fail, cause when you use install command, module A will be packaged and deployed to local repository and then if module B needs module A as a dependency, it can access it from local repository.

How to turn NaN from parseInt into 0 for an empty string?

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

parseInt('') === 0

How to remove any URL within a string in Python

This worked for me:

import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"

URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string

Result:

text1
text2

text3
text4

text5
text6

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Is there a numpy builtin to reject outliers from a list

An alternative is to make a robust estimation of the standard deviation (assuming Gaussian statistics). Looking up online calculators, I see that the 90% percentile corresponds to 1.2815σ and the 95% is 1.645σ (http://vassarstats.net/tabs.html?#z)

As a simple example:

import numpy as np

# Create some random numbers
x = np.random.normal(5, 2, 1000)

# Calculate the statistics
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Add a few large points
x[10] += 1000
x[20] += 2000
x[30] += 1500

# Recalculate the statistics
print()
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Measure the percentile intervals and then estimate Standard Deviation of the distribution, both from median to the 90th percentile and from the 10th to 90th percentile
p90 = np.percentile(x, 90)
p10 = np.percentile(x, 10)
p50 = np.median(x)
# p50 to p90 is 1.2815 sigma
rSig = (p90-p50)/1.2815
print("Robust Sigma=", rSig)

rSig = (p90-p10)/(2*1.2815)
print("Robust Sigma=", rSig)

The output I get is:

Mean=  4.99760520022
Median=  4.95395274981
Max/Min= 11.1226494654   -2.15388472011
Sigma= 1.976629928
90th Percentile 7.52065379649

Mean=  9.64760520022
Median=  4.95667658782
Max/Min= 2205.43861943   -2.15388472011
Sigma= 88.6263902244
90th Percentile 7.60646688694

Robust Sigma= 2.06772555531
Robust Sigma= 1.99878292462

Which is close to the expected value of 2.

If we want to remove points above/below 5 standard deviations (with 1000 points we would expect 1 value > 3 standard deviations):

y = x[abs(x - p50) < rSig*5]

# Print the statistics again
print("Mean= ", np.mean(y))
print("Median= ", np.median(y))
print("Max/Min=", y.max(), " ", y.min())
print("StdDev=", np.std(y))

Which gives:

Mean=  4.99755359935
Median=  4.95213030447
Max/Min= 11.1226494654   -2.15388472011
StdDev= 1.97692712883

I have no idea which approach is the more efficent/robust

Using sed to mass rename files

Using perl rename (a must have in the toolbox):

rename -n 's/0000/000/' F0000*

Remove -n switch when the output looks good to rename for real.

warning There are other tools with the same name which may or may not be able to do this, so be careful.

The rename command that is part of the util-linux package, won't.

If you run the following command (GNU)

$ rename

and you see perlexpr, then this seems to be the right tool.

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo apt install rename
$ sudo update-alternatives --set rename /usr/bin/file-rename

For archlinux:

pacman -S perl-rename

For RedHat-family distros:

yum install prename

The 'prename' package is in the EPEL repository.


For Gentoo:

emerge dev-perl/rename

For *BSD:

pkg install gprename

or p5-File-Rename


For Mac users:

brew install rename

If you don't have this command with another distro, search your package manager to install it or do it manually:

cpan -i File::Rename

Old standalone version can be found here


man rename


This tool was originally written by Larry Wall, the Perl's dad.

Change app language programmatically in Android

I am changed for German language for my app start itself.

Here is my correct code. Anyone want use this same for me.. (How to change language in android programmatically)

my code:

Configuration config ; // variable declaration in globally

// this part is given inside onCreate Method starting and before setContentView()

public void onCreate(Bundle icic) 
{
    super.onCreate(icic);
    config = new Configuration(getResources().getConfiguration());
    config.locale = Locale.GERMAN ;
    getResources().updateConfiguration(config,getResources().getDisplayMetrics());

    setContentView(R.layout.newdesign);
}

Can an Android App connect directly to an online mysql database

you can definitely make such application, you need to make http conection to the database, by calling a php script which will in response run specific queries according to your project, and generated the result in the form of xml, or json formate , whihc can be displayed on your android application!. for complete tutorial on how to connect android application to mysql i would recommend to check out this tutorila

Why call git branch --unset-upstream to fixup?

This might solve your problem.

after doing changes you can commit it and then

git remote add origin https://(address of your repo) it can be https or ssh
then
git push -u origin master

hope it works for you.

thanks

Non greedy (reluctant) regex matching in sed?

Here is something you can do with a two step approach and awk:

A=http://www.suepearson.co.uk/product/174/71/3816/  
echo $A|awk '  
{  
  var=gensub(///,"||",3,$0) ;  
  sub(/\|\|.*/,"",var);  
  print var  
}'  

Output: http://www.suepearson.co.uk

Hope that helps!

Difference between INNER JOIN and LEFT SEMI JOIN

Tried in Hive and got the below output

table1

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

4,yepie,newyork,USA

table2

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

5,chapie,Los angels,USA

Inner Join

SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

Left Join

SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

4 yepie newyork USA NULL NULL NULL NULL

Left Semi Join

SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india

2 stu salem india

3 mia bangalore india

note: Only records in left table are displayed whereas for Left Join both the table records displayed

Can we update primary key values of a table?

Primary key attributes are just as updateable as any other attributes of a table. Stability is often a desirable property of a key but definitely not an absolute requirement. If it makes sense from a business perpective to update a key then there's no fundamental reason why you shouldn't.

svn cleanup: sqlite: database disk image is malformed

Do not waste your time on checking integrity or deleting data from work queue table because these are temporary solutions and it will hit you back after a while.

Just do another checkout and replace the existing .svn folder with the new one. Do an update and then it should go smooth.

pandas read_csv and filter columns with usecols

If your csv file contains extra data, columns can be deleted from the DataFrame after import.

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        index_col=["date", "loc"], 
        usecols=["dummy", "date", "loc", "x"],
        parse_dates=["date"],
        header=0,
        names=["dummy", "date", "loc", "x"])
del df['dummy']

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

As I think, It's not best way to using UIGestureRecognizer-based cells.

First, you'll not have any options to use CoreGraphics.

Perfect solution, will UIResponder or one UIGestureRecognizer for whole table view. Not for every UITableViewCell. It will make you app stuck.

Show week number with Javascript?

Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.

Here is a revised and working version:

Date.prototype.getWeek = function() { 

  // Create a copy of this date object  
  var target  = new Date(this.valueOf());  

  // ISO week date weeks start on monday, so correct the day number  
  var dayNr   = (this.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week with january 4th in it  
  var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
    // Calculate week number: Week 1 (january 4th) plus the    
    // number of weeks between target date and january 4th    
    return 1 + Math.ceil(dayDiff / 7);    
  }
  else {  // jan 4th is on the next week (so next week is week 1)
    return Math.ceil(dayDiff / 7); 
  }
}; 

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
  d[k] = np.concatenate(list(d[k] for d in ds))

How to stop a vb script running in windows

Running scripts can be terminated from the Task Manager.

However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.

Self destruct script:

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True 
WshShell.Run "taskkill /f /im wscript.exe", , True  

Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.

type your shortcut key and all scripts end. Cheers

How do I get the old value of a changed cell in Excel VBA?

In response to Matt Roy answer, I found this option a great response, although I couldn't post as such with my current rating. :(

However, while taking the opportunity to post my thoughts on his response, I thought I would take the opportunity to include a small modification. Just compare code to see.

So thanks to Matt Roy for bringing this code to our attention, and Chris.R for posting original code.

Dim OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'>> Prevent user from multiple selection before any changes:

 If Selection.Cells.Count > 1 Then
        MsgBox "Sorry, multiple selections are not allowed.", vbCritical
        ActiveCell.Select
        Exit Sub
    End If
 'Copy old values
    Set OldValues = Nothing
    Dim c As Range
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next

 On Local Error Resume Next  ' To avoid error if the old value of the cell address you're looking for has not been copied

Dim c As Range

    For Each c In Target
        If OldValues(c.Address) <> "" And c.Value <> "" Then 'both Oldvalue and NewValue are Not Empty
                    Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
        ElseIf OldValues(c.Address) = "" And c.Value = "" Then 'both Oldvalue and NewValue are  Empty
                    Debug.Print "New value of " & c.Address & " is Empty " & c.Value & "; old value is Empty" & OldValues(c.Address)

        ElseIf OldValues(c.Address) <> "" And c.Value = "" Then 'Oldvalue is Empty and NewValue is Not Empty
                    Debug.Print "New value of " & c.Address & " is Empty" & c.Value & "; old value was " & OldValues(c.Address)
        ElseIf OldValues(c.Address) = "" And c.Value <> "" Then 'Oldvalue is Not Empty and NewValue is Empty
                    Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value is Empty" & OldValues(c.Address)
        End If
    Next c

    'Copy old values (in case you made any changes in previous lines of code)
    Set OldValues = Nothing
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c

Read from file in eclipse

Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.

Get element of JS object with an index

var myobj = {"A":["Abe"], "B":["Bob"]};

var keysArray = Object.keys(myobj);

var valuesArray = Object.keys(myobj).map(function(k) {

   return String(myobj[k]);

});

var mydata = valuesArray[keysArray.indexOf("A")]; // Abe

What is the best or most commonly used JMX Console / Client

I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.

I have been primarily using it for GC tuning and finding bottlenecks.

NodeJS - What does "socket hang up" actually mean?

In my case, it was because a application/json response was badly formatted (contains a stack trace). The response was never send to the server. That was very tricky to debug because, there were no log. This thread helps me a lot to understand what happens.

How do I convert an enum to a list in C#?

Language[] result = (Language[])Enum.GetValues(typeof(Language))

What is the difference between an expression and a statement in Python?

STATEMENT:

A Statement is a action or a command that does something. Ex: If-Else,Loops..etc

val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")

EXPRESSION:

A Expression is a combination of values, operators and literals which yields something.

val a: Int = 5 + 5 #yields 10

Quicksort with Python

I think both answers here works ok for the list provided (which answer the original question), but would breaks if an array containing non unique values is passed. So for completeness, I would just point out the small error in each and explain how to fix them.

For example trying to sort the following array [12,4,5,6,7,3,1,15,1] (Note that 1 appears twice) with Brionius algorithm .. at some point will end up with the less array empty and the equal array with a pair of values (1,1) that can not be separated in the next iteration and the len() > 1...hence you'll end up with an infinite loop

You can fix it by either returning array if less is empty or better by not calling sort in your equal array, as in zangw answer

def sort(array=[12,4,5,6,7,3,1,15]):
    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            if x == pivot:
                equal.append(x)
            if x > pivot:
                greater.append(x)

        # Don't forget to return something!
        return sort(less)+ equal +sort(greater)  # Just use the + operator to join lists
    # Note that you want equal ^^^^^ not pivot
    else:  # You need to hande the part at the end of the recursion - when you only have one element in your array, just return the array.
        return array

The fancier solution also breaks, but for a different cause, it is missing the return clause in the recursion line, which will cause at some point to return None and try to append it to a list ....

To fix it just add a return to that line

def qsort(arr): 
   if len(arr) <= 1:
      return arr
   else:
      return qsort([x for x in arr[1:] if x<arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x>=arr[0]])

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

Rails: Default sort order for a rails model?

default_scope

This works for Rails 4+:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

For Rails 2.3, 3, you need this instead:

default_scope order('created_at DESC')

For Rails 2.x:

default_scope :order => 'created_at DESC'

Where created_at is the field you want the default sorting to be done on.

Note: ASC is the code to use for Ascending and DESC is for descending (desc, NOT dsc !).

scope

Once you're used to that you can also use scope:

class Book < ActiveRecord::Base
  scope :confirmed, :conditions => { :confirmed => true }
  scope :published, :conditions => { :published => true }
end

For Rails 2 you need named_scope.

:published scope gives you Book.published instead of Book.find(:published => true).

Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed.

With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.

You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:

scope :recent_books, lambda 
  { |since_when| where("created_at >= ?", since_when) }
  # Note the `where` is making use of AREL syntax added in Rails 3.

Finally you can disable default scope with:

Book.with_exclusive_scope { find(:all) } 

or even better:

Book.unscoped.all

which will disable any filter (conditions) or sort (order by).

Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+


So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!

In fact they are Class level methods as they operate on the 1 set of 'all' records.

Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }.

As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope.

In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.

Send inline image in email

sending 2 images vb.net code convert for C# online converter.

Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean
            Dim client As SmtpClient = New SmtpClient ''("FMSERVER.FMINNOVATIONS.COM.AU")
            'Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise")
            'Dim toAddress As MailAddress
            Try
                Dim aMessage As New MailMessage()
                '(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd))
                If _fromAddress IsNot Nothing Then
                    If _fromName IsNot Nothing Then
                        aMessage.From = New MailAddress(_fromAddress, _fromName)
                    Else
                        aMessage.From = New MailAddress(_fromAddress)
                    End If
                End If
                For Each anAdd As String In _To
                    aMessage.To.Add(New MailAddress(anAdd))
                Next
                For Each cc As String In _CC
                    aMessage.CC.Add(New MailAddress(cc))
                Next
                For Each bcc As String In _BCC
                    aMessage.Bcc.Add(New MailAddress(bcc))
                Next
                aMessage.Subject = _Subject
                aMessage.IsBodyHtml = p_AsHTML

                If _EmailLogo Is Nothing Then
                    aMessage.Body = _Body
                Else
                    If p_themEmail.ToString().ToLower.Contains("dexus") Then

                       Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
                        Dim logo As New LinkedResource(_EmailLogo)
                        logo.ContentId = "Dexuslogo1"
                        Dim logo1 As New LinkedResource(_EmailLogo1)
                        logo1.ContentId = "Dexuslogo2"
                        htmlView.LinkedResources.Add(logo)
                        htmlView.LinkedResources.Add(logo1)
                        aMessage.AlternateViews.Add(htmlView)

                    Else

                        Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
                        Dim logo As New LinkedResource(_EmailLogo)
                        logo.ContentId = "companylogo"
                        htmlView.LinkedResources.Add(logo)
                        aMessage.AlternateViews.Add(htmlView)
                    End If
                End If

                For Each anAttach As Attachment In _Attachments
                    aMessage.Attachments.Add(anAttach)
                Next

                If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo))
                client.Host = "smtpi.cbre.com.au"
                client.UseDefaultCredentials = True
                client.Send(aMessage)
            Catch exRecipUnk As SmtpFailedRecipientException
                Return False
            Catch exSmtp As SmtpException
                ''exSmtp.StatusCode
                Return False
            Catch ex As Exception
                Return False
            End Try
            Return True
        End Function
    If p_Gmap_code = "DE" Then
                Dim p_Theme As New Theme("Dexus")
                Dim passwordlink As String = ""
                Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png")
                Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png")

                passwordlink = "<a href='" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "' target='_blank'>here.</a><br/>"
                bodys += "<div align='Center'><table border='0' cellpadding='0' cellspacing='0'><tr style='height:50px;'><td width='623px' ></td><td valign='top' width='180'><p align='right'><a href='http://www.dexus.com/'><img border='0' height='50' src=cid:Dexuslogo1 width='174' alt=''/></a></p></td></tr><tr><td colspan='2' width='803' style='height:25px;'></td></tr> <tr><td width='623px'><p align='left' style='font-family:Arial;font-size:14pt;'><strong> Your Dexus Response Password is about to expire</strong></p></td>"
                bodys += " <td width='180'><p align='right' style='font-family:Arial;font-size:10pt;'>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>"
                bodys += "</td></tr><tr><td colspan='2' width='803' style='height:30px;'>  </td></tr> <tr>  <td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
                bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>"
                bodys += "</td></tr><tr><td colspan='2' width='803' style='height:25px;'></td> </tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
                bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" 'edit
                bodys += " </tr><tr><td colspan='2' width='803' style='height:30px;'></td></tr><tr><td colspan='2' width='803'><table align='left' border='0' cellpadding='0' cellspacing='0'><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><strong>Dexus Response</strong></p></td></tr><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><a href='mailto:[email protected]'>[email protected]</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href='https://response.dexus.com/'>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan='2' width='803' style='height:15px;'></td></tr><tr> <td colspan='2' width='803'><p> </p><p><a href='https://response.dexus.com/' border='0' target='_blank'><img border='0' height='133'"
                bodys += "src=cid:Dexuslogo2 alt='' width='800' /></a></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'><p><a href='http://www.dexus.com/who-we-are/terms-and-conditions' style=' color:#000000;'>Terms and Conditions</a><strong> | </strong><a href='http://www.dexus.com/who-we-are/privacy-policy' style=' color:#000000;'> Privacy Policy</a></p></td></tr><tr><td colspan='2' width='803' style='height:40px;'></td></tr><tr><td colspan='2' width='803'><p></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr></tr><tr><td colspan='2' width='803' style='height:20px;'></td></tr></table></div>"

                email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2)
                email.ToEmail = p_TenantEmail
                email.SendEmail(True, p_Theme.EmailFrom)

Include another JSP file

What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.

What you need is a dynamic include:

<jsp:include page="..." />

Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.

Removing carriage return and new-line from the end of a string in c#

String temp = s.Replace("\r\n","").Trim();

s being the original string. (Note capitals)

Execute PHP scripts within Node.js web server

If php is in FPM mode node-phpfpm could be an option, check the documenation https://www.npmjs.com/package/node-phpfpm

Good way of getting the user's location in Android

To select the right location provider for your app, you can use Criteria objects:

Criteria myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_HIGH);
myCriteria.setPowerRequirement(Criteria.POWER_LOW);
// let Android select the right location provider for you
String myProvider = locationManager.getBestProvider(myCriteria, true); 

// finally require updates at -at least- the desired rate
long minTimeMillis = 600000; // 600,000 milliseconds make 10 minutes
locationManager.requestLocationUpdates(myProvider,minTimeMillis,0,locationListener); 

Read the documentation for requestLocationUpdates for more details on how the arguments are taken into account:

The frequency of notification may be controlled using the minTime and minDistance parameters. If minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds between location updates to conserve power. If minDistance is greater than 0, a location will only be broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as possible, set both parameters to 0.

More thoughts

  • You can monitor the accuracy of the Location objects with Location.getAccuracy(), which returns the estimated accuracy of the position in meters.
  • the Criteria.ACCURACY_HIGH criterion should give you errors below 100m, which is not as good as GPS can be, but matches your needs.
  • You also need to monitor the status of your location provider, and switch to another provider if it gets unavailable or disabled by the user.
  • The passive provider may also be a good match for this kind of application: the idea is to use location updates whenever they are requested by another app and broadcast systemwide.

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

Why does javascript map function return undefined?

Filter works for this specific case where the items are not modified. But in many cases when you use map you want to make some modification to the items passed.

if that is your intent, you can use reduce:

var arr = ['a','b',1];
var results = arr.reduce((results, item) => {
    if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
    return results
}, [])

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Android 6.0 multiple permissions

It's easy, do this way

private static final int REQUEST_READ_PHONE_STATE = 110 , REQUEST_ACCESS_FINE_LOCATION = 111, REQUEST_WRITE_STORAGE = 112;

In your onCreate

 //request permission
    boolean hasPermissionPhoneState = (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermissionPhoneState) {
        ActivityCompat.requestPermissions(LoginActivity.this,
                new String[]{Manifest.permission.READ_PHONE_STATE},
                REQUEST_READ_PHONE_STATE);
    }

    boolean hasPermissionLocation = (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermissionLocation) {
        ActivityCompat.requestPermissions(LoginActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_ACCESS_FINE_LOCATION);
    }

    boolean hasPermissionWrite = (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermissionWrite) {
        ActivityCompat.requestPermissions(LoginActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
    }

Then check result

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_READ_PHONE_STATE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
                //reload my activity with permission granted or use the features what required the permission
                finish();
                startActivity(getIntent());
            } else
            {
                Toast.makeText(LoginActivity.this, "The app was not allowed to get your phone state. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
        case REQUEST_ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
                //reload my activity with permission granted or use the features what required the permission
                finish();
                startActivity(getIntent());
            } else
            {
                Toast.makeText(LoginActivity.this, "The app was not allowed to get your location. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }

        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(LoginActivity.this, "Permission granted.", Toast.LENGTH_SHORT).show();
                //reload my activity with permission granted or use the features what required the permission
                finish();
                startActivity(getIntent());
            } else
            {
                Toast.makeText(LoginActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Rails: call another controller action from a controller

Composition to the rescue!

Given the reason, rather than invoking actions across controllers one should design controllers to seperate shared and custom parts of the code. This will help to avoid both - code duplication and breaking MVC pattern.

Although that can be done in a number of ways, using concerns (composition) is a good practice.

# controllers/a_controller.rb
class AController < ApplicationController
  include Createable

  private def redirect_url
    'one/url'
  end
end

# controllers/b_controller.rb
class BController < ApplicationController
  include Createable

  private def redirect_url
    'another/url'
  end
end

# controllers/concerns/createable.rb
module Createable
  def create
    do_usefull_things
    redirect_to redirect_url
  end
end

Hope that helps.

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

How would I stop a while loop after n amount of time?

import time

abort_after = 5 * 60
start = time.time()

while True:
  delta = time.time() - start
  if delta >= abort_after:
    break

Rendering an array.map() in React

Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray as proposed in the React documentation

React.Children.toArray

Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.

Note:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.

 <div>
    <ul>
      {
        React.Children.toArray(
          this.state.data.map((item, i) => <li>Test</li>)
        )
      }
    </ul>
  </div>

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

Express.js: how to get remote client address

According to Express behind proxies, req.ip has taken into account reverse proxy if you have configured trust proxy properly. Therefore it's better than req.connection.remoteAddress which is obtained from network layer and unaware of proxy.

How to remove element from array in forEach loop?

I understood that you want to remove from the array using a condition and have another array that has items removed from the array. Is right?

How about this?

_x000D_
_x000D_
var review = ['a', 'b', 'c', 'ab', 'bc'];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if(review[i].charAt(0) == 'a') {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else{_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

Hope this help...

By the way, I compared 'for-loop' to 'forEach'.

If remove in case a string contains 'f', a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if( review[i].includes('f')) {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else {_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"] _x000D_
 */_x000D_
_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  if( item.includes('f')) {_x000D_
    filtered.push(object.splice(i,1)[0]);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "filter",  "findIndex",  "flatten",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"]_x000D_
 */
_x000D_
_x000D_
_x000D_

And remove by each iteration, also a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  filtered.push(review.splice(i,1)[0]);_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  filtered.push(object.splice(i,1)[0]);_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

mysql: SOURCE error 2?

solution - 1) Make sure you're in the root folder of your app. eg app/db/schema.sql.

solution - 2) open/reveal the folder on your window and drag&&drop in the command line next to keywork source (space) filesource. eg source User/myMAC/app/db/schema.sql

How to use Checkbox inside Select Option

I started from @vitfo answer but I want to have <option> inside <select> instead of checkbox inputs so i put together all the answers to make this, there is my code, I hope it will help someone.

_x000D_
_x000D_
$(".multiple_select").mousedown(function(e) {_x000D_
    if (e.target.tagName == "OPTION") _x000D_
    {_x000D_
      return; //don't close dropdown if i select option_x000D_
    }_x000D_
    $(this).toggleClass('multiple_select_active'); //close dropdown if click inside <select> box_x000D_
});_x000D_
$(".multiple_select").on('blur', function(e) {_x000D_
    $(this).removeClass('multiple_select_active'); //close dropdown if click outside <select>_x000D_
});_x000D_
 _x000D_
$('.multiple_select option').mousedown(function(e) { //no ctrl to select multiple_x000D_
    e.preventDefault(); _x000D_
    $(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click_x000D_
    $(this).parent().change(); //trigger change event_x000D_
});_x000D_
_x000D_
 _x000D_
 $("#myFilter").on('change', function() {_x000D_
      var selected = $("#myFilter").val().toString(); //here I get all options and convert to string_x000D_
      var document_style = document.documentElement.style;_x000D_
      if(selected !== "")_x000D_
        document_style.setProperty('--text', "'Selected: "+selected+"'");_x000D_
      else_x000D_
        document_style.setProperty('--text', "'Select values'");_x000D_
 });
_x000D_
:root_x000D_
{_x000D_
 --text: "Select values";_x000D_
}_x000D_
.multiple_select_x000D_
{_x000D_
 height: 18px;_x000D_
 width: 90%;_x000D_
 overflow: hidden;_x000D_
 -webkit-appearance: menulist;_x000D_
 position: relative;_x000D_
}_x000D_
.multiple_select::before_x000D_
{_x000D_
 content: var(--text);_x000D_
 display: block;_x000D_
  margin-left: 5px;_x000D_
  margin-bottom: 2px;_x000D_
}_x000D_
.multiple_select_active_x000D_
{_x000D_
 overflow: visible !important;_x000D_
}_x000D_
.multiple_select option_x000D_
{_x000D_
 display: none;_x000D_
    height: 18px;_x000D_
 background-color: white;_x000D_
}_x000D_
.multiple_select_active option_x000D_
{_x000D_
 display: block;_x000D_
}_x000D_
_x000D_
.multiple_select option::before {_x000D_
  content: "\2610";_x000D_
}_x000D_
.multiple_select option:checked::before {_x000D_
  content: "\2611";_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select id="myFilter" class="multiple_select" multiple>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
  <option>D</option>_x000D_
  <option>E</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

In Python, how do I index a list with another list?

You could also use the __getitem__ method combined with map like the following:

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']

File Upload using AngularJS

You may consider IaaS for file upload, such as Uploadcare. There is an Angular package for it: https://github.com/uploadcare/angular-uploadcare

Technically it's implemented as a directive, providing different options for uploading, and manipulations for uploaded images within the widget:

<uploadcare-widget
  ng-model="object.image.info.uuid"
  data-public-key="YOURKEYHERE"
  data-locale="en"
  data-tabs="file url"
  data-images-only="true"
  data-path-value="true"
  data-preview-step="true"
  data-clearable="true"
  data-multiple="false"
  data-crop="400:200"
  on-upload-complete="onUCUploadComplete(info)"
  on-widget-ready="onUCWidgetReady(widget)"
  value="{{ object.image.info.cdnUrl }}"
 />

More configuration options to play with: https://uploadcare.com/widget/configure/

How to create a inset box-shadow only on one side?

The trick is a second .box-inner inside, which is larger in width than the original .box, and the box-shadow is applied to that.

Then, added more padding to the .text to make up for the added width.

This is how the logic looks:

box logic

And here's how it's done in CSS:

Use max width for .inner-box to not cause .box to get wider, and overflow to make sure the remaining is clipped:

.box {
    max-width: 100% !important;
    overflow: hidden;
}

110% is wider than the parent which is 100% in a child's context (should be the same when the parent .box has a fixed width, for example). Negative margins make up for the width and cause the element to be centered (instead of only the right part hiding):

.box-inner {
    width: 110%;
    margin-left:-5%;
    margin-right: -5%;
    -webkit-box-shadow: inset 0px 5px 10px 1px #000000;
    box-shadow: inset 0px 5px 10px 1px #000000;
}

And add some padding on the X axis to make up for the wider .inner-box:

.text {
    padding: 20px 40px;
}

Here's a working Fiddle.

If you inspect the Fiddle, you'll see:

.box .box-inner .text

Initialize empty vector in structure - c++

Like this:

#include <string>
#include <vector>

struct user
{
    std::string username;
    std::vector<unsigned char> userpassword;
};

int main()
{
    user r;   // r.username is "" and r.userpassword is empty
    // ...
}

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

A potentially dangerous Request.Form value was detected from the client

I was getting this error too.

In my case, a user entered an accented character á in a Role Name (regarding the ASP.NET membership provider).

I pass the role name to a method to grant Users to that role and the $.ajax post request was failing miserably...

I did this to solve the problem:

Instead of

data: { roleName: '@Model.RoleName', users: users }

Do this

data: { roleName: '@Html.Raw(@Model.RoleName)', users: users }

@Html.Raw did the trick.

I was getting the Role name as HTML value roleName="Cadastro b&#225;s". This value with HTML entity &#225; was being blocked by ASP.NET MVC. Now I get the roleName parameter value the way it should be: roleName="Cadastro Básico" and ASP.NET MVC engine won't block the request anymore.

Android Get Application's 'Home' Data Directory

To get the path of file in application package;

ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();

How to connect Robomongo to MongoDB

Currently, Robomongo 0.8.x doesn't work with MongoDB 3.0:

For now, don't use Robomongo. For me, the best solution is to use MongoChef.

How to determine if a number is odd in JavaScript

Many people misunderstand the meaning of odd

  • isOdd("str") should be false.
    Only an integer can be odd.
  • isOdd(1.223) and isOdd(-1.223) should be false.
    A float is not an integer.
  • isOdd(0) should be false.
    Zero is an even integer (https://en.wikipedia.org/wiki/Parity_of_zero).
  • isOdd(-1) should be true.
    It's an odd integer.

Solution

function isOdd(n) {

  // Must be a number
  if (isNaN(n)) {
    return false;
  }

  // Number must not be a float
  if ((n % 1) !== 0) {
    return false;
  }

  // Integer must not be equal to zero
  if (n === 0) {
    return false;
  }

  // Integer must be odd
  if ((n % 2) !== 0) {
    return true;
  }

  return false;
}

JS Fiddle (if needed): https://jsfiddle.net/9dzdv593/8/

1-liner

Javascript 1-liner solution. For those who don't care about readability.

const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;

How to reduce the space between <p> tags?

Reduce space between paragraphs. If you are using blogger, you'd go to template, 'customize' then find 'add css' and paste this: p {margin:.7em 0 .7em 0} /*Reduces space between

from full line to approx. 1/2 line */ If you are just tagging your webpage, that's still what you would use, just put it into your css file(s).

I was an sgml template designer in the late 70s/early 80s and all this tagging is just a dtd within sgml (even if they are now trying to say that html5/css3 is 'not', YES IT STILL IS.) :)

You can find all this basic info at w3schools too you know. Really if you are learning how to do layout using tagging or even javascript, etc. you should start with w3schools. Some people say it is 'not always' right, but folks, I've been in IT since 1960 (age 12) and w3schools is best for beginners. Are some things wrong there? Ah, I dunno, I haven't found any mistake, although sometimes if you are a beginner you might need to read two viewpoints to truly grasp the sense of something. But do remember that you are NOT programming when you code a webpage, you are simply doing layout work. (Yell all you want folks, that's the truth of it.)

Pandas percentage of total with groupby

Paul H's answer is right that you will have to make a second groupby object, but you can calculate the percentage in a simpler way -- just groupby the state_office and divide the sales column by its sum. Copying the beginning of Paul H's answer:

# From Paul H
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
                   'office_id': list(range(1, 7)) * 2,
                   'sales': [np.random.randint(100000, 999999)
                             for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
# Change: groupby state_office and divide by sum
state_pcts = state_office.groupby(level=0).apply(lambda x:
                                                 100 * x / float(x.sum()))

Returns:

                     sales
state office_id           
AZ    2          16.981365
      4          19.250033
      6          63.768601
CA    1          19.331879
      3          33.858747
      5          46.809373
CO    1          36.851857
      3          19.874290
      5          43.273852
WA    2          34.707233
      4          35.511259
      6          29.781508

Routing for custom ASP.NET MVC 404 Error page

Try this in web.config to replace IIS error pages. This is the best solution I guess, and it sends out the correct status code too.

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <remove statusCode="500" subStatusCode="-1" />
    <error statusCode="404" path="Error404.html" responseMode="File" />
    <error statusCode="500" path="Error.html" responseMode="File" />
  </httpErrors>
</system.webServer>

More info from Tipila - Use Custom Error Pages ASP.NET MVC

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

You can disable them in your browser.

Firefox

Type about:config in the Firefox address bar and find security.csp.enable and set it to false.

Chrome

You can install the extension called Disable Content-Security-Policy to disable CSP.

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

Java Read Large Text File With 70million line of text

This article is a great way to start.

Also, you need to create test cases in which you read first 10k(or something else, but shouldn't be too small) lines and calculate the reading times accordingly.

Threading might be a good way to go, but it's important that we know what you will be doing with the data.

Another thing to be considered is, how you will store that size of data.

'No JUnit tests found' in Eclipse

Try this

Right Click on the Unit Test Class,

  1. Select "Run As" -> Run Configuration
  2. In the "Test" tab, make sure in the field "Test runner" select drop down "JUnit 4"
  3. Click "Apply"

Now Run the test!

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:

InsertQueryBuilder:

 public static string InsertQueryBuilder(IEnumerable < string > fields) {


  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();


  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  }
  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;
 }

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   }
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');
  }

And use it like:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {
 "UserName",
 "City"
}

You can write:

List < string > columns = new List < string > {
nameof(UserEntity.UserName),
nameof(UserEntity.City),
}

How to capture Curl output to a file?

If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.

curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"

Invalid column count in CSV input on line 1 Error

If your DB table already exists and you do NOT want to include all the table's columns in your CSV file, then when you run PHP Admin Import, you'll need fill in the Column Names field in the Format-Specific Options for CSV - Shown here at the bottom of the following screenshot.

In summary:

  • Choose a CSV file
  • Set the Format to CSV
  • Fill in the Column Names field with the names of the columns in your CSV
  • If your CSV file has the column names listed in row 1, set "Skip this number of queries (for SQL) or lines (for other formats), starting from the first one" to 1

enter image description here

Why does visual studio 2012 not find my tests?

This problem seems to have so many different solutions may as well add my own:

Close Visual Studio

Rename C:\Users\username\AppData\Local\Microsoft\VisualStudio\12.0\ComponentModelCache to ComponentModelCache.old

Run Visual Studio and the component cache will be rebuilt.

List submodules in a Git repository

Here is another way to parse Git submodule names from .gitmodules without the need for sed or fancy IFS settings. :-)

#!/bin/env bash

function stripStartAndEndQuotes {
  temp="${1%\"}"
  temp="${temp#\"}"
  echo "$temp"
}

function getSubmoduleNames {
  line=$1
  len=${#line} # Get line length
  stripStartAndEndQuotes "${line::len-1}" # Remove last character
}

while read line; do
  getSubmoduleNames "$line"
done < <(cat .gitmodules | grep "\[submodule.*\]" | cut -d ' ' -f 2-)

Is java.sql.Timestamp timezone specific?

I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.

In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal) Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.

API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

How to uninstall pip on OSX?

The first thing you should try is:

sudo pip uninstall pip

On many environments that doesn't work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.

Getting a map() to return a list in Python 3.x

You can try getting a list from the map object by just iterating each item in the object and store it in a different variable.

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']

CSS :not(:last-child):after selector

Every things seems correct. You might want to use the following css selector instead of what you used.

ul > li:not(:last-child):after

Determine if string is in list in JavaScript

In addition to indexOf (which other posters have suggested), using prototype's Enumerable.include() can make this more neat and concise:

var list = ['a', 'b', 'c'];
if (list.include(str)) {
  // do stuff
}

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

How to use SQL LIKE condition with multiple values in PostgreSQL?

Using array or set comparisons:

create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');

select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');

select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));

It is also possible to do an AND which would not be easy with a regex if it were to match any order:

select str from t
where str like all ('{"%999%", "DDD%"}');

select str from t
where str like all (values('%999%'), ('DDD%'));

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

Randall, here are the VB expressions I found to work in SSRS to obtain the first and last days of any month, using the current month as a reference:

First day of last month:

=dateadd("m",-1,dateserial(year(Today),month(Today),1)) 

First day of this month:

=dateadd("m",0,dateserial(year(Today),month(Today),1)) 

First day of next month:

=dateadd("m",1,dateserial(year(Today),month(Today),1)) 

Last day of last month:

=dateadd("m",0,dateserial(year(Today),month(Today),0))

Last day of this month:

=dateadd("m",1,dateserial(year(Today),month(Today),0))

Last day of next month:

=dateadd("m",2,dateserial(year(Today),month(Today),0))

The MSDN documentation for the VisualBasic DateSerial(year,month,day) function explains that the function accepts values outside the expected range for the year, month, and day parameters. This allows you to specify useful date-relative values. For instance, a value of 0 for Day means "the last day of the preceding month". It makes sense: that's the day before day 1 of the current month.

How to both read and write a file in C#

var fs = File.Open("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);

...

fs.Close();
//or sw.Close();

The key thing is to open the file with the FileAccess.ReadWrite flag. You can then create whatever Stream/String/Binary Reader/Writers you need using the initial FileStream.

Find and kill a process in one line using bash and regex

Give -f to pkill

pkill -f /usr/local/bin/fritzcap.py

exact path of .py file is

# ps ax | grep fritzcap.py
 3076 pts/1    Sl     0:00 python -u /usr/local/bin/fritzcap.py -c -d -m

Convert XLS to CSV on command line

Why not write your own?

I see from your profile you have at least some C#/.NET experience. I'd create a Windows console application and use a free Excel reader to read in your Excel file(s). I've used Excel Data Reader available from CodePlex without any problem (one nice thing: this reader doesn't require Excel to be installed). You can call your console application from the command line.

If you find yourself stuck post here and I'm sure you'll get help.

Exit from app when click button in android phonegap?

sorry i can't reply in comment. just FYI, these codes

if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
  navigator.device.exitApp();
}
else {
          window.close();
}

i confirm doesn't work. i use phonegap 6.0.5 and cordova 6.2.0

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

Difference between const reference and normal parameter

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.

There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.

E.g.

int a;

void DoWork(const int &n)
{
    a = n * 2;  // If n was a reference to a, n will have been doubled 

    f();  // Might change the value of whatever n refers to 
}

int main()
{
    DoWork(a);
}

Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.

e.g.

void DoWork(const int &n)
{
    const_cast<int&>(n) = 22;
}

This would cause undefined behaviour if the object passed in was actually const.

When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.

When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.

How to get the real path of Java application at runtime?

Since the application path of a JAR and an application running from inside an IDE differs, I wrote the following code to consistently return the correct current directory:

import java.io.File;
import java.net.URISyntaxException;

public class ProgramDirectoryUtilities
{
    private static String getJarName()
    {
        return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
                .getName();
    }

    private static boolean runningFromJAR()
    {
        String jarName = getJarName();
        return jarName.contains(".jar");
    }

    public static String getProgramDirectory()
    {
        if (runningFromJAR())
        {
            return getCurrentJARDirectory();
        } else
        {
            return getCurrentProjectDirectory();
        }
    }

    private static String getCurrentProjectDirectory()
    {
        return new File("").getAbsolutePath();
    }

    private static String getCurrentJARDirectory()
    {
        try
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
        } catch (URISyntaxException exception)
        {
            exception.printStackTrace();
        }

        return null;
    }
}

Simply call getProgramDirectory() and you should be good either way.

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

Using the Safari browser (not Chrome, Firefox or Opera) on Mac OS X 10.9 (Mavericks) visit https://registry.npmjs.org

Screenshot of Safari showing certificate error

Click the Show certificate button and then check the checkbox labelled Always trust. Then click Continue and enter your password if required.

Always trust checkbox

Curl should now work with that URL correctly.

React js onClick can't pass value to method

There were a lot of performance considerations, all in the vacuum.
The issue with this handlers is that you need to curry them in order to incorporate the argument that you can't name in the props.
This means that the component needs a handler for each and every clickable element. Let's agree that for a few buttons this is not an issue, right?
The problem arises when you are handling tabular data with dozens of columns and thousands of rows. There you notice the impact of creating that many handlers.

The fact is, I only need one.
I set the handler at the table level (or UL or OL...), and when the click happens I can tell which was the clicked cell using data available since ever in the event object:

nativeEvent.target.tagName
nativeEvent.target.parentElement.tagName 
nativeEvent.target.parentElement.rowIndex
nativeEvent.target.cellIndex
nativeEvent.target.textContent

I use the tagname fields to check that the click happened in a valid element, for example ignore clicks in THs ot footers.
The rowIndex and cellIndex give the exact location of the clicked cell.
Textcontent is the text of the clicked cell.

This way I don't need to pass the cell's data to the handler, it can self-service it.
If I needed more data, data that is not to be displayed, I can use the dataset attribute, or hidden elements.
With some simple DOM navigation it's all at hand.
This has been used in HTML since ever, since PCs were much easier to bog.

What's default HTML/CSS link color?

The best way to get a browser's default styling on something is to not style the element at all in the first place.

Showing Difference between two datetime values in hours

Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.

Ignore cells on Excel line graph

  1. In the value or values you want to separate, enter the =NA() formula. This will appear that the value is skipped but the preceding and following data points will be joined by the series line.
  2. Enter the data you want to skip in the same location as the original (row or column) but add it as a new series. Add the new series to your chart.
  3. Format the new data point to match the original series format (color, shape, etc.). It will appear as though the data point was just skipped in the original series but will still show on your chart if you want to label it or add a callout.

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

How do I convert a calendar week into a date in Excel?

If you are looking for the opposite to get a date from a weeknumber i found a solution online and changed it slightly:

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
  ' get the date from a certain day in a certain week in a certain year
  fnDateFromWeek = DateSerial(iYear, 1, (iWeek * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
End Function

I took the formular from asap-utilities.com/ and changed

DateSerial(iYear, 1, ((iWeek - 1) * 7) 

to

DateSerial(iYear, 1, (iWeek * 7)

Update

It seems that at least for germany the formular works not as expected for the leap year 2016 so i changed it to this

Function fnDateFromWeek(iYear As Integer, iWeek As Integer, iWeekDday As Integer)
' get the date from a certain day in a certain week in a certain year
  
    If isLeapYear(iYear) Then
        curDate = DateSerial(iYear, 1, ((iWeek) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    Else
        curDate = DateSerial(iYear, 1, ((iWeek - 1) * 7) _
          + iWeekDday - Weekday(DateSerial(iYear, 1, 1)) + 1)
    End If
    fnDateFromWeek = curDate
End Function

Since 2016 hardcoded is not ideal you could check if a year is a leap year with this function

Function isLeapYear(iYear As Integer) As Boolean

    If (Month(DateSerial(iYear, 2, 29)) = 2) Then
        isLeapYear = True
    Else
        isLeapYear = False
    End If
    
End Function

For a non-leap-year DateSerial(iYear,2 ,29) returns 1st of march

This may still be wrong but my limited test gave the expected results:

Sub TestExample()
   Debug.Print Format(fnDateFromWeek(2014, 48, 2), "ddd dd mmm yyyy") ' mo 24 Nov 2014
   Debug.Print Format(fnDateFromWeek(2015, 11, 6), "ddd dd-mmm-yyyy") ' fr 13 Mar 2015
   Debug.Print Format(fnDateFromWeek(2016, 36, 2), "ddd dd-mmm-yyyy") ' Mo 05 Sep 2015
End Sub

Creation timestamp and last update timestamp with Hibernate and MySQL

We had a similar situation. We were using Mysql 5.7.

CREATE TABLE my_table (
        ...
      updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    );

This worked for us.

Python - use list as function parameters

Use an asterisk:

some_func(*params)

How do I hide a menu item in the actionbar?

Android kotlin, hide or set visibility of a menu item in the action bar programmatically.

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    val inflater = menuInflater
    inflater.inflate(R.menu.main_menu, menu)
    val method = menu.findItem(R.id.menu_method)
    method.isVisible = false //if want to show set true
    return super.onCreateOptionsMenu(menu)
}

Redirecting from cshtml page

Change to this:

@{ Response.Redirect("~/HOME/NoResults");}

Modifying a query string without reloading the page

If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:

if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
    window.history.pushState({path:newurl},'',newurl);
}

It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.

For more information:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Process with an ID #### is not running in visual studio professional 2013 update 3

Close VS. Navigate to the folder of the solution and delete the hidden .vs folder. Restart VS. Hit F5 and IIS Express should load as normal, allowing you to debug.

If this not working, then:

  1. right click your solution and go to properties

  2. Click left menu Web tag

  3. Click checkbox "Override application root Url"

and run again your project.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

In my case it was a brief issue with the way a function was written. A memory leak can be caused by assigning a new value to a function's input variable, e.g.:

/**
* Memory leak function that illustrates unintentional bad code
* @param $variable - input function that will be assigned a new value
* @return null
**/
function doSomehting($variable){
    $variable = 'set value';
    // Or
    $variable .= 'set value';
}

How can I find which tables reference a given table in Oracle SQL Developer?

I like to do this with a straight SQL query, rather than messing about with the SQL Developer application.

Here's how I just did it. Best to read through this and understand what's going on, so you can tweak it to fit your needs...

WITH all_primary_keys AS (
  SELECT constraint_name AS pk_name,
         table_name
    FROM all_constraints
   WHERE owner = USER
     AND constraint_type = 'P'
)
  SELECT ac.table_name || ' table has a foreign key called ' || upper(ac.constraint_name)
         || ' which references the primary key ' || upper(ac.r_constraint_name) || ' on table ' || apk.table_name AS foreign_keys
    FROM all_constraints ac
         LEFT JOIN all_primary_keys apk
                ON ac.r_constraint_name = apk.pk_name
   WHERE ac.owner = USER
     AND ac.constraint_type = 'R'
     AND ac.table_name = nvl(upper(:table_name), ac.table_name)
ORDER BY ac.table_name, ac.constraint_name
;

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

Is there a way to specify a default property value in Spring XML?

Spring 3 supports ${my.server.port:defaultValue} syntax.

how do I check in bash whether a file was created more than x time ago?

Using the stat to figure out the last modification date of the file, date to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.

if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
   echo "$somefile is older then 2 hours"
fi

While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)


  1. As Phil correctly noted creation time is not recorded, but use %Z instead of %Y below to get "change time" which may be what you want.

[Update]

For mac users, use stat -f "%m" $somefile instead of the Linux specific syntax above

Update a column in MySQL

UPDATE table1 SET col_a = 'newvalue'

Add a WHERE condition if you want to only update some of the rows.

Output Django queryset as JSON

To return the queryset you retrieved with queryset = Users.objects.all(), you first need to serialize them.

Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.

from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View

class JSONListView(View):
    def get(self, request, *args, **kwargs):
        qs = User.objects.all()
        data = serialize("json", qs)
        return JsonResponse(data)

This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.

How to reset form body in bootstrap modal box?

This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:

var stylesString = $('#DefaultModal .modal-body').html();

Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).

$("#btnStyles").click(function () {
    //pass the data in the modal body adding html elements
    $('#DefaultModal .modal-body').html(stylesString);
 $('#DefaultModal').modal('show');
})

If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.

Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:

<div class="modal-body" id="modalbody">


    <div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
    <div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>

Register DLL file on Windows Server 2008 R2

That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.

What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.

To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

"No such file or directory" but it exists

This error may also occur if trying to run a script and the shebang is misspelled. Make sure it reads #!/bin/sh, #!/bin/bash, or whichever interpreter you're using.

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

New warnings in iOS 9: "all bitcode will be dropped"

This issue has been recently fixed (Nov 2010) by Google, see https://code.google.com/p/analytics-issues/issues/detail?id=671. But be aware that as a good fix it brings more bugs :)

You will also have to follow the initialisation method listed here: https://developers.google.com/analytics/devguides/collection/ios/v2.

The latest instructions are going to give you a headache because it references utilities not included in the pod. Below will fail with the cocoapod

// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

Steps that helped me (VS Community 2017, 15.9.11).

Note that breakpoints will be lost after doing steps below.

  1. Right clicked on the class file
  2. Selected Exclude From Project
  3. Right clicked on the project
  4. Chose Add and Existing File
  5. Navigated to pick the class file in question

How to use "svn export" command to get a single file from the repository?

Use SVN repository URL to export file to Local path.

     svn export [-r rev] [--ignore-externals] URL Export_PATH
     svn export http://<path>/test.txt C:\Temp-Folder

Rails: Why "sudo" command is not recognized?

sudo is a Unix/Linux command. It's not available in Windows.

When to use LinkedList over ArrayList in Java?

ArrayList and LinkedList have their own pros and cons.

ArrayList uses contiguous memory address compared to LinkedList which uses pointers toward the next node. So when you want to look up an element in an ArrayList is faster than doing n iterations with LinkedList.

On the other hand, insertion and deletion in a LinkedList are much easier because you just have to change the pointers whereas an ArrayList implies the use of shift operation for any insertion or deletion.

If you have frequent retrieval operations in your app use an ArrayList. If you have frequent insertion and deletion use a LinkedList.

Load CSV file with Spark

This is in-line with what JP Mercier initially suggested about using Pandas, but with a major modification: If you read data into Pandas in chunks, it should be more malleable. Meaning, that you can parse a much larger file than Pandas can actually handle as a single piece and pass it to Spark in smaller sizes. (This also answers the comment about why one would want to use Spark if they can load everything into Pandas anyways.)

from pyspark import SparkContext
from pyspark.sql import SQLContext
import pandas as pd

sc = SparkContext('local','example')  # if using locally
sql_sc = SQLContext(sc)

Spark_Full = sc.emptyRDD()
chunk_100k = pd.read_csv("Your_Data_File.csv", chunksize=100000)
# if you have headers in your csv file:
headers = list(pd.read_csv("Your_Data_File.csv", nrows=0).columns)

for chunky in chunk_100k:
    Spark_Full +=  sc.parallelize(chunky.values.tolist())

YourSparkDataFrame = Spark_Full.toDF(headers)
# if you do not have headers, leave empty instead:
# YourSparkDataFrame = Spark_Full.toDF()
YourSparkDataFrame.show()

What is a good naming convention for vars, methods, etc in C++?

There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.

So I'll have 2 advices:

  • be consistent within a project
  • don't use reserved identifiers (anything with two underscores or beginning with an underscore followed by an uppercase letter)

The rest is up to you.

CURRENT_DATE/CURDATE() not working as default DATE value

----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----

Support for DEFAULT with expressions (MDEV-10134).

----- 2018-10-22 8.0.13 General Availability -- -- -----

MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.

Checking version of angular-cli that's installed?

Simply just enter any of below in the command line,

ng --version OR ng v OR ng -v

The Output would be like,

Screenshot

Not only the Angular version but also the Node version is also mentioned there. I use Angular 6.

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

C++ String array sorting

My solution is slightly different to any of those above and works as I just ran it.So for interest:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
  char *name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
  vector<string> v(name, name + 14);

  sort(v.begin(),v.end());
  for(vector<string>::const_iterator i = v.begin(); i != v.end(); ++i) cout << *i << ' ';
  return 0;
}

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There are multiple ways how to present a timespan in the database.

time

This datatype is supported since SQL Server 2008 and is the prefered way to store a TimeSpan. There is no mapping needed. It also works well with SQL code.

public TimeSpan ValidityPeriod { get; set; }

However, as stated in the original question, this datatype is limited to 24 hours.

datetimeoffset

The datetimeoffset datatype maps directly to System.DateTimeOffset. It's used to express the offset between a datetime/datetime2 to UTC, but you can also use it for TimeSpan.

However, since the datatype suggests a very specific semantic, so you should also consider other options.

datetime / datetime2

One approach might be to use the datetime or datetime2 types. This is best in scenarios where you need to process the values in the database directly, ie. for views, stored procedures, or reports. The drawback is that you need to substract the value DateTime(1900,01,01,00,00,00) from the date to get back the timespan in your business logic.

public DateTime ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return ValidityPeriod - DateTime(1900,01,01,00,00,00); }
    set { ValidityPeriod = DateTime(1900,01,01,00,00,00) + value; }
}

bigint

Another approach might be to convert the TimeSpan into ticks and use the bigint datatype. However, this approach has the drawback that it's cumbersome to use in SQL queries.

public long ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.FromTicks(ValidityPeriod); }
    set { ValidityPeriod = value.Ticks; }
}

varchar(N)

This is best for cases where the value should be readable by humans. You might also use this format in SQL queries by utilizing the CONVERT(datetime, ValidityPeriod) function. Dependent on the required precision, you will need between 8 and 25 characters.

public string ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.Parse(ValidityPeriod); }
    set { ValidityPeriod = value.ToString("HH:mm:ss"); }
}

Bonus: Period and Duration

Using a string, you can also store NodaTime datatypes, especially Duration and Period. The first is basically the same as a TimeSpan, while the later respects that some days and months are longer or shorter than others (ie. January has 31 days and February has 28 or 29; some days are longer or shorter because of daylight saving time). In such cases, using a TimeSpan is the wrong choice.

You can use this code to convert Periods:

using NodaTime;
using NodaTime.Serialization.JsonNet;

internal static class PeriodExtensions
{
    public static Period ToPeriod(this string input)
    {
        var js = JsonSerializer.Create(new JsonSerializerSettings());
        js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        var quoted = string.Concat(@"""", input, @"""");
        return js.Deserialize<Period>(new JsonTextReader(new StringReader(quoted)));
    }
}

And then use it like

public string ValidityPeriod { get; set; }

[NotMapped]
public Period ValidityPeriodPeriod
{
    get => ValidityPeriod.ToPeriod();
    set => ValidityPeriod = value.ToString();
}

I really like NodaTime and it often saves me from tricky bugs and lots of headache. The drawback here is that you really can't use it in SQL queries and need to do calculations in-memory.

CLR User-Defined Type

You also have the option to use a custom datatype and support a custom TimeSpan class directly. See CLR User-Defined Types for details.

The drawback here is that the datatype might not behave well with SQL Reports. Also, some versions of SQL Server (Azure, Linux, Data Warehouse) are not supported.

Value Conversions

Starting with EntityFramework Core 2.1, you have the option to use Value Conversions.

However, when using this, EF will not be able to convert many queries into SQL, causing queries to run in-memory; potentially transfering lots and lots of data to your application.

So at least for now, it might be better not to use it, and just map the query result with Automapper.

How can I sanitize user input with PHP?

Never trust user data.

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

The trim() function removes whitespace and other predefined characters from both sides of a string.

The stripslashes() function removes backslashes

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

How can I find the method that called the current method?

Take a look at Logging method name in .NET. Beware of using it in production code. StackFrame may not be reliable...

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

Checkout multiple git repos into same Jenkins workspace

Since Multiple SCMs Plugin is deprecated.

With Jenkins Pipeline its possible to checkout multiple git repos and after building it using gradle

node {   
def gradleHome

stage('Prepare/Checkout') { // for display purposes
    git branch: 'develop', url: 'https://github.com/WtfJoke/Any.git'

    dir('a-child-repo') {
       git branch: 'develop', url: 'https://github.com/WtfJoke/AnyChild.git'
    }

    env.JAVA_HOME="${tool 'JDK8'}"
    env.PATH="${env.JAVA_HOME}/bin:${env.PATH}" // set java home in jdk environment
    gradleHome = tool '3.4.1' 
}

stage('Build') {
  // Run the gradle build
  if (isUnix()) {
     sh "'${gradleHome}/bin/gradle' clean build"
  } else {
     bat(/"${gradleHome}\bin\gradle" clean build/)
  }
}
}

You might want to consider using git submodules instead of a custom pipeline like this.

How to create a custom navigation drawer in android

I need to add a header to categorize the list item in Drawer

Customize the listView or use expandableListView

I need a radio button to select some of my options

You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawer then you can do any complex layouts within that as normal.

Maven dependency update on commandline

mvn -Dschemaname=public liquibase:update

How to disable Compatibility View in IE

If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1") in a code block in _Layout to work quite well:

@Code
    Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else

How to add CORS request in header in Angular 5

If you are like me and you are using a local SMS Gateway server and you make a GET request to an IP like 192.168.0.xx you will get for sure CORS error.

Unfortunately I could not find an Angular solution, but with the help of a previous replay I got my solution and I am posting an updated version for Angular 7 8 9

import {from} from 'rxjs';

getData(): Observable<any> {
    return from(
      fetch(
        'http://xxxxx', // the url you are trying to access
        {
          headers: {
            'Content-Type': 'application/json',
          },
          method: 'GET', // GET, POST, PUT, DELETE
          mode: 'no-cors' // the most important option
        }
      ));
  }

Just .subscribe like the usual.

How can I remove a substring from a given String?

replace('regex', 'replacement');
replaceAll('regex', 'replacement');

In your example,

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

How to convert HTML file to word?

Try using pandoc

pandoc -f html -t docx -o output.docx input.html

If the input or output format is not specified explicitly, pandoc will attempt to guess it from the extensions of the input and output filenames.
— pandoc manual

So you can even use

pandoc -o output.docx input.html

Send file using POST from a Python script

Looks like python requests does not handle extremely large multi-part files.

The documentation recommends you look into requests-toolbelt.

Here's the pertinent page from their documentation.

PHP - SSL certificate error: unable to get local issuer certificate

I tried this it works

open

vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php

and change this

 $conf[CURLOPT_SSL_VERIFYHOST] = 2;
 `enter code here`$conf[CURLOPT_SSL_VERIFYPEER] = true;

to this

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = FALSE;

What is the best way to implement "remember me" for a website?

Improved Persistent Login Cookie Best Practice

You could use this strategy described here as best practice (2006) or an updated strategy described here (2015):

  1. When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie.
  2. The login cookie contains a series identifier and a token. The series and token are unguessable random numbers from a suitably large space. Both are stored together in a database table, the token is hashed (sha256 is fine).
  3. When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database.
    1. If the series identifier is present and the hash of the token matches the hash for that series identifier, the user is considered authenticated. A new token is generated, a new hash for the token is stored over the old record, and a new login cookie is issued to the user (it's okay to re-use the series identifier).
    2. If the series is present but the token does not match, a theft is assumed. The user receives a strongly worded warning and all of the user's remembered sessions are deleted.
    3. If the username and series are not present, the login cookie is ignored.

This approach provides defense-in-depth. If someone manages to leak the database table, it does not give an attacker an open door for impersonating users.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I ran into this issue when the number of <th> tags in the '' did not match the number of in the <tfoot> section

<thead>
    <tr>
        <th></th>
        <th>Subject Areas</th>
        <th></th>
        <th>Option(s)</th>
    <tr>
</thead>

<tbody></tbody>

<tfoot>
    <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</tfoot>

javax vs java package

I think it's a historical thing - if a package is introduced as an addition to an existing JRE, it comes in as javax. If it's first introduced as part of a JRE (like NIO was, I believe) then it comes in as java. Not sure why the new date and time API will end up as javax following this logic though... unless it will also be available separately as a library to work with earlier versions (which would be useful). Note from many years later: it actually ended up being in java after all.

I believe there are restrictions on the java package - I think classloaders are set up to only allow classes within java.* to be loaded from rt.jar or something similar. (There's certainly a check in ClassLoader.preDefineClass.)

EDIT: While an official explanation (the search orbfish suggested didn't yield one in the first page or so) is no doubt about "core" vs "extension", I still suspect that in many cases the decision for any particular package has an historical reason behind it too. Is java.beans really that "core" to Java, for example?

C++ Singleton design pattern

I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:

#include<iostream>
#include<string>

class DoNotCopy
{
protected:
    DoNotCopy(void) = default;
    DoNotCopy(const DoNotCopy&) = delete;
    DoNotCopy& operator=(const DoNotCopy&) = delete;
};

class DoNotMove
{
protected:
    DoNotMove(void) = default;
    DoNotMove(DoNotMove&&) = delete;
    DoNotMove& operator=(DoNotMove&&) = delete;
};

class DoNotCopyMove : public DoNotCopy,
    public DoNotMove
{
protected:
    DoNotCopyMove(void) = default;
};

template<class T>
class Singleton : public DoNotCopyMove
{
public:
    static T& Instance(void)
    {
        static T instance;
        return instance;
    }

protected:
    Singleton(void) = default;
};

class Logger final: public Singleton<Logger>
{
public:
    void log(const std::string& str) { std::cout << str << std::endl; }
};



int main()
{
    Logger::Instance().log("xx");
}

The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).

Get div height with plain JavaScript

var clientHeight = document.getElementById('myDiv').clientHeight;

or

var offsetHeight = document.getElementById('myDiv').offsetHeight;

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.

Passing string parameter in JavaScript function

You can pass string parameters to JavaScript functions like below code:

I passed three parameters where the third one is a string parameter.

var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");'  value='Room is Ready' />";

// Your JavaScript function

function RoomIsReadyFunc(ID, RefId, YourString)
{
    alert(ID);
    alert(RefId);
    alert(YourString);
}

Setting environment variables in Linux using Bash

The reason people often suggest writing

VAR=value
export VAR

instead of the shorter

export VAR=value

is that the longer form works in more different shells than the short form. If you know you're dealing with bash, either works fine, of course.

How do I clone a generic List in Java?

Why would you want to clone? Creating a new list usually makes more sense.

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.

How to get last key in an array?

$array = array(
    'something' => array(1,2,3),
    'somethingelse' => array(1,2,3,4)
);

$last_value = end($array);
$last_key = key($array); // 'somethingelse'

This works because PHP moves it's array pointer internally for $array

Java decimal formatting using String.format?

java.text.NumberFormat is probably what you want.

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

For Tomcat 8.5.x users

You've to change the ServerInfo.properties file of Tomcat's /lib/catalina.jar file.

ServerInfo.properties file contains the following code

server.info=Apache Tomcat/8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Just open the ServerInfo.properties file by opening the catalina.jar with winrar from your Tomcat's lib folder

ServerInfo.properties file location in catalina.jar is /org/apache/catalina/util/ServerInfo.properties

Notice : shutdown the Tomcat server(if it's already opened by cmd) before doing these things otherwise your file doesn't change and your winrar shows error.

Then change the following code in ServerInfo.properties

server.info=Apache Tomcat/8.0.8.5.4
server.number=8.5.4.0
server.built=Jul 6 2016 08:43:30 UTC

Restart your eclipse(if opened). Now it'll work...

ScreenShot of eclipse

How can I send an email through the UNIX mailx command?

mail [-s subject] [-c ccaddress] [-b bccaddress] toaddress

-c and -b are optional.

-s : Specify subject;if subject contains spaces, use quotes.

-c : Send carbon copies to list of users seperated by comma.

-b : Send blind carbon copies to list of users seperated by comma.

Hope my answer clarifies your doubt.

How to run VBScript from command line without Cscript/Wscript

You may follow the following steps:

  • Open your CMD(Command Prompt)
  • Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
  • Type 'CD VBS' and hit Enter. Example: D:>CD VBS
  • Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Replace spaces with dashes and make all letters lower-case

_x000D_
_x000D_
var str = "Tatwerat Development Team";_x000D_
str = str.replace(/\s+/g, '-');_x000D_
console.log(str);_x000D_
console.log(str.toLowerCase())
_x000D_
_x000D_
_x000D_

How do I import other TypeScript files?

If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)

You have different approaches available to you, depending upon how many things you wish to export from each .ts file.

Multiple exports

Foo.ts

export class Foo {}
export interface IFoo {}

Bar.ts

import fooModule = require("Foo");

var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};

Single export

Foo.ts

class Foo
{}

export = Foo;

Bar.ts

import Foo = require("Foo");

var foo = new Foo();

get all characters to right of last dash

I created a string extension for this, hope it helps.

public static string GetStringAfterChar(this string value, char substring)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            var index = value.LastIndexOf(substring);
            return index > 0 ? value.Substring(index + 1) : value;
        }

        return string.Empty;
    }

Removing array item by value

Your solutions only work if you have unique values in your array

See:

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

A better way would be unset with array_search, in a loop if neccessary.

Set a button group's width to 100% and make buttons equal width?

Angular - equal width button group

Assuming you have an array of 'things' in your scope...

  • Make sure the parent div has a width of 100%.
  • Use ng-repeat to create the buttons within the button group.
  • Use ng-style to calculate the width for each button.

<div class="btn-group"
     style="width: 100%;">
    <button ng-repeat="thing in things"
            class="btn btn-default"
            ng-style="{width: (100/things.length)+'%'}">
        {{thing}}
    </button>
</div>

Logical operator in a handlebars.js {{#if}} conditional

Yet another crooked solution for a ternary helper:

'?:' ( condition, first, second ) {
  return condition ? first : second;
}

<span>{{?: fooExists 'found it' 'nope, sorry'}}</span>

Or a simple coalesce helper:

'??' ( first, second ) {
  return first ? first : second;
}

<span>{{?? foo bar}}</span>

Since these characters don't have a special meaning in handlebars markup, you're free to use them for helper names.

SQL recursive query on self referencing table (Oracle)

What about using PRIOR,

so

SELECT id, parent_id, PRIOR name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id`

or if you want to get the root name

SELECT id, parent_id, CONNECT_BY_ROOT name
   FROM tbl 
START WITH id = 1 
CONNECT BY PRIOR id = parent_id

ssh remote host identification has changed

My solution is:

  1. vi ~/.ssh/known_hosts
  2. delete the line that contains your want connected ip.

This is better than delete all of the known_hosts

How to convert a char to a String?

Here are a few methods, in no particular order:

char c = 'c';

String s = Character.toString(c); // Most efficient way

s = new Character(c).toString(); // Same as above except new Character objects needs to be garbage-collected

s = c + ""; // Least efficient and most memory-inefficient, but common amongst beginners because of its simplicity

s = String.valueOf(c); // Also quite common

s = String.format("%c", c); // Not common

Formatter formatter = new Formatter();
s = formatter.format("%c", c).toString(); // Same as above
formatter.close();

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)