Programs & Examples On #Kannel

Kannel is an opensource WAP and SMS gateway for two-way SMS and WAP message sending.

How to re-render flatlist?

For me, the trick was extraData and drilling down into the item component one more time

state = {
  uniqueValue: 0
}

<FlatList
  keyExtractor={(item, index) => item + index}
  data={this.props.photos}
  renderItem={this.renderItem}
  ItemSeparatorComponent={this.renderSeparator}
/>

renderItem = (item) => {
  if(item.item.selected) {
    return ( <Button onPress={this.itemPressed.bind(this, item)}>Selected</Button> );
  }
  return ( <Button onPress={this.itemPressed.bind(this, item)}>Not selected</Button>);
}

itemPressed (item) {
  this.props.photos.map((img, i) => {
    if(i === item.index) {
      if(img['selected') {
        delete img.selected;
      } else {
        img['selected'] = true;
      }
      this.setState({ uniqueValue: this.state.uniqueValue +1 });
    }
  }
}

How should I edit an Entity Framework connection string?

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

Google Geocoding API - REQUEST_DENIED

I had this problem and I realized that I was assuming that Geocoding came with the JS maps API. However, it is a separate API which I hadn't enabled in the cloud console. Enabling it fixed it right away.

JPA OneToMany not deleting child

You can try this:

@OneToOne(cascade = CascadeType.REFRESH) 

or

@OneToMany(cascade = CascadeType.REFRESH)

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Create a dropdown component

If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts

Check time difference in Javascript

Here is my rendition....

function get_time_difference(earlierDate, laterDate) 
{
    var oDiff = new Object();

    //  Calculate Differences
    //  -------------------------------------------------------------------  //
    var nTotalDiff = laterDate.getTime() - earlierDate.getTime();

    oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
    nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

    oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
    nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

    oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
    nTotalDiff -= oDiff.minutes * 1000 * 60;

    oDiff.seconds = Math.floor(nTotalDiff / 1000);
    //  -------------------------------------------------------------------  //

    //  Format Duration
    //  -------------------------------------------------------------------  //
    //  Format Hours
    var hourtext = '00';
    if (oDiff.days > 0){ hourtext = String(oDiff.days);}
    if (hourtext.length == 1){hourtext = '0' + hourtext};

    //  Format Minutes
    var mintext = '00';
    if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
    if (sectext.length == 1) { sectext = '0' + sectext };

    //  Set Duration
    var sDuration = hourtext + ':' + mintext + ':' + sectext;
    oDiff.duration = sDuration;
    //  -------------------------------------------------------------------  //

    return oDiff;
}

How do I completely rename an Xcode project (i.e. inclusive of folders)?

Extra instructions when following @Luke-West's + @Vaiden's solutions:

  • If your scheme has not changed (still showing my mac) on the top left next to the stop button:
  1. Click NEWLY created Project name (next to stop button) > Click Edit Schemes > Build (left hand side) > Remove the old target (will say it's missing) and replace with the NEWLY named project under NEWLY named project logo

Also, I did not have to use step 3 of @Vaiden's solution. Just running rm -rf Pods/ in terminal got rid of all old pod files

I also did not have to use step 9 in @Vaiden's solution, instead I just removed the OLD project named framework under Link Binary Libraries (the NEWLY named framework was already there)

So the updated steps would be as follows:

Step 1 - Rename the project

  1. If you are using cocoapods in your project, close the workspace, and open the XCode project for these steps.
  2. Click on the project you want to rename in the "Project navigator" on the left of the Xcode view.
  3. On the right select the "File inspector" and the name of your project should be in there under "Identity and Type", change it to the new name.
  4. Click "Rename" in a dropdown menu

Step 2 - Rename the Scheme

  1. In the top bar (near "Stop" button), there is a scheme for your OLD product, click on it, then go to "Manage schemes"
  2. Click on the OLD name in the scheme, and it will become editable, change the name
  3. Quit XCode.
  4. In the master folder, rename OLD.xcworkspace to NEW.xcworkspace.

Step 3 - Rename the folder with your assets

  1. Quit Xcode
  2. In the correctly named master folder, there is a newly named xcodeproj file with the the wrongly named OLD folder. Rename the OLD folder to your new name
  3. Reopen the project, you will see a warning: "The folder OLD does not exist", dismiss the warning
  4. In the "Project navigator" on the left, click the top level OLD folder name
  5. In Utilities pane under "Identity and type" you will see the "Name" entry, change this from the OLD to the new name
  6. Just below there is a "Location" entry. Click on a folder with the OLD name and chose the newly renamed folder

Step 4 - Rename the Build plist data

  1. Click on the project in the "Project navigator" on the left, in the main panel select "Build Settings"
  2. Search for "plist" in this section Under packaging, you will see Info.plist, and Product bundle identifier
  3. Rename the top entry in Info.plist
  4. Do the same for Product Identifier

Step 5 Handling Podfile

  1. In XCode: choose and edit Podfile from the project navigator. You should see a target clause with the OLD name. Change it to NEW.
  2. Quit XCode.
  3. In terminal, cd into project directory, then: pod deintegrate
  4. Run pod install.
  5. Open XCode.
  6. Click on your project name in the project navigator.
  7. In the main pane, switch to the Build Phases tab. Under Link Binary With Libraries, look for the OLD framework and remove it (should say it is missing) The NEWLY named framework should already be there, if not use the "+" button at the bottom of the window to add it
  8. If you have an objective-c Bridging header go to Build settings and change the location of the header from OLD/OLD-Bridging-Header.h to NEW/NEW-Bridging-Header.h
  9. Clean and run.

You should be able to build with no errors after you have followed all of the steps successfully

How to keep indent for second line in ordered lists via CSS?

my solution is quite the same as Pumbaa80's one, but I suggest to use display: table instead of display:table-row for li element. So it will be something like this:

ol {
    counter-reset: foo; /* default display:list-item */
}

ol > li {
    counter-increment: foo;
    display: table; /* instead of table-row */
}

ol > li::before {
    content: counter(foo) ".";
    display: table-cell;
    text-align: right;
}

So now we can use margins for spacing between li's

Using AND/OR in if else PHP statement

for AND you use

if ($status = 'clear' && $pRent == 0) {
    mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
} 

for OR you use

if ($status = 'clear' || $pRent == 0) {
    mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
} 

Google Maps V3 - How to calculate the zoom level for a given bounds

map.getBounds() is not momentary operation, so I use in similar case event handler. Here is my example in Coffeescript

@map.fitBounds(@bounds)
google.maps.event.addListenerOnce @map, 'bounds_changed', =>
  @map.setZoom(12) if @map.getZoom() > 12

Rename a table in MySQL

According to mysql docs: "to rename TEMPORARY tables, RENAME TABLE does not work. Use ALTER TABLE instead."

So this is the most portable method:

ALTER TABLE `old_name` RENAME `new_name`;

SQL Server : export query as a .txt file

you do this in the SSMS app, not the SQL. In the toolbar select

Query --> Results To --> Results To File

Call async/await functions in parallel

await Promise.all([someCall(), anotherCall()]); as already mention will act as a thread fence (very common in parallel code as CUDA), hence it will allow all the promises in it to run without blocking each other, but will prevent the execution to continue until ALL are resolved.

another approach that is worth to share is the Node.js async that will also allow you to easily control the amount of concurrency that is usually desirable if the task is directly linked to the use of limited resources as API call, I/O operations, etc.

// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
  console.log('Hello ' + task.name);
  callback();
}, 2);

// assign a callback
q.drain = function() {
  console.log('All items have been processed');
};

// add some items to the queue
q.push({name: 'foo'}, function(err) {
  console.log('Finished processing foo');
});

q.push({name: 'bar'}, function (err) {
  console.log('Finished processing bar');
});

// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  console.log('Finished processing item');
});

// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
  console.log('Finished processing bar');
});

Credits to the Medium article autor (read more)

How does JavaScript .prototype work?

It may help to categorise prototype chains into two categories.

Consider the constructor:

 function Person() {}

The value of Object.getPrototypeOf(Person) is a function. In fact, it is Function.prototype. Since Person was created as a function, it shares the same prototype function object that all functions have. It is the same as Person.__proto__, but that property should not be used. Anyway, with Object.getPrototypeOf(Person) you effectively walk up the ladder of what is called the prototype chain.

The chain in upward direction looks like this:

    Person ? Function.prototype ? Object.prototype (end point)

Important is that this prototype chain has little to do with the objects that Person can construct. Those constructed objects have their own prototype chain, and this chain can potentially have no close ancestor in common with the one mentioned above.

Take for example this object:

var p = new Person();

p has no direct prototype-chain relationship with Person. Their relationship is a different one. The object p has its own prototype chain. Using Object.getPrototypeOf, you'll find the chain is as follows:

    p ? Person.prototype ? Object.prototype (end point)

There is no function object in this chain (although that could be).

So Person seems related to two kinds of chains, which live their own lives. To "jump" from one chain to the other, you use:

  1. .prototype: jump from the constructor's chain to the created-object's chain. This property is thus only defined for function objects (as new can only be used on functions).

  2. .constructor: jump from the created-object's chain to the constructor's chain.

Here is a visual presentation of the two prototype chains involved, represented as columns:

enter image description here

To summarise:

The prototype property gives no information of the subject's prototype chain, but of objects created by the subject.

It is no surprise that the name of the property prototype can lead to confusion. It would maybe have been clearer if this property had been named prototypeOfConstructedInstances or something along that line.

You can jump back and forth between the two prototype chains:

Person.prototype.constructor === Person

This symmetry can be broken by explicitly assigning a different object to the prototype property (more about that later).

Create one Function, Get Two Objects

Person.prototype is an object that was created at the same time the function Person was created. It has Person as constructor, even though that constructor did not actually execute yet. So two objects are created at the same time:

  1. The function Person itself
  2. The object that will act as prototype when the function is called as a constructor

Both are objects, but they have different roles: the function object constructs, while the other object represents the prototype of any object that function will construct. The prototype object will become the parent of the constructed object in its prototype chain.

Since a function is also an object, it also has its own parent in its own prototype chain, but recall that these two chains are about different things.

Here are some equalities that could help grasp the issue -- all of these print true:

_x000D_
_x000D_
function Person() {};_x000D_
_x000D_
// This is prototype chain info for the constructor (the function object):_x000D_
console.log(Object.getPrototypeOf(Person) === Function.prototype);_x000D_
// Step further up in the same hierarchy:_x000D_
console.log(Object.getPrototypeOf(Function.prototype) === Object.prototype);_x000D_
console.log(Object.getPrototypeOf(Object.prototype) === null);_x000D_
console.log(Person.__proto__ === Function.prototype);_x000D_
// Here we swap lanes, and look at the constructor of the constructor_x000D_
console.log(Person.constructor === Function);_x000D_
console.log(Person instanceof Function);_x000D_
_x000D_
// Person.prototype was created by Person (at the time of its creation)_x000D_
// Here we swap lanes back and forth:_x000D_
console.log(Person.prototype.constructor === Person);_x000D_
// Although it is not an instance of it:_x000D_
console.log(!(Person.prototype instanceof Person));_x000D_
// Instances are objects created by the constructor:_x000D_
var p = new Person();_x000D_
// Similarly to what was shown for the constructor, here we have_x000D_
// the same for the object created by the constructor:_x000D_
console.log(Object.getPrototypeOf(p) === Person.prototype);_x000D_
console.log(p.__proto__ === Person.prototype);_x000D_
// Here we swap lanes, and look at the constructor_x000D_
console.log(p.constructor === Person);_x000D_
console.log(p instanceof Person);
_x000D_
_x000D_
_x000D_

Adding levels to the prototype chain

Although a prototype object is created when you create a constructor function, you can ignore that object, and assign another object that should be used as prototype for any subsequent instances created by that constructor.

For instance:

function Thief() { }
var p = new Person();
Thief.prototype = p; // this determines the prototype for any new Thief objects:
var t = new Thief();

Now the prototype chain of t is one step longer than that of p:

    t ? p ? Person.prototype ? Object.prototype (end point)

The other prototype chain is not longer: Thief and Person are siblings sharing the same parent in their prototype chain:

    Person}
    Thief  } ? Function.prototype ? Object.prototype (end point)

The earlier presented graphic can then be extended to this (the original Thief.prototype is left out):

enter image description here

The blue lines represent prototype chains, the other coloured lines represent other relationships:

  • between an object and its constructor
  • between a constructor and the prototype object that will be used for constructing objects

How to use Class<T> in Java?

All we know is "All instances of a any class shares the same java.lang.Class object of that type of class"

e.g)

Student a = new Student();
Student b = new Student();

Then a.getClass() == b.getClass() is true.

Now assume

Teacher t = new Teacher();

without generics the below is possible.

Class studentClassRef = t.getClass();

But this is wrong now ..?

e.g) public void printStudentClassInfo(Class studentClassRef) {} can be called with Teacher.class

This can be avoided using generics.

Class<Student> studentClassRef = t.getClass(); //Compilation error.

Now what is T ?? T is type parameters (also called type variables); delimited by angle brackets (<>), follows the class name.
T is just a symbol, like a variable name (can be any name) declared during writing of the class file. Later that T will be substituted with
valid Class name during initialization (HashMap<String> map = new HashMap<String>();)

e.g) class name<T1, T2, ..., Tn>

So Class<T> represents a class object of specific class type 'T'.

Assume that your class methods has to work with unknown type parameters like below

/**
 * Generic version of the Car class.
 * @param <T> the type of the value
 */
public class Car<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

Here T can be used as String type as CarName

OR T can be used as Integer type as modelNumber,

OR T can be used as Object type as valid car instance.

Now here the above is the simple POJO which can be used differently at runtime.
Collections e.g) List, Set, Hashmap are best examples which will work with different objects as per the declaration of T, but once we declared T as String
e.g) HashMap<String> map = new HashMap<String>(); Then it will only accept String Class instance objects.

Generic Methods

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For generic methods, the type parameter section must appear before the method's return type.

 class Util {
    // Generic static method
    public static <K, V, Z, Y> boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

 class Pair<K, V> {

    private K key;
    private V value;
}

Here <K, V, Z, Y> is the declaration of types used in the method arguments which should before the return type which is boolean here.

In the below; type declaration <T> is not required at method level, since it is already declared at class level.

class MyClass<T> {
   private  T myMethod(T a){
       return  a;
   }
}

But below is wrong as class-level type parameters K, V, Z, and Y cannot be used in a static context (static method here).

class Util <K, V, Z, Y>{
    // Generic static method
    public static  boolean compare(Pair<K, V> p1, Pair<Z, Y> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

OTHER VALID SCENARIOS ARE

class MyClass<T> {

        //Type declaration <T> already done at class level
        private  T myMethod(T a){
            return  a;
        }

        //<T> is overriding the T declared at Class level;
        //So There is no ClassCastException though a is not the type of T declared at MyClass<T>. 
        private <T> T myMethod1(Object a){
                return (T) a;
        }

        //Runtime ClassCastException will be thrown if a is not the type T (MyClass<T>).  
        private T myMethod1(Object a){
                return (T) a;
        }       

        // No ClassCastException        
        // MyClass<String> obj= new MyClass<String>();
        // obj.myMethod2(Integer.valueOf("1"));
        // Since type T is redefined at this method level.
        private <T> T myMethod2(T a){
            return  a;
        }

        // No ClassCastException for the below
        // MyClass<String> o= new MyClass<String>();
        // o.myMethod3(Integer.valueOf("1").getClass())
        // Since <T> is undefined within this method; 
        // And MyClass<T> don't have impact here
        private <T> T myMethod3(Class a){
            return (T) a;
        }

        // ClassCastException for o.myMethod3(Integer.valueOf("1").getClass())
        // Should be o.myMethod3(String.valueOf("1").getClass())
    private  T myMethod3(Class a){
        return (T) a;
    }


        // Class<T> a :: a is Class object of type T
        //<T> is overriding of class level type declaration; 
        private <T> Class<T> myMethod4(Class<T> a){
            return  a;
        }
    }

And finally Static method always needs explicit <T> declaration; It wont derive from class level Class<T>. This is because of Class level T is bound with instance.

Also read Restrictions on Generics

Wildcards and Subtyping

type argument for a generic method

Could not commit JPA transaction: Transaction marked as rollbackOnly

Save sub object first and then call final repository save method.

@PostMapping("/save")
    public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
        Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
        if (existingShortcode != null) {
            result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
        }
        if (result.hasErrors()) {
            return "redirect:/shortcode/create";
        }
        **shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
        shortcodeService.save(shortcode);
        return "redirect:/shortcode/create?success";
    }

Automatically open default email client and pre-populate content

Try this: It will open the default mail directly.

<a href="mailto:[email protected]"><img src="ICON2.png"></a>

Getting a HeadlessException: No X11 DISPLAY variable was set

I think you are trying to run some utility or shell script from UNIX\LINUX which has some GUI. Anyways

SOLUTION: dude all you need is an XServer & X11 forwarding enabled. I use XMing (XServer). You are already enabling X11 forwarding. Just Install it(XMing) and keep it running when you create the session with PuTTY.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

My Solution was to use 2 asp panels:

<asp:Panel ID=”..” DefaultButton=”ID_OF_SHIPPING_SUBMIT_BUTTON”….></asp:Panel>

How to git reset --hard a subdirectory?

For the case of simply discarding changes, the git checkout -- path/ or git checkout HEAD -- path/ commands suggested by other answers work great. However, when you wish to reset a directory to a revision other than HEAD, that solution has a significant problem: it doesn't remove files which were deleted in the target revision.

So instead, I have begun using the following command:

git diff --cached commit -- subdir | git apply -R --index

This works by finding the diff between the target commit and the index, then applying that diff in reverse to the working directory and index. Basically, this means that it makes the contents of the index match the contents of the revision you specified. The fact that git diff takes a path argument allows you to limit this effect to a specific file or directory.

Since this command fairly long and I plan on using it frequently, I have set up an alias for it which I named reset-checkout:

git config --global alias.reset-checkout '!f() { git diff --cached "$@" | git apply -R --index; }; f'

You can use it like this:

git reset-checkout 451a9a4 -- path/to/directory

Or just:

git reset-checkout 451a9a4

Load a HTML page within another HTML page

The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.

Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.

<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
    <div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
        <iframe src="otherpage.html" width="400px"></iframe>
    </div>
</div>

Escaping ampersand in URL

I would like to add a minor comment on Blender solution.

You can do the following:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M');

That outputs:

http://example.com?candy_name=M%26M

The great thing about this it does not only work for & but for any especial character.

For instance:

var link = 'http://example.com?candy_name=' + encodeURIComponent('M&M?><')

Outputs:

"http://example.com?candy_name=M%26M%3F%3E%3C"

Get most recent file in a directory on Linux

I use:

ls -ABrt1 --group-directories-first | tail -n1

It gives me just the file name, excluding folders.

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

groovy: safely find a key in a map and return its value

The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
if(x)
    println "x value: ${x}"

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

How to create the most compact mapping n ? isprime(n) up to a limit N?

I compared the efficiency of the most popular suggestions to determine if a number is prime. I used python 3.6 on ubuntu 17.10; I tested with numbers up to 100.000 (you can test with bigger numbers using my code below).

This first plot compares the functions (which are explained further down in my answer), showing that the last functions do not grow as fast as the first one when increasing the numbers.

plot1

And in the second plot we can see that in case of prime numbers the time grows steadily, but non-prime numbers do not grow so fast in time (because most of them can be eliminated early on).

plot2

Here are the functions I used:

  1. this answer and this answer suggested a construct using all():

    def is_prime_1(n):
        return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))
    
  2. This answer used some kind of while loop:

    def is_prime_2(n):
        if n <= 1:
            return False
        if n == 2:
            return True
        if n == 3:
            return True
        if n % 2 == 0:
            return False
        if n % 3 == 0:
            return False
    
        i = 5
        w = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += w
            w = 6 - w
    
        return True
    
  3. This answer included a version with a for loop:

    def is_prime_3(n):
        if n <= 1:
            return False
    
        if n % 2 == 0 and n > 2:
            return False
    
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    
  4. And I mixed a few ideas from the other answers into a new one:

    def is_prime_4(n):
        if n <= 1:          # negative numbers, 0 or 1
            return False
        if n <= 3:          # 2 and 3
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False
    
        for i in range(5, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    

Here is my script to compare the variants:

import math
import pandas as pd
import seaborn as sns
import time
from matplotlib import pyplot as plt


def is_prime_1(n):
    ...
def is_prime_2(n):
    ...
def is_prime_3(n):
    ...
def is_prime_4(n):
    ...

default_func_list = (is_prime_1, is_prime_2, is_prime_3, is_prime_4)

def assert_equal_results(func_list=default_func_list, n):
    for i in range(-2, n):
        r_list = [f(i) for f in func_list]
        if not all(r == r_list[0] for r in r_list):
            print(i, r_list)
            raise ValueError
    print('all functions return the same results for integers up to {}'.format(n))

def compare_functions(func_list=default_func_list, n):
    result_list = []
    n_measurements = 3

    for f in func_list:
        for i in range(1, n + 1):
            ret_list = []
            t_sum = 0
            for _ in range(n_measurements):
                t_start = time.perf_counter()
                is_prime = f(i)
                t_end = time.perf_counter()

                ret_list.append(is_prime)
                t_sum += (t_end - t_start)

            is_prime = ret_list[0]
            assert all(ret == is_prime for ret in ret_list)
            result_list.append((f.__name__, i, is_prime, t_sum / n_measurements))

    df = pd.DataFrame(
        data=result_list,
        columns=['f', 'number', 'is_prime', 't_seconds'])
    df['t_micro_seconds'] = df['t_seconds'].map(lambda x: round(x * 10**6, 2))
    print('df.shape:', df.shape)

    print()
    print('', '-' * 41)
    print('| {:11s} | {:11s} | {:11s} |'.format(
        'is_prime', 'count', 'percent'))
    df_sub1 = df[df['f'] == 'is_prime_1']
    print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
        'all', df_sub1.shape[0], 100))
    for (is_prime, count) in df_sub1['is_prime'].value_counts().iteritems():
        print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
            str(is_prime), count, count * 100 / df_sub1.shape[0]))
    print('', '-' * 41)

    print()
    print('', '-' * 69)
    print('| {:11s} | {:11s} | {:11s} | {:11s} | {:11s} |'.format(
        'f', 'is_prime', 't min (us)', 't mean (us)', 't max (us)'))
    for f, df_sub1 in df.groupby(['f', ]):
        col = df_sub1['t_micro_seconds']
        print('|{0}|{0}|{0}|{0}|{0}|'.format('-' * 13))
        print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
            f, 'all', col.min(), col.mean(), col.max()))
        for is_prime, df_sub2 in df_sub1.groupby(['is_prime', ]):
            col = df_sub2['t_micro_seconds']
            print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
                f, str(is_prime), col.min(), col.mean(), col.max()))
    print('', '-' * 69)

    return df

Running the function compare_functions(n=10**5) (numbers up to 100.000) I get this output:

df.shape: (400000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |     100,000 |     100.0 % |
| False       |      90,408 |      90.4 % |
| True        |       9,592 |       9.6 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.57 |        2.50 |      154.35 |
| is_prime_1  | False       |        0.57 |        1.52 |      154.35 |
| is_prime_1  | True        |        0.89 |       11.66 |       55.54 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        1.14 |      304.82 |
| is_prime_2  | False       |        0.24 |        0.56 |      304.82 |
| is_prime_2  | True        |        0.25 |        6.67 |       48.49 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        0.95 |       50.99 |
| is_prime_3  | False       |        0.20 |        0.60 |       40.62 |
| is_prime_3  | True        |        0.58 |        4.22 |       50.99 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.20 |        0.89 |       20.09 |
| is_prime_4  | False       |        0.21 |        0.53 |       14.63 |
| is_prime_4  | True        |        0.20 |        4.27 |       20.09 |
 ---------------------------------------------------------------------

Then, running the function compare_functions(n=10**6) (numbers up to 1.000.000) I get this output:

df.shape: (4000000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |   1,000,000 |     100.0 % |
| False       |     921,502 |      92.2 % |
| True        |      78,498 |       7.8 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.51 |        5.39 |     1414.87 |
| is_prime_1  | False       |        0.51 |        2.19 |      413.42 |
| is_prime_1  | True        |        0.87 |       42.98 |     1414.87 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        2.65 |      612.69 |
| is_prime_2  | False       |        0.24 |        0.89 |      322.81 |
| is_prime_2  | True        |        0.24 |       23.27 |      612.69 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        1.93 |       67.40 |
| is_prime_3  | False       |        0.20 |        0.82 |       61.39 |
| is_prime_3  | True        |        0.59 |       14.97 |       67.40 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.18 |        1.88 |      332.13 |
| is_prime_4  | False       |        0.20 |        0.74 |      311.94 |
| is_prime_4  | True        |        0.18 |       15.23 |      332.13 |
 ---------------------------------------------------------------------

I used the following script to plot the results:

def plot_1(func_list=default_func_list, n):
    df_orig = compare_functions(func_list=func_list, n=n)
    df_filtered = df_orig[df_orig['t_micro_seconds'] <= 20]
    sns.lmplot(
        data=df_filtered, x='number', y='t_micro_seconds',
        col='f',
        # row='is_prime',
        markers='.',
        ci=None)

    plt.ticklabel_format(style='sci', axis='x', scilimits=(3, 3))
    plt.show()

Unable to compile simple Java 10 / Java 11 project with Maven

If you are using spring boot then add these tags in pom.xml.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

and

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    `<maven.compiler.release>`10</maven.compiler.release>
</properties>

You can change java version to 11 or 13 as well in <maven.compiler.release> tag.

Just add below tags in pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.release>11</maven.compiler.release>
</properties>

You can change the 11 to 10, 13 as well to change java version. I am using java 13 which is latest. It works for me.

How to change bower's default components folder?

Hi i am same problem and resolve this ways.

windows user and vs cant'create .bowerrc file.

in cmd go any folder

install any packages which is contains .bowerrc file forexample

bower install angular-local-storage

this plugin contains .bowerrc file. copy that and go to your project and paste this file.

and in visual studio - solution explorer - show all files and include project seen .bowerrc file

i resolve this ways :)

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

SQlite - Android - Foreign key syntax

Since I cannot comment, adding this note in addition to @jethro answer.

I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:

private static final String TASK_TABLE_CREATE = "create table "
    + TASK_TABLE + " (" + TASK_ID
    + " integer primary key autoincrement, " + TASK_TITLE
    + " text not null, " + TASK_NOTES + " text not null, "
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), "
+ TASK_DATE_TIME + " text not null);";

Where I put the TASK_DATE_TIME after the foreign key line.

How to set a variable inside a loop for /F

I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2

What is does, is loop all the commandline params, and that set the variable with the proper name to the value.

After that, you can just use set value=!param1! set value2=!param2!

regardless the sequence the params are given. (so called named parameters). Note the !<>!, instead of the %<>%.

SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%P IN (%*) DO (
    call :processParam %%P
)

goto:End

:processParam [%1 - param]

    @echo "processparam : %1"
    FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
        @echo a,b %%G %%H
        set nameWithSlash=%%G
        set name=!nameWithSlash:~1!
        @echo n=!name!
        set value=%%H
        set !name!=!value!
    )
    goto :eof

:End    

change cursor from block or rectangle to line?

please Press fn +ins key together

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

How to convert a full date to a short date in javascript?

Here you go:

(new Date()).toLocaleDateString('en-US');

That's it !!

you can use it on any date object

let's say.. you have an object called "currentDate"

var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy

(or)

If you want it in local format then

currentDate.toLocaleDateString(); // gives date in local Format

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

List of macOS text editors and code editors

I've tried Komodo out a bit, and I really like it so far. Aptana, an Eclipse variant, is also rather useful for a wide variety of things. There's always good ole' VI, too!

How to get all elements which name starts with some string?

A quick and easy way is to use jQuery and do this:

var $eles = $(":input[name^='q1_']").css("color","yellow");

That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:

var DOMeles = $eles.get();

see http://api.jquery.com/attribute-starts-with-selector/

In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:

var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('q1_') == 0) {
        eles.push(inputs[i]);
    }
}

Pip freeze vs. pip list

The main difference is that the output of pip freeze can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.

In other words you can run: pip freeze > frozen-requirements.txt on one machine and then later on a different machine or on a clean environment you can do: pip install -r frozen-requirements.txt and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.

Attach (open) mdf file database with SQL Server Management Studio

You may need to repair your mdf file first using some tools. There are lot of tool available in the market. There is tool called SQL Database Recovery Tool Repairs which is very useful to repair the mdf files.

The issue might me because of corrupted transaction logs, you may use tool SQL Database Recovery Tool Repairs to repair your corrupted mdf file.

How to write ternary operator condition in jQuery?

Also, the ternary operator expects expressions, not statements. Do not use semicolons, only at the end of the ternary op.

$("#blackbox").css({'background': 
    $("#blackbox").css('background') === 'pink' ? 'black' : 'pink'});

AngularJS $resource RESTful example

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

How do I copy a hash in Ruby?

As mentioned in Security Considerations section of Marshal documentation,

If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc.

Here is an example on how to do cloning using JSON in Ruby:

require "json"

original = {"John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
cloned = JSON.parse(JSON.generate(original))

# Modify original hash
original["John"] << ' Sandler'
p original 
#=> {"John"=>"Adams Sandler", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}

# cloned remains intact as it was deep copied
p cloned  
#=> {"John"=>"Adams", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}

How can I check if given int exists in array?

You can use std::find for this:

#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end

int main () 
{
  int a[] = {3, 6, 8, 33};
  int x = 8;
  bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}

std::find returns an iterator to the first occurrence of x, or an iterator to one-past the end of the range if x is not found.

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Find and replace with sed in directory and sub directories

In linuxOS:

sed -i 's/textSerch/textReplace/g' namefile

if "sed" not work try :

perl -i -pe 's/textSerch/textReplace/g' namefile

remote rejected master -> master (pre-receive hook declined)

You might also want to check for Heroku telling you there's a typo in your CSS file.

Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after. It means Heroku has found a typo and you need to fix it in the CSS file.

You can do a find for rake aborted! and directly after that it should say why the push failed.

How to randomize (shuffle) a JavaScript array?

I have written a shuffle function on my own . The difference here is it will never repeat a value (checks in the code for this) :-

function shuffleArray(array) {
 var newArray = [];
 for (var i = 0; i < array.length; i++) {
     newArray.push(-1);
 }

 for (var j = 0; j < array.length; j++) {
    var id = Math.floor((Math.random() * array.length));
    while (newArray[id] !== -1) {
        id = Math.floor((Math.random() * array.length));
    }

    newArray.splice(id, 1, array[j]);
 }
 return newArray; }

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Git push existing repo to a new and different remote repo server?

Here is a manual way to do git remote set-url origin [new repo URL]:

  1. Clone the repository: git clone <old remote>
  2. Create a GitHub repository
  3. Open <repository>/.git/config

    $ git config -e
    
    [core]
        repositoryformatversion = 0
        filemode = false
        bare = false
        logallrefupdates = true
        symlinks = false
        ignorecase = true
    [remote "origin"]
        url = <old remote>
        fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "master"]
        remote = origin
        merge = refs/heads/master
    

    and change the remote (the url option)

    [remote "origin"]
        url = <new remote>
        fetch = +refs/heads/*:refs/remotes/origin/*
    
  4. Push the repository to GitHub: git push

You can also use both/multiple remotes.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

Import jquery first before bootstrap:

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>

Android Studio Emulator and "Process finished with exit code 0"

I had this problem and it took me nearly 2 days to resolve...

I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.

Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.

Bash write to file without echo?

awk ' BEGIN { print "Hello, world" } ' > test.txt

would do it

How to plot a function curve in R

Here is a lattice version:

library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")

Lattice output

Iterate through Nested JavaScript Objects

The following code assumes no circular references, and assumes subs is always an array (and not null in leaf nodes):

function find(haystack, needle) {
  if (haystack.label === needle) return haystack;
  for (var i = 0; i < haystack.subs.length; i ++) {
    var result = find(haystack.subs[i], needle);
    if (result) return result;
  }
  return null;
}

How to read appSettings section in the web.config file?

Add namespace

using System.Configuration;

and in place of

ConfigurationSettings.AppSettings

you should use

ConfigurationManager.AppSettings

String path = ConfigurationManager.AppSettings["configFile"];

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

How to print register values in GDB?

info registers shows all the registers; info registers eax shows just the register eax. The command can be abbreviated as i r

SOAP PHP fault parsing WSDL: failed to load external entity?

I had the same problem, I succeeded by adding:

new \SoapClient(URI WSDL OR NULL if non-WSDL mode, [
    'cache_wsdl' => WSDL_CACHE_NONE, 
    'proxy_host' => 'URL PROXY',
    'proxy_port' => 'PORT PROXY'
]);

Hope this help :)

How can I get onclick event on webview in android?

On Click event On webView works in onTouch like this:

imagewebViewNewsChart.setOnTouchListener(new View.OnTouchListener(){

  @Override   
  public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction()==MotionEvent.ACTION_MOVE){                        
       return false;     
    }

    if (event.getAction()==MotionEvent.ACTION_UP){    
        startActivity(new Intent(this,Example.class));                

    } 

    return false;                 
  }                       
});

Center image in div horizontally

A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

.top_image img { margin:0 auto; }

More information and examples from W3C.

Using custom std::set comparator

std::less<> when using custom classes with operator<

If you are dealing with a set of your custom class that has operator< defined, then you can just use std::less<>.

As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find APIs:

template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;

which allow you to do:

main.cpp

#include <cassert>
#include <set>

class Point {
    public:
        // Note that there is _no_ conversion constructor,
        // everything is done at the template level without
        // intermediate object creation.
        //Point(int x) : x(x) {}
        Point(int x, int y) : x(x), y(y) {}
        int x;
        int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
    return c.x < d;
}

int main() {
    std::set<Point, std::less<>> s;
    s.insert(Point(1, -1));
    s.insert(Point(2, -2));
    s.insert(Point(0,  0));
    s.insert(Point(3, -3));
    assert(s.find(0)->y ==  0);
    assert(s.find(1)->y == -1);
    assert(s.find(2)->y == -2);
    assert(s.find(3)->y == -3);
    // Ignore 1234, find 1.
    assert(s.find(Point(1, 1234))->y == -1);
}

Compile and run:

g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

More info about std::less<> can be found at: What are transparent comparators?

Tested on Ubuntu 16.10, g++ 6.2.0.

jQuery .scrollTop(); + animation

jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");
    });

How to apply color in Markdown?

When you want to use pure Markdown (without nested HTML), you can use Emojis to draw attention to some fragment of the file, i.e. ??WARNING??, IMPORTANT? or NEW.

Log4j, configuring a Web App to use a relative path

In case you're using Maven I have a great solution for you:

  1. Edit your pom.xml file to include following lines:

    <profiles>
        <profile>
            <id>linux</id>
            <activation>
                <os>
                    <family>unix</family>
                </os>
            </activation>
            <properties>
                <logDirectory>/var/log/tomcat6</logDirectory>
            </properties>
        </profile>
        <profile>
            <id>windows</id>
            <activation>
                <os>
                    <family>windows</family>
                </os>
            </activation>
            <properties>
                <logDirectory>${catalina.home}/logs</logDirectory>
            </properties>
        </profile>
    </profiles>
    

    Here you define logDirectory property specifically to OS family.

  2. Use already defined logDirectory property in log4j.properties file:

    log4j.appender.FILE=org.apache.log4j.RollingFileAppender
    log4j.appender.FILE.File=${logDirectory}/mylog.log
    log4j.appender.FILE.MaxFileSize=30MB
    log4j.appender.FILE.MaxBackupIndex=10
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} [%x] %-5p [%t] [%c{1}] %m%n
    
  3. That's it!

P.S.: I'm sure this can be achieved using Ant but unfortunately I don't have enough experience with it.

Keep only first n characters in a string?

You can use .substring, which returns a potion of a string:

"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

2020 Update

JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.


Safe Property Access

The optional chaining operator (?.) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.

// `undefined` if either `a` or `b` are `null`/`undefined`. `a.b.c` otherwise.
const myVariable = a?.b?.c;

The logical AND operator (&&) is the "old", more-verbose way to handle this scenario.

const myVariable = a && a.b && a.b.c;

Providing a Default

The nullish coalescing operator (??) is currently a stage 4 ECMAScript proposal. You can use it today with Babel. It allows you to set a default value if the left-hand side of the operator is a nullary value (null/undefined).

const myVariable = a?.b?.c ?? 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null ?? 'Some other value';

// Evaluates to ''
const myVariable3 = '' ?? 'Some other value';

The logical OR operator (||) is an alternative solution with slightly different behavior. It allows you to set a default value if the left-hand side of the operator is falsy. Note that the result of myVariable3 below differs from myVariable3 above.

const myVariable = a?.b?.c || 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null || 'Some other value';

// Evaluates to 'Some other value'
const myVariable3 = '' || 'Some other value';

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

What are the dark corners of Vim your mom never told you about?

Not sure if this counts as dark-corner-ish at all, but I've only just learnt it...

:g/match/y A

will yank (copy) all lines containing "match" into the "a/@a register. (The capitalization as A makes vim append yankings instead of replacing the previous register contents.) I used it a lot recently when making Internet Explorer stylesheets.

Download image from the site in .NET/C#

        private static void DownloadRemoteImageFile(string uri, string fileName)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if ((response.StatusCode == HttpStatusCode.OK ||
                response.StatusCode == HttpStatusCode.Moved ||
                response.StatusCode == HttpStatusCode.Redirect) &&
                response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) 
            {
                using (Stream inputStream = response.GetResponseStream())
                using (Stream outputStream = File.OpenWrite(fileName))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    do
                    {
                        bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                        outputStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead != 0);
                }
            }
        }

Get time of specific timezone

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

regular expression to match exactly 5 digits

what is about this? \D(\d{5})\D

This will do on:

f 23 23453 234 2344 2534 hallo33333 "50000"

23453, 33333 50000

De-obfuscate Javascript code to make it readable again

Here's a new automated tool, JSNice, to try to deobfuscate/deminify it. The tool even tries to guess the variable names, which is unbelievably cool. (It mines Javascript on github for this purpose.)

http://www.jsnice.org

Delete files older than 3 months old in a directory using .NET

Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.

This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.

Private Sub DeleteZip()

    Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
    Dim fileName As IO.FileInfo

    Try
        For Each fileName In eachFileInMydirectory.GetFiles
            If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
                fileName.Delete()
            End If
        Next

    Catch ex As Exception
        WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
    End Try
End Sub

Stopping a CSS3 Animation on last frame

-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
animation-fill-mode: forwards;

Browser Support

  • Chrome 43.0 (4.0 -webkit-)
  • IE 10.0
  • Mozilla 16.0 ( 5.0 -moz-)
  • Shafari 4.0 -webkit-
  • Opera 15.0 -webkit- (12.112.0 -o-)

Usage:-

.fadeIn {
  animation-name: fadeIn;
    -webkit-animation-name: fadeIn;

    animation-duration: 1.5s;
    -webkit-animation-duration: 1.5s;

    animation-timing-function: ease;
    -webkit-animation-timing-function: ease;

     animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
}


@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

how I can show the sum of in a datagridview column?

Add the total row to your data collection that will be bound to the grid.

How can I reverse the order of lines in a file?

This will work on both BSD and GNU.

awk '{arr[i++]=$0} END {while (i>0) print arr[--i] }' filename

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

Python Database connection Close

You can wrap the whole connection in a context manager, like the following:

from contextlib import contextmanager
import pyodbc
import sys

@contextmanager
def open_db_connection(connection_string, commit=False):
    connection = pyodbc.connect(connection_string)
    cursor = connection.cursor()
    try:
        yield cursor
    except pyodbc.DatabaseError as err:
        error, = err.args
        sys.stderr.write(error.message)
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        connection.close()

Then do something like this where ever you need a database connection:

with open_db_connection("...") as cursor:
    # Your code here

The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True).

Java and HTTPS url connection without downloading certificate

Use the latest X509ExtendedTrustManager instead of X509Certificate as advised here: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

    package javaapplication8;

    import java.io.InputStream;
    import java.net.Socket;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLEngine;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509ExtendedTrustManager;

    /**
     *
     * @author hoshantm
     */
    public class JavaApplication8 {

        /**
         * @param args the command line arguments
         * @throws java.lang.Exception
         */
        public static void main(String[] args) throws Exception {
            /*
             *  fix for
             *    Exception in thread "main" javax.net.ssl.SSLHandshakeException:
             *       sun.security.validator.ValidatorException:
             *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
             *               unable to find valid certification path to requested target
             */
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509ExtendedTrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            /*
             * end of the fix
             */

            URL url = new URL("https://10.52.182.224/cgi-bin/dynamic/config/panel.bmp");
            URLConnection con = url.openConnection();
            //Reader reader = new ImageStreamReader(con.getInputStream());

            InputStream is = new URL(url.toString()).openStream();

            // Whatever you may want to do next

        }

    }

Reactjs - Form input validation

Try powerform-react . It is based upon powerform which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.

Checkout this simple form that uses powerform-react

There is also a complex example.

Access elements in json object like an array

I noticed a couple of syntax errors, but other than that, it should work fine:

var arr = [
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har."], //<- syntax error here
  ["57.586174","16.521841"], ["57.893162","16.406090"]
];


console.log(arr[4]);    //["57.893162","16.406090"]
console.log(arr[4][0]); //57.893162

How to get scrollbar position with Javascript?

I did this for a <div> on Chrome.

element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element.scrollHeight - is the pixels of the whole div.

element.clientHeight - is the pixels that you see in your browser.

var a = element.scrollTop;

will be the position.

var b = element.scrollHeight - element.clientHeight;

will be the maximum value for scrollTop.

var c = a / b;

will be the percent of scroll [from 0 to 1].

Select from where field not equal to Mysql Php

You can use like

NOT columnA = 'x'

Or

columnA != 'x'

Or

columnA <> 'x'

And like Jeffly Bake's query, for including null values, you don't have to write like

(NOT columnA = 'x' OR columnA IS NULL)

You can make it simple by

Not columnA <=> 'x'

<=> is the Null Safe equal to Operator, which includes results from even null values.

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

Best way to pretty print a hash

Another solution which works better for me than pp or awesome_print:

require 'pry' # must install the gem... but you ALWAYS want pry installed anyways
Pry::ColorPrinter.pp(obj)

Returning a file to View/Download in ASP.NET MVC

I believe this answer is cleaner, (based on https://stackoverflow.com/a/3007668/550975)

    public ActionResult GetAttachment(long id)
    {
        FileAttachment attachment;
        using (var db = new TheContext())
        {
            attachment = db.FileAttachments.FirstOrDefault(x => x.Id == id);
        }

        return File(attachment.FileData, "application/force-download", Path.GetFileName(attachment.FileName));
    }

initializing strings as null vs. empty string

I would prefere

if (!myStr.empty())
{
    //do something
}

Also you don't have to write std::string a = "";. You can just write std::string a; - it will be empty by default

Global npm install location on windows?

Just press windows button and type %APPDATA% and type enter.

Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.

Converting an int to std::string

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.

Double free or corruption after queue::push

You are getting double free or corruption because first destructor is for object q in this case the memory allocated by new will be free.Next time when detructor will be called for object t at that time the memory is already free (done for q) hence when in destructor delete[] myArray; will execute it will throw double free or corruption. The reason is that both object sharing the same memory so define \copy, assignment, and equal operator as mentioned in above answer.

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

submitting a form when a checkbox is checked

Yes, this is possible.

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
    <input type="submit" name="submit" value="Search" />
</form>

By adding onchange="document.getElementById('formName').submit()" to each checkbox, you'll submit any time a checkbox is changed.

If you're OK with jQuery, it's even easier (and unobtrusive):

$(document).ready(function(){
    $("#formname").on("change", "input:checkbox", function(){
        $("#formname").submit();
    });
});

For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on() method.

MySQL - ignore insert error: duplicate entry

You can make sure that you do not insert duplicate information by using the EXISTS condition.

For example, if you had a table named clients with a primary key of client_id, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);

This statement inserts multiple records with a subselect.

If you wanted to insert a single record, you could use the following statement:

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);

The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.

from http://www.techonthenet.com/sql/insert.php

Kotlin Ternary Conditional Operator

You can use if expression for this in Kotlin. In Kotlin if is an expression with a result value. So in Kotlin we can write

fun max(a: Int, b: Int) = if (a > b) a else b

and in Java we can achieve the same but with larger code

int max(int a, int b) {
return a > b ? a : b
}

momentJS date string add 5 days

moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))

has to format and then convert to moment again.

Escape text for HTML

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

How to "select distinct" across multiple data frame columns in pandas?

There is no unique method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique) but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:

In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
    d[col] = df[col].unique()
d

Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

ngFor with index as value in attribute

I would use this syntax to set the index value into an attribute of the HTML element:

Angular >= 2

You have to use let to declare the value rather than #.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Angular = 1

<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

Convert all data frame character columns to factors

I used to do a simple for loop. As @A5C1D2H2I1M1N2O1R2T1 answer, lapply is a nice solution. But if you convert all the columns, you will need a data.frame before, otherwise you will end up with a list. Little execution time differences.

 mm2N=mm2New[,10:18]
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : int  4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : int  -3 -3 -2 -2 -3 -1 0 0 3 3 ...
 $ bb55  : int  7 6 3 4 4 4 9 2 5 4 ...
 $ vabb55: int  -3 -1 0 -1 -2 -2 -3 0 -1 3 ...
 $ zr    : num  0 -2 -1 1 -1 -1 -1 1 1 0 ...
 $ z55r  : num  -2 -2 0 1 -2 -2 -2 1 -1 1 ...
 $ fechar: num  0 -1 1 0 1 1 0 0 1 0 ...
 $ varr  : num  3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: int  3 0 4 6 6 6 0 6 6 1 ...

 # For solution
 t1=Sys.time()
 for(i in 1:ncol(mm2N)) mm2N[,i]=as.factor(mm2N[,i])
 Sys.time()-t1
Time difference of 0.2020121 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- lapply(mm2N, as.factor)
 Sys.time()-t1
Time difference of 0.209012 secs
 str(mm2N)
List of 9
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #data.frame lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- data.frame(lapply(mm2N, as.factor))
 Sys.time()-t1
Time difference of 0.2010119 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

How do I remove  from the beginning of a file?

You can open it by PhpStorm and right-click on your file and click on Remove BOM...

What is the <leader> in a .vimrc file?

The <Leader> key is mapped to \ by default. So if you have a map of <Leader>t, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader variable, see

:help leader

To define a mapping which uses the "mapleader" variable, the special string
"<Leader>" can be used.  It is replaced with the string value of "mapleader".
If "mapleader" is not set or empty, a backslash is used instead.  
Example:
    :map <Leader>A  oanother line <Esc>
Works like:
    :map \A  oanother line <Esc>
But after:
    :let mapleader = ","
It works like:
    :map ,A  oanother line <Esc>

Note that the value of "mapleader" is used at the moment the mapping is
defined.  Changing "mapleader" after that has no effect for already defined
mappings.


Get domain name

 protected void Page_Init(object sender, EventArgs e)
 {
   String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
 }

Update Git submodule to latest commit on origin

It seems like two different scenarios are being mixed together in this discussion:

Scenario 1

Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.

This is, as pointed out, done with

git submodule foreach git pull origin BRANCH
git submodule update

Scenario 2, which I think is what OP is aiming at

New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.

This would be done by

git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH

Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.

It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add) to point to the head of the submodule(s).

For this, I made this small Bash script:

git-update-submodules.sh

#!/bin/bash

APP_PATH=$1
shift

if [ -z $APP_PATH ]; then
  echo "Missing 1st argument: should be path to folder of a git repo";
  exit 1;
fi

BRANCH=$1
shift

if [ -z $BRANCH ]; then
  echo "Missing 2nd argument (branch name)";
  exit 1;
fi

echo "Working in: $APP_PATH"
cd $APP_PATH

git checkout $BRANCH && git pull --ff origin $BRANCH

git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH

To run it, execute

git-update-submodules.sh /path/to/base/repo BRANCH_NAME

Elaboration

First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.

The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).

git checkout $BRANCH && git pull --ff origin $BRANCH

Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:

git submodule sync
git submodule init
git submodule update

Then I update/pull all submodules:

git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

Notice a few things: First of all, I'm chaining some Git commands using && - meaning previous command must execute without error.

After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.

Finally, the final || true is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).

My favourite part:

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

Iterate all submodules - with --quiet, which removes the 'Entering MODULE_PATH' output. Using 'echo $path' (must be in single-quotes), the path to the submodule gets written to output.

This list of relative submodule paths is captured in an array ($(...)) - finally iterate this and do git add $i to update the parent repository.

Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.

I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.

I hope this will be of help to someone.

python JSON object must be str, bytes or bytearray, not 'dict

You are passing a dictionary to a function that expects a string.

This syntax:

{"('Hello',)": 6, "('Hi',)": 5}

is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

If you pass this string to loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

then it will return a dictionary that looks a lot like the one you are trying to pass to it.

You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

I have the same error on amazon AMI linux.

I Solved by setting curl.cainfo on /etc/php.d/curl.ini

https://gist.github.com/reinaldomendes/97fb2ce8a606ec813c4b

Addition October 2018

On Amazon Linux v1 edit this file

vi /etc/php.d/20-curl.ini

To add this line

curl.cainfo="/etc/ssl/certs/ca-bundle.crt"

What is an Intent in Android?

After writing a single activity, there comes a need to transition to another activity to perform another task either with or without information from the first activity.

Android platform allows transition by means of Intent Interface.

Words are taken from here: Using Intent Demo and i suggest you to go through this example because they also have provided a code file as well. so you can use it and easily understand the same.

Javascript change color of text and background to input value

document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';

convert a list of objects from one type to another using lambda expression

var list1 = new List<Type1>();
var list2 = new List<Type2>();

list1.ForEach(item => list2.Add(new Type2() { Prop1 = value1 }));

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Passing multiple argument through CommandArgument of Button in Asp.net

Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

How can I selectively escape percent (%) in Python strings?

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

List file names based on a filename pattern and file content?

find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log

How to insert 1000 rows at a time

You can insert multiple records by inserting from a result:

insert into db (@names,@email,@password) 
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword'

Just add as many records you like. There may be limitations on the complexity of the query though, so it might not be possible to add as many as 1000 records at once.

Is there a shortcut to make a block comment in Xcode?

@Nikola Milicevic

Here is the screenshot of the indentation issue. This is very minor, but it is strange that it seems to work so well, in your example visual.

I am also adding a screenshot of my Automator set-up...

Thanks

enter image description here

enter image description here

Update:

If I change the script slightly to:

enter image description here

And then select full lines in XCode, I get the desired outcome:

enter image description here

enter image description here

How to change value of ArrayList element in java

I agree with Duncan ...I have tried it with mutable object but still get the same problem... I got a simple solution to this... use ListIterator instead Iterator and use set method of ListIterator

ListIterator<Integer> i = a.listIterator();
//changed the value of first element in List
Integer x =null;
        if(i.hasNext()) {
            x = i.next();
            x = Integer.valueOf(9);
        }
    //set method sets the recent iterated element in ArrayList
    i.set(x);
        //initialized the iterator again and print all the elements
        i = a.listIterator();
        while(i.hasNext())
        System.out.print(i.next());

But this constraints me to use this only for ArrayList only which can use ListIterator...i will have same problem with any other Collection

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

How to pause / sleep thread or process in Android?

You probably don't want to do it that way. By putting an explicit sleep() in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.

Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.

Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.

What does "O(1) access time" mean?

O(1) means the time to access something is independent of the number of items in the collection.

O(N) would mean the time to access an item is a proportional to the number (N) of items in the collection.

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

Downcasting in Java

We can all see that the code you provided won't work at run time. That's because we know that the expression new A() can never be an object of type B.

But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:

variable_of_type_B = (B)expression_of_type_A;

And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B. The compiler sees that A and B have a subtype relation, so with the "expression" view of the code, the cast might work.

The compiler does not consider the special case when it knows exactly what object type expression_of_type_A will really have. It just sees the static type as A and considers the dynamic type could be A or any descendant of A, including B.

CreateProcess: No such file or directory

I experienced a similar problem. Initially, adding the GCC bin folder to my system path did not resolve the problem. I found two solutions.

The first was to run a batch file I found in the root of the MinGW install, mingwbuilds.bat. It (apparently) launches a command prompt configured correctly to run GCC. The second was to remove double-quotation marks from the GCC install bin folder that I had added to my user path variable. I tried this after noticing the batch file not using double-quotes around the install bin path.

Extra Details

I found the batch file accidentally while browsing the install folder tree trying to locate the various executables that weren't launching (according to the -v output). I found some information on the MinGW wiki, http://www.mingw.org/wiki/Getting_Started, in the Cautions and Environment Settings sections, that indicates why the MinGW installer does not set up the system or user path to include the install folder. These seem to confirm the batch file is intended to launch a command prompt suitable for running GCC from a Windows prompt.

Sum up a column from a specific row down

This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:

=sum(c6:c1048576)

For more robust solutions, see the other answers.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

How to open Android Device Monitor in latest Android Studio 3.1

If you're looking for the Hierarchy Viewer tool, it has been changed to Layout Inspector:

https://developer.android.com/studio/debug/layout-inspector.html

how can the textbox width be reduced?

<input type='text' 
       name='t1'
       id='t1'
       maxlength=10
       placeholder='typing some text' >
<p></p>

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

Java: How can I compile an entire directory structure of code ?

I would take Jon's suggestion and use Ant, since this is a pretty complex task.

However, if you are determined to get it all in one line in the Terminal, on Linux you could use the find command. But I don't recommend this at all, since there's no guarantee that, say, Foo.java will be compiled after Bar.java, even though Foo uses Bar. An example would be:

find . -type f -name "*.java" -exec javac {} \;

If all of your classes haven't been compiled yet, if there's one main harness or driver class (basically the one containing your main method), compiling that main class individually should compile most of project, even if they are in different folders, since Javac will try to the best of its abilities to resolve dependency issues.

How can I account for period (AM/PM) using strftime?

You used %H (24 hour format) instead of %I (12 hour format).

How to activate an Anaconda environment

let's assume your environment name is 'demo' and you are using anaconda and want to create a virtual environment:

(if you want python3)

    conda create -n demo python=3

(if you want python2)

    conda create -n demo python=2

After running above command you have to activate the environment by bellow command:

    source activate demo 

How to get a list of all files in Cloud Storage in a Firebase app?

So I had a project that required downloading assets from firebase storage, so I had to solve this problem myself. Here is How :

1- First, make a model data for example class Choice{}, In that class defines a String variable called image Name so it will be like that

class Choice {
    .....
    String imageName;
}

2- from a database/firebase database, go and hardcode the image names to the objects, so if you have image name called Apple.png, create the object to be

Choice myChoice = new Choice(...,....,"Apple.png");

3- Now, get the link for the assets in your firebase storage which will be something like that

gs://your-project-name.appspot.com/

like this one

4- finally, initialize your firebase storage reference and start getting the files by a loop like that

storageRef = storage.getReferenceFromUrl(firebaseRefURL).child(imagePath);

File localFile = File.createTempFile("images", "png");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {

@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
    //Dismiss Progress Dialog\\
}

5- that's it

Differences between git pull origin master & git pull origin/master

git pull = git fetch + git merge origin/branch

git pull and git pull origin branch only differ in that the latter will only "update" origin/branch and not all origin/* as git pull does.

git pull origin/branch will just not work because it's trying to do a git fetch origin/branch which is invalid.

Question related: git fetch + git merge origin/master vs git pull origin/master

What's the difference between Thread start() and Runnable run()

invoke run() is executing on the calling thread, like any other method call. whereas Thread.start() creates a new thread. invoking run() is a programmatic bug.

jQuery hide and show toggle div with plus and minus icon

Try something like this

jQuery

$('#toggle_icon').toggle(function() {

    $('#toggle_icon').text('-');
    $('#toggle_text').slideToggle();

}, function() {

    $('#toggle_icon').text('+');
    $('#toggle_text').slideToggle();

});

HTML

<a href="#" id="toggle_icon">+</a>

<div id="toggle_text" style="display: none">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

DEMO

Git: How to remove file from index without deleting files from any repository

To remove the file from the index, use:

git reset myfile

This should not affect your local copy or anyone else's.

ASP.NET MVC Conditional validation

Typical usage for conditional removal of error from Model State:

  1. Make conditional first part of controller action
  2. Perform logic to remove error from ModelState
  3. Do the rest of the existing logic (typically Model State validation, then everything else)

Example:

public ActionResult MyAction(MyViewModel vm)
{
    // perform conditional test
    // if true, then remove from ModelState (e.g. ModelState.Remove("MyKey")

    // Do typical model state validation, inside following if:
    //     if (!ModelState.IsValid)

    // Do rest of logic (e.g. fetching, saving

In your example, keep everything as is and add the logic suggested to your Controller's Action. I'm assuming your ViewModel passed to the controller action has the Person and Senior Person objects with data populated in them from the UI.

Default background color of SVG root element

Let me report a very simple solution I found, that is not written in previous answers. I also wanted to set background in an SVG, but I also want that this works in a standalone SVG file.

Well, this solution is really simple, in fact SVG supports style tags, so you can do something like

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
  <style>svg { background-color: red; }</style>
  <text>hello</text>
</svg>

Embedding JavaScript engine into .NET

I came up with a much simpler solution instead.

I built a .dll file using Javascript and then compiled it using the Javascript compiler which is available in a VS2013 developer command prompt.

Once we have the .dll we simply add it to the \Support folder and then referenced it in the project which needed to eval Javascript statements.

Detailed Steps to create a .dll:

  1. Create a file in Notepad with only these contents:

    class EvalClass { function Evaluate(expression: String) { return eval(expression); } } 
    
  2. Save the file as C:\MyEval.js

  3. Open a VS2005 Command Prompt (Start, Programs, VS2005, VS2005 Tools)

  4. Type Cd\ to get to C:\

  5. Type

    jsc /t:library C:\MyEval.js
    
  6. A new file is created named MyEval.dll.

  7. Copy MyEval.dll to the project and reference it (also reference Microsoft.Jscript.dll).

  8. Then you should be able to call it like this:

    Dim jScriptEvaluator As New EvalClass
    Dim objResult As Object
    objResult = jScriptEvaluator.Evaluate(“1==1 && 2==2”)
    

objResult is True.

Generating UNIQUE Random Numbers within a range

This probably will solve your problem:

<?php print_r(array_rand(range(1,50), 5)); ?>

Node.js: How to read a stream into a buffer?

I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers

Do I need to compile the header files in a C program?

Firstly, in general:

If these .h files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.

Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.

Basically, compiling hello.h as a standalone translation unit equivalent to creating a degenerate dummy.c file consisting only of #include "hello.h" directive, and feeding that dummy.c file to the compiler. It will compile, but it will serve no meaningful purpose.


Secondly, specifically for GCC:

Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h file.

You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html

So, this is the reason you might see .h files being fed directly to GCC.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Clear image on picturebox

You need the following:

pictbox.Image = null;
pictbox.update();

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

browser sessionStorage. share between tabs?

You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.

This code would need to exist on ALL tabs. It should execute before your other scripts.

// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
  if(!event) { event = window.event; } // ie suq
  if(!event.newValue) return;          // do nothing if no value to work with
  if (event.key == 'getSessionStorage') {
    // another tab asked for the sessionStorage -> send it
    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
    // the other tab should now have it, so we're done with it.
    localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
  } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
    // another tab sent data <- get it
    var data = JSON.parse(event.newValue);
    for (var key in data) {
      sessionStorage.setItem(key, data[key]);
    }
  }
};

// listen for changes to localStorage
if(window.addEventListener) {
  window.addEventListener("storage", sessionStorage_transfer, false);
} else {
  window.attachEvent("onstorage", sessionStorage_transfer);
};


// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
  localStorage.setItem('getSessionStorage', 'foobar');
  localStorage.removeItem('getSessionStorage', 'foobar');
};

I tested this in chrome, ff, safari, ie 11, ie 10, ie9

This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)

Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/

Difference between ProcessBuilder and Runtime.exec()

There are no difference between ProcessBuilder.start() and Runtime.exec() because implementation of Runtime.exec() is:

public Process exec(String command) throws IOException {
    return exec(command, null, null);
}

public Process exec(String command, String[] envp, File dir)
    throws IOException {
    if (command.length() == 0)
        throw new IllegalArgumentException("Empty command");

    StringTokenizer st = new StringTokenizer(command);
    String[] cmdarray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++)
        cmdarray[i] = st.nextToken();
    return exec(cmdarray, envp, dir);
}

public Process exec(String[] cmdarray, String[] envp, File dir)
    throws IOException {
    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();
}

So code:

List<String> list = new ArrayList<>();
new StringTokenizer(command)
.asIterator()
.forEachRemaining(str -> list.add((String) str));
new ProcessBuilder(String[])list.toArray())
            .environment(envp)
            .directory(dir)
            .start();

should be the same as:

Runtime.exec(command)

Thanks dave_thompson_085 for comment

Python dictionary get multiple values

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

How to access a mobile's camera from a web app?

I don't think you can - there is a W3C draft API to get audio or video, but there is no implementation yet on any of the major mobile OSs.

Second best The only option is to go with Dennis' suggestion to use PhoneGap. This will mean you need to create a native app and add it to the mobile app store/marketplace.

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:

(Get-ChildItem "[FILEPATH]" -recurse).FullName |
  Foreach-Object {
   (Get-Content $_ -Raw).
     Replace('abt7d9epp4','w2svuzf54f').
     Replace('AccountName=adtestnego','AccountName=zadtestnego').
     Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
   Set-Content $_
  }

Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.

Leader Not Available Kafka in Console Producer

For me, it was happen due to a miss configuration
Docker port (9093)
Kafka command port "bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TopicName"
I checked my configuration to match port and now everything is ok

SQL Server check case-sensitivity?

SQL Server is not case sensitive. SELECT * FROM SomeTable is the same as SeLeCT * frOM soMetaBLe.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I was in the same boat. Installed Eclipse, realized need CDT.

sudo apt-get install eclipse eclipse-cdt g++

This just adds the CDT package on top of existing installation - no un-installation etc. required.

What is %2C in a URL?

Simple & Easy answer,

The %2C means , comma in URL. when you add the String "abc,defg" in the url as parameter then that comma in the string which is abc , defg is changed to abc%2Cdefg .There is no need to worry about it.

Convert nullable bool? to bool

System.Convert works fine by me.

using System; ... Bool fixed = Convert.ToBoolean(NullableBool);

Process all arguments except the first one (in a bash script)

If you want a solution that also works in /bin/sh try

first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"

shift [n] shifts the positional parameters n times. A shift sets the value of $1 to the value of $2, the value of $2 to the value of $3, and so on, decreasing the value of $# by one.

How to check for null/empty/whitespace values with a single test?

As in Oracle you can use NVL function in MySQL you can use IFNULL(columnaName, newValue) to achieve your desired result as in this example

SELECT column_name from table_name WHERE IFNULL(column_name,'') NOT LIKE '%_%';

Is there a difference between PhoneGap and Cordova commands?

From what I've read (and please correct me if Im wrong):

Phonegap claim that they started trying to make this but couldn't, so they passed it to the Apache Software Foundation.

Apache in their awesomeness (Long live Apache) fixed it, developed it, and made it supremely awesome.

Now Phonegap are trying to maintain and enhance a copy they took back, but keep stuffing it up.

So, by my thinking, I want a solid and trustworthy dev platform made by seasoned professionals that I can trust, rather than a patched upon sub-version of said. Therefore Id say I am a Cordova developer NOT a Phonegap developer.

Iv also read that in a second desperate attempt to gain popularity and control over the great works of Apache, Phonegap has now been sold under the Adobe flag. You know Adobe, they are the guys who do nothing for free and are so bad at maintaining software life-cycles that their apps need to perform updates every time you blink, and for some reason each of their apps are about 100 times the size you would expect.

I guess that is the summary of my research if I didn't read it wrongly.

And if true, then lets all drop this whole Phonegap nonsense and just stick with Cordova.

Customizing Bootstrap CSS template

The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :

  1. Clone bootstrap in your root folder : git clone https://github.com/twbs/bootstrap.git
  2. Rename it "bootstrap"
  3. Create a package.json file : https://gist.github.com/jide/8440609
  4. Create a Gruntfile.js : https://gist.github.com/jide/8440502
  5. Create a "less" folder
  6. Copy bootstrap/less/variables.less into the "less" folder
  7. Change the font path : @icon-font-path: "../bootstrap/fonts/";
  8. Create a custom style.less file in the "less" folder which imports bootstrap.less and your custom variables.less file : https://gist.github.com/jide/8440619
  9. Run npm install
  10. Run grunt watch

Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !

EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate

ggplot2: sorting a plot

I've recently been struggling with a related issue, discussed at length here: Order of legend entries in ggplot2 barplots with coord_flip() .

As it happens, the reason I had a hard time explaining my issue clearly, involved the relation between (the order of) factors and coord_flip(), as seems to be the case here.

I get the desired result by adding + xlim(rev(levels(x$variable))) to the ggplot statement:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))

This reverses the order of factors as found in the original data frame in the x-axis, which will become the y-axis with coord_flip(). Notice that in this particular example, the variable also happen to be in alphabetical order, but specifying an arbitrary order of levels within xlim() should work in general.

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

How can I retrieve Id of inserted entity using Entity framework?

When you use EF 6.x code first

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

and initialize a database table, it will put a

(newsequentialid())

inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.

The problem is if you create a table and add the

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

part later, future update-databases won't add back the (newsequentialid())

To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

REST, HTTP DELETE and parameters

I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.

Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Fixing the order of facets in ggplot

Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:

# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
                    size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
                    size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
                    amount=c(48.4, 48.1, 46.8, 
                             25.9, 26.0, 24.9,
                             20.8, 21.5, 16.5,
                             21.1, 21.4, 20.1))

temp %>% 
  arrange(size_num) %>% # sort
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor

  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:

    temp %>% 
  arrange(size_num) %>%
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
  arrange(desc(amount)) %>%
  mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)


  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

Raise an error manually in T-SQL to jump to BEGIN CATCH block

you can use raiserror. Read more details here

--from MSDN

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

EDIT If you are using SQL Server 2012+ you can use throw clause. Here are the details.

How to round a number to significant figures in Python

I have created the package to-precision that does what you want. It allows you to give your numbers more or less significant figures.

It also outputs standard, scientific, and engineering notation with a specified number of significant figures.

In the accepted answer there is the line

>>> round_to_1(1234243)
1000000.0

That actually specifies 8 sig figs. For the number 1234243 my library only displays one significant figure:

>>> from to_precision import to_precision
>>> to_precision(1234243, 1, 'std')
'1000000'
>>> to_precision(1234243, 1, 'sci')
'1e6'
>>> to_precision(1234243, 1, 'eng')
'1e6'

It will also round the last significant figure and can automatically choose what notation to use if a notation isn't specified:

>>> to_precision(599, 2)
'600'
>>> to_precision(1164, 2)
'1.2e3'

How do I print the elements of a C++ vector in GDB?

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

Server did not recognize the value of HTTP Header SOAPAction

I've decided to post my own answer here because I've lost a few hours on this and I think that, although the accepted answer is very good and pointed me in the right direction (yes, it got a voteup), it was not detailed enough to explain what was wrong with my application, at least in my case.

I'm running a BPEL module in OpenESB 2.2 and the Test Case of my Composite Application was failing with the following error:

Caused by: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .

After doing some research I've noticed that the external WSDL has all the clues we need to fix this problem, e.g., I'm using the following web service to validate a credit card number through a orchestration of Web Services: http://www.webservicex.net/CreditCard.asmx?WSDL

If you check the <wsdl:operation elements you will see that it clearly states the soapAction for that operation:

<wsdl:binding name="CCCheckerSoap" type="tns:CCCheckerSoap">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
  <wsdl:operation name="ValidateCardNumber">
    <soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>
    <wsdl:input>
  <soap:body use="literal"/>
</wsdl:input>
...

But, once you create the Composite Application and build the project with the BPEL that invokes this external WSDL service, for some reason (bug?), the XML of the Composite Application Service Assembly (CASA) binding is generated with an empty soapAction parameter:

<binding name="casaBinding1" type="ns:CCCheckerSoap">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="ValidateCardNumber">
            <soap:operation soapAction="" style="document"/>
            <input>
                <soap:body use="literal"/>
            </input>

Once you copy the proper soapAction (http://www.webservicex.net/ValidateCardNumber) into this parameter, the application's Test Case will correctly and return the expected Soap response.

<soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>

So, it's a more specific solution that I decided to document based on the information found in this blog post: http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/.

It means (at least in my case) that you are accessing a web service with SOAP and passing a SOAPAction parameter in the HTTP request that does not match what the service is expecting.

How to change the URI (URL) for a remote Git repository?

As seen here,

$ git remote rm origin
$ git remote add origin [email protected]:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master

Read a text file in R line by line

I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).

con = file("pathtotargetfile", "r")
readsizeof<-2    # read size for one step to caculate number of lines in file
nooflines<-0     # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0)    # calculate number of lines. Also a better solution for big file
  nooflines<-nooflines+linesread

con = file("pathtotargetfile", "r")    # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0)    # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
  tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
  print(is.vector(tmp))
  print(tmp)
}
close(con)

Get ASCII value at input word

char ch='A';

System.out.println((int)ch);

How to check type of variable in Java?

public class Demo1 {

Object printType(Object o)
{
    return o;
}
 public static void main(String[] args) {

    Demo1 d=new Demo1();
    Object o1=d.printType('C');
    System.out.println(o1.getClass().getSimpleName());

}

}

python numpy/scipy curve fitting

I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

enter image description here

Where does Anaconda Python install on Windows?

conda info will display information about the current install, including the active env location which is what you want.

Here's my output:

(base) C:\Users\USERNAME>conda info

     active environment : base
    active env location : C:\ProgramData\Miniconda3
            shell level : 1
       user config file : C:\Users\USERNAME\.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : not installed
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
       base environment : C:\ProgramData\Miniconda3  (read only)
           channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : C:\ProgramData\Miniconda3\pkgs
                          C:\Users\USERNAME\.conda\pkgs
                          C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
       envs directories : C:\Users\USERNAME\.conda\envs
                          C:\ProgramData\Miniconda3\envs
                          C:\Users\USERNAME\AppData\Local\conda\conda\envs
               platform : win-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
          administrator : False
             netrc file : None
           offline mode : False

If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.

If that's the case find and open the Anaconda Prompt and do it from there.

Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.

Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)

How do I calculate someone's age in Java?

It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:

public static int age(Date birthday, Date date) {
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    int d1 = Integer.parseInt(formatter.format(birthday));
    int d2 = Integer.parseInt(formatter.format(date));
    int age = (d2-d1)/10000;
    return age;
}

git push rejected: error: failed to push some refs

What I did to solve the problem was:

git pull origin [branch]
git push origin [branch]

Also make sure that you are pointing to the right branch by running:

git remote set-url origin [url]

Zsh: Conda/Pip installs command not found

  1. Open your ~./bashrc
  2. Find the following code (maybe something similar) that launches your conda:

    # >>> conda init >>>
    # !! Contents within this block are managed by 'conda init' !!
    __conda_setup="$(CONDA_REPORT_ERRORS=false '/anaconda3/bin/conda' shell.bash hook 2> /dev/null)" if [ $? -eq 0 ]; then
        \eval "$__conda_setup" else
        if [ -f "/anaconda3/etc/profile.d/conda.sh" ]; then
            . "/anaconda3/etc/profile.d/conda.sh"
            CONDA_CHANGEPS1=false conda activate base
        else
            \export PATH="/anaconda3/bin:$PATH"
        fi fi unset __conda_setup
    # <<< conda init <<<

  1. source ~/.zshrc
  2. Things should work.

Python JSON encoding

Try:

import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"

simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon

NB: Based on Paolo's answer.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

You can also look in the registry.

    using System.IO;
    using Microsoft.Win32;

    string GetMimeType(FileInfo fileInfo)
    {
        string mimeType = "application/unknown";

        RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(
            fileInfo.Extension.ToLower()
            );

        if(regKey != null)
        {
            object contentType = regKey.GetValue("Content Type");

            if(contentType != null)
                mimeType = contentType.ToString();
        }

        return mimeType;
    }

One way or another you're going to have to tap into a database of MIMEs - whether they're mapped from extensions or magic numbers is somewhat trivial - windows registry is one such place. For a platform independent solution though one would have to ship this DB with the code (or as a standalone library).

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

How to list the size of each file and directory and sort by descending size in Bash?

Simply navigate to directory and run following command:

du -a --max-depth=1 | sort -n

OR add -h for human readable sizes and -r to print bigger directories/files first.

du -a -h --max-depth=1 | sort -hr

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

Vertically centering a div inside another div

Vertically centering div items inside another div

Just set the container to display:table and then the inner items to display:table-cell. Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

Just note that the vertical alignment will depend on the height of the parent container.

_x000D_
_x000D_
.cn_x000D_
{_x000D_
display:table;_x000D_
height:80px;_x000D_
background-color:#555;_x000D_
}_x000D_
_x000D_
.inner_x000D_
{_x000D_
display:table-cell;_x000D_
vertical-align:middle;_x000D_
color:#FFF;_x000D_
padding-left:10px;_x000D_
padding-right:10px;_x000D_
}
_x000D_
<div class="cn">_x000D_
  <div class="inner">Item 1</div>_x000D_
  <div class="inner">Item 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

Goto the SDK manager in your IDE and install the latest "Intel HAXM" and start the emulator.

If it is throwing the error as

Starting emulator for AVD 'X86'
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX is not installed on this machine (/dev/HAX is missing).

It means that some hardware graphical features are to be assigned.So to overcome this problem just go to the path where you have your Adroid SDK installed.

Windows

C:\Android\SDK\extras\intel\Hardware_Accelerated_Execution_Manager

There you can find the file intelhaxm-android.exe.

Mac OS X

On Mac OSXthere is a IntelHAXM_X.X.X.dmg file, mount it and you'll find an mpkg-file.

Install the file and restart all the applications using android emulator such as(android studio,cmd etc..,).

Now try to open the emulator it will work fine

iOS Remote Debugging

iOS WebKit debug proxy is the simpliest solution - debug and live preview directly in Chrome.

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}