Programs & Examples On #Html escape characters

HTML escape characters are special codes, used to display Unicode characters including those which can't be typed on a standard keyboard and those having a special meaning to HTML.

What do < and > stand for?

&lt; ==  lesser-than == <
&gt; == greater-than == >

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

How do I replicate a \t tab space in HTML?

The same issue exists for a Mediawiki: It does not provide tabs, nor are consecutive spaces allowed.

Although not really a TAB function, the workaround was to add a template named 'Tab', which replaces each call (i.e. {{tab}}) by 4 non-breaking space symbols:

 &nbsp;&nbsp;&nbsp;&nbsp; 

Those are not collapsed, and create a 4 space distance anywhere used.
It's not really a tab, because it would not align to fixed tab positions, but I still find many uses for it.

Maybe someone can come up with similar mechanism for a Wiki Template in HTML (CSS class or whatever).

HTML-encoding lost when attribute read from input field

I ran into some issues with backslash in my Domain\User string.

I added this to the other escapes from Anentropic's answer

.replace(/\\/g, '&#92;')

Which I found here: How to escape backslash in JavaScript?

Get class name using jQuery

If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:

" myclass1  myclass2 ".split(' ').join(".")

produces

".myclass1..myclass2."

I think you're better off using a regular expression to match on set of allowable characters for class names. For example:

" myclass1  myclass2  ".match(/[\d\w-_]+/g);

produces

["myclass1", "myclass2"]

The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply!

Remove item from list based on condition

prods.Remove(prods.Find(x => x.ID == 1));

How to change the Push and Pop animations in a navigation based app

I did the following and it works fine.. and is simple and easy to understand..

CATransition* transition = [CATransition animation];
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade; //kCATransitionMoveIn; //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
//transition.subtype = kCATransitionFromTop; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[[self navigationController] popViewControllerAnimated:NO];

And the same thing for push..


Swift 3.0 version:

let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
self.navigationController?.view.layer.add(transition, forKey: nil)
_ = self.navigationController?.popToRootViewController(animated: false)

How to redirect docker container logs to a single file?

The easiest way that I use is this command on terminal:

docker logs elk > /home/Desktop/output.log

structure is:

docker logs <Container Name> > path/filename.log

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

Do a "git export" (like "svn export")?

My preference would actually be to have a dist target in your Makefile (or other build system) that exports a distributable archive of your code (.tar.bz2, .zip, .jar, or whatever is appropriate). If you happen to be using GNU autotools or Perl's MakeMaker systems, I think this exists for you automatically. If not, I highly recommend adding it.

ETA (2012-09-06): Wow, harsh downvotes. I still believe it is better to build your distributions with your build tools rather than your source code control tool. I believe in building artifacts with build tools. In my current job, our main product is built with an ant target. We are in the midst of switching source code control systems, and the presence of this ant target means one less hassle in migration.

How does OAuth 2 protect against things like replay attacks using the Security Token?

Figure 1, lifted from RFC6750:

     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+

double free or corruption (!prev) error in c program

Change this line

double *ptr = malloc(sizeof(double *) * TIME);

to

double *ptr = malloc(sizeof(double) * TIME);

How do I get the current mouse screen coordinates in WPF?

Do you want coordinates relative to the screen or the application?

If it's within the application just use:

Mouse.GetPosition(Application.Current.MainWindow);

If not, I believe you can add a reference to System.Windows.Forms and use:

System.Windows.Forms.Control.MousePosition;

jQuery - Get Width of Element when Not Visible (Display: None)

Here is a trick I have used. It involves adding some CSS properties to make jQuery think the element is visible, but in fact it is still hidden.

var $table = $("#parent").children("table");
$table.css({ position: "absolute", visibility: "hidden", display: "block" });
var tableWidth = $table.outerWidth();
$table.css({ position: "", visibility: "", display: "" });

It is kind of a hack, but it seems to work fine for me.

UPDATE

I have since written a blog post that covers this topic. The method used above has the potential to be problematic since you are resetting the CSS properties to empty values. What if they had values previously? The updated solution uses the swap() method that was found in the jQuery source code.

Code from referenced blog post:

//Optional parameter includeMargin is used when calculating outer dimensions  
(function ($) {
$.fn.getHiddenDimensions = function (includeMargin) {
    var $item = this,
    props = { position: 'absolute', visibility: 'hidden', display: 'block' },
    dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
    $hiddenParents = $item.parents().andSelf().not(':visible'),
    includeMargin = (includeMargin == null) ? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function () {
        var old = {};

        for (var name in props) {
            old[name] = this.style[name];
            this.style[name] = props[name];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);

    $hiddenParents.each(function (i) {
        var old = oldProps[i];
        for (var name in props) {
            this.style[name] = old[name];
        }
    });

    return dim;
}
}(jQuery));

Running a shell script through Cygwin on Windows

If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).

To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash echo '$0 = ' $0 echo '$1 = ' $1 filepath=$1 3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run


Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.

Note: Using this method, you do not need to prepend your script file name with bash to run

printf with std::string?

use myString.c_str() if you want a c-like string (const char*) to use with printf

thanks

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For UWP (Windows Store) apps none of the above will work (PointerPressed doesn't fire; no Preview, DropDownClosed or SelectedIndexChanged events exist)

I had to resort to a transparent button overlaying the ComboBox (but not its drop down arrow). When you press on the arrow, the list drops down as usual and the Combo Box's SelectionChanged event fires. When you click anywhere else on the Combo Box the transparent button's click event fires allowing you to re-select the Combo Box's current value.

Some working XAML code:

                <Grid x:Name="ComboOverlay" Margin="0,0,5,0"> <!--See comments in code behind at ClickedComboButValueHasntChanged event handler-->
                    <ComboBox x:Name="NewFunctionSelect" Width="97" ItemsSource="{x:Bind Functions}"
                          SelectedItem="{x:Bind ChosenFunction}" SelectionChanged="Function_SelectionChanged"/>
                    <Button x:Name="OldFunctionClick" Height="30" Width="73" Background="Transparent" Click="ClickedComboButValueHasntChanged"/>
                </Grid>

Some working C# code:

    /// <summary>
    /// It is impossible to simply click a ComboBox to select the shown value again. It always drops down the list of options but
    ///     doesn't raise SelectionChanged event if the value selected from the list is the same as before
    ///     
    /// To handle this, a transparent button is overlaid over the ComboBox (but not its dropdown arrow) to allow reselecting the old value
    /// Thus clicking over the dropdown arrow allows the user to select a new option from the list, but
    ///     clicking anywhere else in the Combo re-selects the previous value
    /// </summary>
    private void ClickedComboButValueHasntChanged(object sender, RoutedEventArgs e)
    {
        //You could also dummy up a SelectionChangedEvent event and raise it to invoke Function_SelectionChanged handler, below 
        FunctionEntered(NewFunctionSelect.SelectedValue as string);
    }

    private void Function_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        FunctionEntered(e.AddedItems[0] as string);
    }

Interface vs Abstract Class (general OO)

Interface:- == contract.Whichever class implements it has to follow all the specification of interface.

A real-time example would be any ISO marked Product.ISO gives set of rules/specification on how the product should be build and what minimum set of features it Must have.

This is nothing but subset of properties product Must have.ISO will sign the product only if it satisfies the its standards.

Now take a look at this code

public interface IClock{       //defines a minimum set of specification which a clock should have

    public abstract Date getTime();
    public abstract int getDate();
}
public class Fasttrack: Clock {
    // Must have getTime() and getTime() as it implements IClock
    // It also can have other set of feature like 
    public void startBackgroundLight() {
        // watch with internal light in it.
    }
    .... //Fastrack can support other feature as well
    ....
    ....
}

Here a Fastrack is called as watch because it has all that features that a watch must suppost(Minimum set of features).

Why and When Abstract:

From MSDN:

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract simply means if you cannot define it completely declare it as an abstract .Implementing class will complete this implementation.

E.g -: Suppose I declare a Class Recipe as abstract but I dont know which recipe to be made.Then I will generalize this class to define the common definition of any recipe.The implantation of recipe will depend on implementing dish.

Abstract class can consist of abstract methods as well as not abstract method So you can notice the difference in Interface.So not necessarily every method your implementing class must have.You only need to override the abstract methods.

In Simple words If you want tight coupling use Interface o/w use in case of lose coupling Abstract Class

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

WHERE vs HAVING

Why is it that you need to place columns you create yourself (for example "select 1 as number") after HAVING and not WHERE in MySQL?

WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates).

In general, you can reference aliases in neither of these clauses, but MySQL allows referencing SELECT level aliases in GROUP BY, ORDER BY and HAVING.

And are there any downsides instead of doing "WHERE 1" (writing the whole definition instead of a column name)

If your calculated expression does not contain any aggregates, putting it into the WHERE clause will most probably be more efficient.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to change PHP version used by composer

Another possibility to make composer think you're using the correct version of PHP is to add to the config section of a composer.json file a platform option, like this:

"config": {
    "platform": {
        "php": "<ver>"
    }
},

Where <ver> is the PHP version of your choice.

Snippet from the docs:

Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.

Remote debugging a Java application

Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):

java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>

Original answer follows.


Try this:

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp

Two points here:

  1. No spaces in the runjdwp option.
  2. Options come before the class name. Any arguments you have after the class name are arguments to your program!

How do you launch the JavaScript debugger in Google Chrome?

Windows and Linux:

Ctrl + Shift + I keys to open Developer Tools

Ctrl + Shift + J to open Developer Tools and bring focus to the Console.

Ctrl + Shift + C to toggle Inspect Element mode.

Mac:

? + ? + I keys to open Developer Tools

? + ? + J to open Developer Tools and bring focus to the Console.

? + ? + C to toggle Inspect Element mode.

Source

Other shortcuts

How to sort a List of objects by their date (java collections, List<Object>)

I'd add Commons NullComparator instead to avoid some problems...

Convert String to Float in Swift

Use this:

 // get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

How do I start Mongo DB from Windows?

I have installed MongoDB in D:\Installs folder instead of default location.

Open command prompt and change directory into D:\Installs\MongoDB\Server\4.4\bin and run the following command:

mongod.exe --config=mongod.cfg

This should start the MongoDB service.

Now, Open MongoDB Compass and connect as shown below:

enter image description here

Java Delegates?

I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.

How It Works

There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.

With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.

In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.

The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.

static private final Method             COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);

...

IoUtil.processDirectory(root,new Callback(this,COUNT),selector);

...

private void callback_count(File dir, File fil) {
    if(fil!=null) {                                                                             // file is null for processing a directory
        fileTotal++;
        if(fil.length()>fileSizeLimit) {
            throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
            }
        }
    progress("Counting",dir,fileTotal);
    }

IoUtil.processDirectory():

/**
 * Process a directory using callbacks.  To interrupt, the callback must throw an (unchecked) exception.
 * Subdirectories are processed only if the selector is null or selects the directories, and are done
 * after the files in any given directory.  When the callback is invoked for a directory, the file
 * argument is null;
 * <p>
 * The callback signature is:
 * <pre>    void callback(File dir, File ent);</pre>
 * <p>
 * @return          The number of files processed.
 */
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
    return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
    }

static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
    int                                 cnt=0;

    if(!dir.isDirectory()) {
        if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
        }
    else {
        cbk.invoke(dir,(Object[])null);

        File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
        if(lst!=null) {
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(!ent.isDirectory()) {
                    cbk.invoke(dir,ent);
                    lst[xa]=null;
                    cnt++;
                    }
                }
            for(int xa=0; xa<lst.length; xa++) {
                File ent=lst[xa];
                if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
                }
            }
        }
    return cnt;
    }

This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.

Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".

The page cannot be displayed because an internal server error has occurred on server

For those of you who hit this stackoverflow entry because it ranks high for the phrase:

The page cannot be displayed because an internal server error has occurred.

In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.

Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.

Getting mouse position in c#

Initialize the current cursor. Use it to get the position of X and Y

this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

Convert Dictionary to JSON in Swift

private func convertDictToJson(dict : NSDictionary) -> NSDictionary?
{
    var jsonDict : NSDictionary!

    do {
        let jsonData = try JSONSerialization.data(withJSONObject:dict, options:[])
        let jsonDataString = String(data: jsonData, encoding: String.Encoding.utf8)!
        print("Post Request Params : \(jsonDataString)")
        jsonDict = [ParameterKey : jsonDataString]
        return jsonDict
    } catch {
        print("JSON serialization failed:  \(error)")
        jsonDict = nil
    }
    return jsonDict
}

Bootstrap carousel width and height

If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Third slide">
    </div>
  </div>
</div>

Solution:

The solution is to put "div" around the image, with the class ".container", like this:

<div class="carousel-item active">
  <div class="container">
    <img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
  </div>
</div>

Removing special characters VBA Excel

This is what I use, based on this link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

Usage:

=StripAccentb(B2) ' cell address

Sub version for all cells in a sheet:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

Script to Change Row Color when a cell changes text

I used GENEGC's script, but I found it quite slow.

It is slow because it scans whole sheet on every edit.

So I wrote way faster and cleaner method for myself and I wanted to share it.

function onEdit(e) {
    if (e) { 
        var ss = e.source.getActiveSheet();
        var r = e.source.getActiveRange(); 

        // If you want to be specific
        // do not work in first row
        // do not work in other sheets except "MySheet"
        if (r.getRow() != 1 && ss.getName() == "MySheet") {

            // E.g. status column is 2nd (B)
            status = ss.getRange(r.getRow(), 2).getValue();

            // Specify the range with which You want to highlight
            // with some reading of API you can easily modify the range selection properties
            // (e.g. to automatically select all columns)
            rowRange = ss.getRange(r.getRow(),1,1,19);

            // This changes font color
            if (status == 'YES') {
                rowRange.setFontColor("#999999");
            } else if (status == 'N/A') {
                rowRange.setFontColor("#999999");
            // DEFAULT
            } else if (status == '') { 
                rowRange.setFontColor("#000000");
            }   
        }
    }
}

Mapping many-to-many association table with extra column(s)

I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.

Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).

First here is the Java objects.

public class A implements Serializable{  

    protected int id;
    // put some others fields if needed ...   
    private Set<AC> ac = new HashSet<AC>();

    public A(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Set<AC> getAC() {
        return ac;
    }

    public void setAC(Set<AC> ac) {
        this.ac = ac;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 97;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof A))
            return false;
        final A other = (A) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

public class C implements Serializable{

    protected int id;
    // put some others fields if needed ...    

    public C(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 98;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof C))
            return false;
        final C other = (C) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).

public class ACId implements Serializable{

    private A a;
    private C c;

    public ACId() {
        super();
    }

    public A getA() {
        return a;
    }
    public void setA(A a) {
        this.a = a;
    }
    public C getC() {
        return c;
    }
    public void setC(C c) {
        this.c = c;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((a == null) ? 0 : a.hashCode());
        result = prime * result
                + ((c == null) ? 0 : c.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ACId other = (ACId) obj;
        if (a == null) {
            if (other.a != null)
                return false;
        } else if (!a.equals(other.a))
            return false;
        if (c == null) {
            if (other.c != null)
                return false;
        } else if (!c.equals(other.c))
            return false;
        return true;
    }
}

Now let's create the association object itself.

public class AC implements java.io.Serializable{

    private ACId id = new ACId();
    private String extra;

    public AC(){

    }

    public ACId getId() {
        return id;
    }

    public void setId(ACId id) {
        this.id = id;
    }

    public A getA(){
        return getId().getA();
    }

    public C getC(){
        return getId().getC();
    }

    public void setC(C C){
        getId().setC(C);
    }

    public void setA(A A){
        getId().setA(A);
    }

    public String getExtra() {
        return extra;
    }

    public void setExtra(String extra) {
        this.extra = extra;
    }

    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        AC that = (AC) o;

        if (getId() != null ? !getId().equals(that.getId())
                : that.getId() != null)
            return false;

        return true;
    }

    public int hashCode() {
        return (getId() != null ? getId().hashCode() : 0);
    }
}

At this point, it's time to map all our classes with hibernate xml configuration.

A.hbm.xml and C.hxml.xml (quiete the same).

<class name="A" table="a">
        <id name="id" column="id_a" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">a_id_seq</param>
            </generator>
        </id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
    <set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
        <key>
            <column name="id_a" not-null="true" />
        </key>
        <one-to-many class="AC" />
    </set>
</class>

<class name="C" table="c">
        <id name="id" column="id_c" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">c_id_seq</param>
            </generator>
        </id>
</class>

And then association mapping file, a_c.hbm.xml.

<class name="AC" table="a_c">
    <composite-id name="id" class="ACId">
        <key-many-to-one name="a" class="A" column="id_a" />
        <key-many-to-one name="c" class="C" column="id_c" />
    </composite-id>
    <property name="extra" type="string" column="extra" />
</class>

Here is the code sample to test.

A = ADao.get(1);
C = CDao.get(1);

if(A != null && C != null){
    boolean exists = false;
            // just check if it's updated or not
    for(AC a : a.getAC()){
        if(a.getC().equals(c)){
            // update field
            a.setExtra("extra updated");
            exists = true;
            break;
        }
    }

    // add 
    if(!exists){
        ACId idAC = new ACId();
        idAC.setA(a);
        idAC.setC(c);

        AC AC = new AC();
        AC.setId(idAC);
        AC.setExtra("extra added"); 
        a.getAC().add(AC);
    }

    ADao.save(A);
}

Git: Remove committed file after push

You can revert only one file to a specified revision.

First you can check on which commits the file was changed.

git log path/to/file.txt

Then you can checkout the file with the revision number.

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt

After that you can commit and push it again.

Elastic Search: how to see the indexed data

If you are using Google Chrome then you can simply use this extension named as Sense it is also a tool if you use Marvel.

https://chrome.google.com/webstore/detail/sense-beta/lhjgkmllcaadmopgmanpapmpjgmfcfig

Calling a function within a Class method?

Try this one:

class test {
     public function newTest(){
          $this->bigTest();
          $this->smallTest();
     }

     private function bigTest(){
          //Big Test Here
     }

     private function smallTest(){
          //Small Test Here
     }

     public function scoreTest(){
          //Scoring code here;
     }
}

$testObject = new test();

$testObject->newTest();

$testObject->scoreTest();

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

What's the function like sum() but for multiplication? product()?

There's a prod() in numpy that does what you're asking for.

std::string to char*

(This answer applies to C++98 only.)

Please, don't use a raw char*.

std::string str = "string";
std::vector<char> chars(str.c_str(), str.c_str() + str.size() + 1u);
// use &chars[0] as a char*

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

laravel 5.3 new Auth::routes()

If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

Overlaying histograms with ggplot2 in R

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

which produces something like this:

enter image description here

Edited to fix typos; you wanted fill, not colour.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

Use the Bit datatype. It has values 1 and 0 when dealing with it in native T-SQL

How to check if pytorch is using the GPU?

Create a tensor on the GPU as follows:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

Do not quit, open another terminal and check if the python process is using the GPU using:

$ nvidia-smi

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

Unable to Cast from Parent Class to Child Class

A simple way to downcast in C# is to serialize the parent and then deserialize it into the child.

 var serializedParent = JsonConvert.SerializeObject(parentInstance); 
 Child c  = JsonConvert.DeserializeObject<Child>(serializedParent);

I have a simple console app that casts animal into dog, using the above two lines of code over here

ESRI : Failed to parse source map

Chrome recently added support for source maps in the developer tools. If you go under settings on the chrome developer toolbar you can see the following two options:

Chrome Developer Tools Source Maps

If you disable those two options, and refresh the browser, it should no longer ask for source maps.

These settings can be found here:

Chrome Developer Tools Source Maps

How To Use DateTimePicker In WPF?

There is no out of the box DateTime picker for WPF..

There are however a lot of third party DateTime pickers of course :)

http://www.devcomponents.com/dotnetbar-wpf/WPFDateTimePicker.aspx

http://marlongrech.wordpress.com/2007/09/11/wpf-datepicker/

http://www.codeplex.com/AvalonControlsLib

Just do a quick google to find more!

Onchange open URL via select - jQuery

Here's how i'd do it

<select id="urlSelect" onchange="window.location = jQuery('#urlSelect option:selected').val();">
 <option value="http://www.yadayadayada.com">Great Site</option>
 <option value="http://www.stackoverflow.com">Better Site</option>
</select>

How to disable the ability to select in a DataGridView?

If you don't need to use the information in the selected cell then clearing selection works but if you need to still use the information in the selected cell you can do this to make it appear there is no selection and the back color will still be visible.

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView.SelectedRows)
        {
            dataGridView.RowsDefaultCellStyle.SelectionBackColor = row.DefaultCellStyle.BackColor;
        }
    }

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

In Tensorflow, get the names of all the Tensors in a graph

Previous answers are good, I'd just like to share a utility function I wrote to select Tensors from a graph:

def get_graph_op(graph, and_conds=None, op='and', or_conds=None):
    """Selects nodes' names in the graph if:
    - The name contains all items in and_conds
    - OR/AND depending on op
    - The name contains any item in or_conds

    Condition starting with a "!" are negated.
    Returns all ops if no optional arguments is given.

    Args:
        graph (tf.Graph): The graph containing sought tensors
        and_conds (list(str)), optional): Defaults to None.
            "and" conditions
        op (str, optional): Defaults to 'and'. 
            How to link the and_conds and or_conds:
            with an 'and' or an 'or'
        or_conds (list(str), optional): Defaults to None.
            "or conditions"

    Returns:
        list(str): list of relevant tensor names
    """
    assert op in {'and', 'or'}

    if and_conds is None:
        and_conds = ['']
    if or_conds is None:
        or_conds = ['']

    node_names = [n.name for n in graph.as_graph_def().node]

    ands = {
        n for n in node_names
        if all(
            cond in n if '!' not in cond
            else cond[1:] not in n
            for cond in and_conds
        )}

    ors = {
        n for n in node_names
        if any(
            cond in n if '!' not in cond
            else cond[1:] not in n
            for cond in or_conds
        )}

    if op == 'and':
        return [
            n for n in node_names
            if n in ands.intersection(ors)
        ]
    elif op == 'or':
        return [
            n for n in node_names
            if n in ands.union(ors)
        ]

So if you have a graph with ops:

['model/classifier/dense/kernel',
'model/classifier/dense/kernel/Assign',
'model/classifier/dense/kernel/read',
'model/classifier/dense/bias',
'model/classifier/dense/bias/Assign',
'model/classifier/dense/bias/read',
'model/classifier/dense/MatMul',
'model/classifier/dense/BiasAdd',
'model/classifier/ArgMax/dimension',
'model/classifier/ArgMax']

Then running

get_graph_op(tf.get_default_graph(), ['dense', '!kernel'], 'or', ['Assign'])

returns:

['model/classifier/dense/kernel/Assign',
'model/classifier/dense/bias',
'model/classifier/dense/bias/Assign',
'model/classifier/dense/bias/read',
'model/classifier/dense/MatMul',
'model/classifier/dense/BiasAdd']

What's the best way to build a string of delimited items in Java?

So a couple of things you might do to get the feel that it seems like you're looking for:

1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)

2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.

Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.

To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.

What is JSON and why would I use it?

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Structure



JSON Object diagram

JSON Array diagram

JSON Value diagram

JSON String diagram

JSON Number diagram

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON in JavaScript

JSON (in Javascript) is a string!

People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.

In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.

See Javascript object Vs JSON


When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.


References

How can I start InternetExplorerDriver using Selenium WebDriver

Below steps are worked for me, Hope this will work for you as well,

  1. Open internet explorer.
  2. Navigate to Tools->Option
  3. Navigate to Security Tab
  4. Click on "Reset All Zones to Default level" button
  5. Now for all option like Internet,Intranet,Trusted Sites and Restricted Site enable "Enable Protected" mode check-box.
  6. Set IE zoom level to 100%
  7. then write below code in a java file and run

    System.setProperty("webdriver.ie.driver","path of your IE driver exe\IEDriverServer.exe");
    InternetExplorerDriver driver=new InternetExplorerDriver();
    driver.manage().window().maximize();
    Thread.Sleep(10100);
    driver.get("http://www.Google.com");
    Thread.Sleep(10000);
    

How to create file object from URL object (image)

In order to create a File from a HTTP URL you need to download the contents from that URL:

URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();

The downloaded file will be found at the root of your project: {project}/downloaded.jpg

how to create virtual host on XAMPP

I fixed it using following configuration.

 Listen 85
 <VirtualHost *:85>
           DocumentRoot "C:/xampp/htdocs/LaraBlog/public"
           <Directory "C:/xampp/htdocs/CommunicationApp/public">
           DirectoryIndex index.php
           AllowOverride All
           Order allow,deny
           Allow from all
           </Directory>
 </VirtualHost>

Get parent directory of running script

This is also a possible solution

$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;

Defining a `required` field in Bootstrap

Use 'needs-validation' apart from form-group, it will work.

PostgreSQL query to list all table names?

Try this:

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema='public' AND table_type='BASE TABLE'

this one works!

IOS 7 Navigation Bar text and arrow color

Swift / iOS8

let textAttributes = NSMutableDictionary(capacity:1)
textAttributes.setObject(UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
navigationController?.navigationBar.titleTextAttributes = textAttributes

Token Authentication vs. Cookies

I believe that there is some confusion here. The significant difference between cookie based authentication and what is now possible with HTML5 Web Storage is that browsers are built to send cookie data whenever they are requesting resources from the domain that set them. You can't prevent that without turning off cookies. Browsers do not send data from Web Storage unless code in the page sends it. And pages can only access data that they stored, not data stored by other pages.

So, a user worried about the way that their cookie data might be used by Google or Facebook might turn off cookies. But, they have less reason to turn off Web Storage (until the advertisers figure a way to use that as well).

So, that's the difference between cookie based and token based, the latter uses Web Storage.

How to remove an HTML element using Javascript?

What's happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You're handling the click event on a submit button.

If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:

HTML:

<form  onsubmit="return removeDummy(); ">
    <input type="submit" value="Remove DUMMY"/>
</form>

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

But you don't need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:

HTML:

<input type="button" value="Remove DUMMY" onclick="removeDummy()" />

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}

However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:

HTML:

<input id='btnRemoveDummy' type="button" value="Remove DUMMY"/>

JavaScript:

function removeDummy() {
    var elem = document.getElementById('dummy');
    elem.parentNode.removeChild(elem);
    return false;
}
function pageInit() {
    // Hook up the "remove dummy" button
    var btn = document.getElementById('btnRemoveDummy');
    if (btn.addEventListener) {
        // DOM2 standard
        btn.addEventListener('click', removeDummy, false);
    }
    else if (btn.attachEvent) {
        // IE (IE9 finally supports the above, though)
        btn.attachEvent('onclick', removeDummy);
    }
    else {
        // Really old or non-standard browser, try DOM0
        btn.onclick = removeDummy;
    }
}

...then call pageInit(); from a script tag at the very end of your page body (just before the closing </body> tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn't good for hooking up event handlers (it happens after all images have finally loaded, for instance).

Note that I've had to put in some handling to deal with browser differences. You'll probably want a function for hooking up events so you don't have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It's very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit) to run as soon as the DOM is ready to be manipulated, long before window load fires.

How to delete all files and folders in a directory?

using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

foreach (string filePath in filePaths)

File.Delete(filePath);

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

How do I reference a cell within excel named range?

There are a couple different ways I would do this:

1) Mimic Excel Tables Using with a Named Range

In your example, you named the range A10:A20 "Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5) or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:

=INDEX(Age, ROW()-ROW(Age)+1)

This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.

If the named range is an entire column, the formula simplifies as:

=INDEX(Age, ROW())

2) Use an Excel Table

Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:

=[@[Age]]

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

C: printf a float value

You need to use %2.6f instead of %f in your printf statement

Change table header color using bootstrap

Try This:

table.table tr th{background-color:blue !important; font-color:white !important;}

hope this helps..

How can I show/hide a specific alert with twitter bootstrap?

Add the "collapse" class to the alert div and the alert will be "collapsed" (hidden) by default. You can still call it using "show"

<div class="alert alert-error collapse" role="alert" id="passwordsNoMatchRegister">
  <span>
  <p>Looks like the passwords you entered don't match!</p>
  </span>
</div>

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

How to make Java honor the DNS Caching Timeout?

According to the official oracle java properties, sun.net.inetaddr.ttl is Sun implementation-specific property, which "may not be supported in future releases". "the preferred way is to use the security property" networkaddress.cache.ttl.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

The file is being read as a bunch of strs, but it should be unicodes. Python tries to implicitly convert, but fails. Change:

job_titles = [line.strip() for line in title_file.readlines()]

to explicitly decode the strs to unicode (here assuming UTF-8):

job_titles = [line.decode('utf-8').strip() for line in title_file.readlines()]

It could also be solved by importing the codecs module and using codecs.open rather than the built-in open.

Deep copy an array in Angular 2 + TypeScript

This is Daria's suggestion (see comment on the question) which works starting from TypeScript 2.1 and basically clones each element from the array:

this.clonedArray = theArray.map(e => ({ ... e }));

'mvn' is not recognized as an internal or external command, operable program or batch file

In windows 7, I Got it resolved after adding the environment variables in system level. If you do not have enough permission try to set the %JAVA_HOME% and the %M2_HOME% in System variables instead of User Variables.

How to insert 1000 rows at a time

If you have a DataTable in your application, and this is where the 1000 names are coming from, you can use a table-valued parameter for this.

First, a table type:

CREATE TYPE dbo.Names AS TABLE
(
  Name NVARCHAR(255),
  email VARCHAR(320),
  [password] VARBINARY(32) -- surely you are not storing this as a string!?
);

Then a procedure to use this:

CREATE PROCEDURE dbo.Names_BulkInsert
  @Names dbo.Names READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.RealTable(Name, email, password)
    SELECT Name, email, password
    FROM @Names;
END
GO

Then your C# code can say:

SqlCommand cmd = new SqlCommand("dbo.Names_BulkInsert", connection_object);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter names = cmd.Parameters.AddWithValue("@Names", DataTableName);
names.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();

If you just want to generate 1000 rows with random values:

;WITH x AS
(
  SELECT TOP (1000) n = REPLACE(LEFT(name,32),'_','')
  FROM sys.all_columns ORDER BY NEWID()
)
-- INSERT dbo.sometable(name, email, [password])
SELECT 
  name = LEFT(n,3),
  email = RIGHT(n,5) + '@' + LEFT(n,2) + '.com', 
  [password] = CONVERT(VARBINARY(32), SUBSTRING(n, 1, 32))  
FROM x;

In neither of these cases should you be using while loops or cursors. IMHO.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

Subprocess changing directory

If you need to change directory, run a command and get the std output as well:

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<[email protected]>\nDate:   2020-04-23 09:58:49 +0200\n\n

How to Use Sockets in JavaScript\HTML?

How to Use Sockets in JavaScript/HTML?

There is no facility to use general-purpose sockets in JS or HTML. It would be a security disaster, for one.

There is WebSocket in HTML5. The client side is fairly trivial:

socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
    socket.send('hello');
};
socket.onmessage= function(s) {
    alert('got reply '+s);
};

You will need a specialised socket application on the server-side to take the connections and do something with them; it is not something you would normally be doing from a web server's scripting interface. However it is a relatively simple protocol; my noddy Python SocketServer-based endpoint was only a couple of pages of code.

In any case, it doesn't really exist, yet. Neither the JavaScript-side spec nor the network transport spec are nailed down, and no browsers support it.

You can, however, use Flash where available to provide your script with a fallback until WebSocket is widely available. Gimite's web-socket-js is one free example of such. However you are subject to the same limitations as Flash Sockets then, namely that your server has to be able to spit out a cross-domain policy on request to the socket port, and you will often have difficulties with proxies/firewalls. (Flash sockets are made directly; for someone without direct public IP access who can only get out of the network through an HTTP proxy, they won't work.)

Unless you really need low-latency two-way communication, you are better off sticking with XMLHttpRequest for now.

Python functions call by reference

Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:

  1. Here's why it's not pass-by-value. Because

    def append(list):
        list.append(1)
    
    list = [0]
    reassign(list)
    append(list)
    

returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.

Looks like pass-by-reference then, hu? Nope.

  1. Here's why it's not pass-by-reference. Because

    def reassign(list):
      list = [0, 1]
    
    list = [0]
    reassign(list)
    print list
    

returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].

For more information look here:

If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.

from copy import copy

def append(list):
  list2 = copy(list)
  list2.append(1)
  print list2

list = [0]
append(list)
print list

ITextSharp insert text to an existing pdf

This worked for me and includes using OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    using (Stream outStream = Response.OutputStream)
    {
        Document document = new Document(size);
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

        document.Open();
        try
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(110, 110);
                cb.ShowText("aaa");
            }
            finally
            {
                cb.EndText();
            }

                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 0, 0);

        }
        finally
        {
            document.Close();
            writer.Close();
            reader.Close();
        }
    }

java.lang.IllegalArgumentException: No converter found for return value of type

I was facing same issue for long time then comes to know have to convert object into JSON using Object Mapper and pass it as JSON Object

@RequestMapping(value = "/getTags", method = RequestMethod.GET)
public @ResponseBody String getTags(@RequestParam String tagName) throws
        JsonGenerationException, JsonMappingException, IOException {
    List<Tag> result = new ArrayList<Tag>();
    for (Tag tag : data) {
        if (tag.getTagName().contains(tagName)) {
            result.add(tag);
        }
    }
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(result);
    return json;
}

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

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

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Saving results with headers in Sql Server Management Studio

The same problem exists in Visual Studio, here's how to fix it there:

Go to:

Tools > Options > SQL Server Tools > Transact-SQL Editor > Query Results > Results To Grid

Now click the check box to true: "Include column headers when copying or saving the results"

pandas read_csv and filter columns with usecols

The solution lies in understanding these two keyword arguments:

  • names is only necessary when there is no header row in your file and you want to specify other arguments (such as usecols) using column names rather than integer indices.
  • usecols is supposed to provide a filter before reading the whole DataFrame into memory; if used properly, there should never be a need to delete columns after reading.

So because you have a header row, passing header=0 is sufficient and additionally passing names appears to be confusing pd.read_csv.

Removing names from the second call gives the desired output:

import pandas as pd
from StringIO import StringIO

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

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

Which gives us:

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

Can't accept license agreement Android SDK Platform 24

You can also follow the "official" way. Run "sdkmanager --licenses" within tools/bin folder of Android SDK installation and accept all licenses. Done!

c:\android-sdk\tools\bin>sdkmanager --licenses

For macOS or Linux it's the same command.

Why do we need the "finally" clause in Python?

Perfect example is as below:

try:
    #x = Hello + 20
    x = 10 + 20 
except:
    print 'I am in except block'
    x = 20 + 30
else:
    print 'I am in else block'
    x += 1
finally:
    print 'Finally x = %s' %(x)

Tomcat Server not starting with in 45 seconds

I got the solution for your requirement.

I'm also getting the same error in my eclipse Luna.

Go to Windows option -> select preference.

Than Select General -> Network Connection.

Than select the Active Provider as Manual.

Then restart the tomcat and run. It will work.

Hope it will help you.

Is there any advantage of using map over unordered_map in case of trivial keys?

I've made a test recently which makes 50000 merge&sort. That means if the string keys are the same, merge the byte string. And the final output should be sorted. So this includes a look up for every insertion.

For the map implementation, it takes 200 ms to finish the job. For the unordered_map + map, it takes 70 ms for unordered_map insertion and 80 ms for map insertion. So the hybrid implementation is 50 ms faster.

We should think twice before we use the map. If you only need the data to be sorted in the final result of your program, a hybrid solution may be better.

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Eclipse, regular expression search and replace

For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.

enter image description here

I want to rename

/download.mp4^lecture_id=271

to

/271.mp4

And there can be multiple of these.

Here is how it should be done.

enter image description here

Then hit find/replace button

How to add a button to UINavigationBar?

The answers above are good, but I'd like to flesh them out with a few more tips:

If you want to modify the title of the back button (the arrow-y looking one at the left of the navigation bar) you MUST do it in the PREVIOUS view controller, not the one for which it will display. It's like saying "hey, if you ever push another view controller on top of this one, call the back button "Back" (or whatever) instead of the default."

If you want to hide the back button during a special state, such as while a UIPickerView is displayed, use self.navigationItem.hidesBackButton = YES; and remember to set it back when you leave the special state.

If you want to display one of the special symbolic buttons, use the form initWithBarButtonSystemItem:target:action with a value like UIBarButtonSystemItemAdd

Remember, the meaning of that symbol is up to you, but be careful of the Human Interface Guidelines. Using UIBarButtonSystemItemAdd to mean deleting an item will probably get your application rejected.

Align div with fixed position on the right side

With position fixed, you need to provide values to set where the div will be placed, since it's a fixed position.

Something like....

.test
{
   position:fixed;
   left:100px;
   top:150px;
}

Fixed - Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties

More on position here.

How to get current html page title with javascript

$('title').text();

returns all the title

but if you just want the page title then use

document.title

How can I exclude directories from grep -R?

A simpler way would be to filter your results using "grep -v".

grep -i needle -R * | grep -v node_modules

What uses are there for "placement new"?

Generally, placement new is used to get rid of allocation cost of a 'normal new'.

Another scenario where I used it is a place where I wanted to have access to the pointer to an object that was still to be constructed, to implement a per-document singleton.

Scheduling Python Script to run every hour accurately

For apscheduler < 3.0, see Unknown's answer.

For apscheduler > 3.0

from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()

@sched.scheduled_job('interval', seconds=10)
def timed_job():
    print('This job is run every 10 seconds.')

@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
    print('This job is run every weekday at 10am.')

sched.configure(options_from_ini_file)
sched.start()

Update:

apscheduler documentation.

This for apscheduler-3.3.1 on Python 3.6.2.

"""
Following configurations are set for the scheduler:

 - a MongoDBJobStore named “mongo”
 - an SQLAlchemyJobStore named “default” (using SQLite)
 - a ThreadPoolExecutor named “default”, with a worker count of 20
 - a ProcessPoolExecutor named “processpool”, with a worker count of 5
 - UTC as the scheduler’s timezone
 - coalescing turned off for new jobs by default
 - a default maximum instance limit of 3 for new jobs
"""

from pytz import utc
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor

"""
Method 1:
"""
jobstores = {
    'mongo': {'type': 'mongodb'},
    'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
    'default': {'type': 'threadpool', 'max_workers': 20},
    'processpool': ProcessPoolExecutor(max_workers=5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 3
}

"""
Method 2 (ini format):
"""
gconfig = {
    'apscheduler.jobstores.mongo': {
        'type': 'mongodb'
    },
    'apscheduler.jobstores.default': {
        'type': 'sqlalchemy',
        'url': 'sqlite:///jobs.sqlite'
    },
    'apscheduler.executors.default': {
        'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
        'max_workers': '20'
    },
    'apscheduler.executors.processpool': {
        'type': 'processpool',
        'max_workers': '5'
    },
    'apscheduler.job_defaults.coalesce': 'false',
    'apscheduler.job_defaults.max_instances': '3',
    'apscheduler.timezone': 'UTC',
}

sched_method1 = BlockingScheduler() # uses overrides from Method1
sched_method2 = BlockingScheduler() # uses same overrides from Method2 but in an ini format


@sched_method1.scheduled_job('interval', seconds=10)
def timed_job():
    print('This job is run every 10 seconds.')


@sched_method2.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
    print('This job is run every weekday at 10am.')


sched_method1.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
sched_method1.start()

sched_method2.configure(gconfig=gconfig)
sched_method2.start()

Get index of element as child relative to parent

something like:

$("ul#wizard li").click(function () {
  var index = $("ul#wizard li").index(this);
  alert("index is: " + index)
});

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

How to change the style of a DatePicker in android?

(I'm using React Native; targetSdkVersion 22). I'm trying to change the look of a calendar date picker dialog. The accepted answer didn't work for me, but this did. Hope this snippet helps some of you.

<style name="CalendarDatePickerDialog"  parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#6bf442</item>
    <item name="android:textColorPrimary">#6bf442</item>
</style>

Setting PayPal return URL and making it auto return?

on the checkout page, look for the 'cancel_return' hidden form element:

set the value of the cancel_return form element to the URL you wish to return to:

Counting the number of files in a directory using Java

Unfortunately, I believe that is already the best way (although list() is slightly better than listFiles(), since it doesn't construct File objects).

Button text toggle in jquery

You could also use .toggle() like so:

$(".pushme").toggle(function() {
    $(this).text("DON'T PUSH ME");
}, function() {
    $(this).text("PUSH ME");
});

More info at http://api.jquery.com/toggle-event/.

This way also makes it pretty easy to change the text or add more than just 2 differing states.

How do I get an OAuth 2.0 authentication token in C#

Here is a complete example. Right click on the solution to manage nuget packages and get Newtonsoft and RestSharp:

using Newtonsoft.Json.Linq;
using RestSharp;
using System;


namespace TestAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            String id = "xxx";
            String secret = "xxx";

            var client = new RestClient("https://xxx.xxx.com/services/api/oauth2/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            dynamic resp = JObject.Parse(response.Content);
            String token = resp.access_token;            

            client = new RestClient("https://xxx.xxx.com/services/api/x/users/v1/employees");
            request = new RestRequest(Method.GET);
            request.AddHeader("authorization", "Bearer " + token);
            request.AddHeader("cache-control", "no-cache");
            response = client.Execute(request);
        }        
    }
}

Markdown open a new window link

There is no such feature in markdown, however you can always use HTML inside markdown:

<a href="http://example.com/" target="_blank">example</a>

How can I check if a value is of type Integer?

Here is the function for to check is String is Integer or not ?

public static boolean isStringInteger(String number ){
    try{
        Integer.parseInt(number);
    }catch(Exception e ){
        return false;
    }
    return true;
}

How to install python modules without root access?

You can run easy_install to install python packages in your home directory even without root access. There's a standard way to do this using site.USER_BASE which defaults to something like $HOME/.local or $HOME/Library/Python/2.7/bin and is included by default on the PYTHONPATH

To do this, create a .pydistutils.cfg in your home directory:

cat > $HOME/.pydistutils.cfg <<EOF
[install]
user=1
EOF

Now you can run easy_install without root privileges:

easy_install boto

Alternatively, this also lets you run pip without root access:

pip install boto

This works for me.

Source from Wesley Tanaka's blog : http://wtanaka.com/node/8095

MySQL: How to add one day to datetime field in query

Have a go with this, as this is how I would do it :)

SELECT * 
FROM fab_scheduler
WHERE custid = '123456'
AND CURDATE() = DATE(DATE_ADD(eventdate, INTERVAL 1 DAY))

Oracle date difference to get number of years

I had to implement a year diff function which works similarly to datediff. In that case the real year difference is counted, not the rounded day difference. So if there are two dates separated by one day, the year difference can be 1 (see select datediff(year, '20141231', '20150101')).

If the year diff has to be counted this way then use:

EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)

Just for the log the (almost) complete datediff function:

CREATE OR REPLACE FUNCTION datediff (datepart IN VARCHAR2, date_from IN DATE, date_to IN DATE)
RETURN NUMBER
AS
  diff NUMBER;
BEGIN
  diff :=  CASE datepart
    WHEN 'day'   THEN TRUNC(date_to,'DD') - TRUNC(date_from, 'DD')
    WHEN 'week'  THEN (TRUNC(date_to,'DAY') - TRUNC(date_from, 'DAY')) / 7
    WHEN 'month' THEN MONTHS_BETWEEN(TRUNC(date_to, 'MONTH'), TRUNC(date_from, 'MONTH'))
    WHEN 'year'  THEN EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)
  END;
  RETURN diff;
END;";

:first-child not working as expected

The element cannot directly inherit from <body> tag. You can try to put it in a <dir style="padding-left:0px;"></dir> tag.

Hashmap holding different data types as values for instance Integer, String and Object

Define a class to store your data first

public class YourDataClass {

    private String messageType;
    private Timestamp timestamp;
    private int count;
    private int version;

    // your get/setters
    ...........
}

And then initialize your map:

Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();

jQuery get the rendered height of an element?

I use this to get the height of an element (returns float):

document.getElementById('someDiv').getBoundingClientRect().height

It also works when you use the virtual DOM. I use it in Vue like this:

this.$refs['some-ref'].getBoundingClientRect().height

For a Vue component:

this.$refs['some-ref'].$el.getBoundingClientRect().height

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

Should I use 'has_key()' or 'in' on Python dicts?

There is one example where in actually kills your performance.

If you use in on a O(1) container that only implements __getitem__ and has_key() but not __contains__ you will turn an O(1) search into an O(N) search (as in falls back to a linear search via __getitem__).

Fix is obviously trivial:

def __contains__(self, x):
    return self.has_key(x)

Is there a way to break a list into columns?

If you can support it CSS Grid is probably the cleanest way for making a one-dimensional list into a two column layout with responsive interiors.

_x000D_
_x000D_
ul {_x000D_
  max-width: 400px;_x000D_
  display: grid;_x000D_
  grid-template-columns: 50% 50%;_x000D_
  padding-left: 0;_x000D_
  border: 1px solid blue;_x000D_
}_x000D_
_x000D_
li {_x000D_
  list-style: inside;_x000D_
  border: 1px dashed red;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
  <li>6</li>_x000D_
  <li>7</li>_x000D_
  <li>8</li>_x000D_
  <li>9</li>_x000D_
<ul>
_x000D_
_x000D_
_x000D_

These are the two key lines which will give you your 2 column layout

display: grid;
grid-template-columns: 50% 50%;

Python, Unicode, and the Windows console

Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,

For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).

def pr(s):
    try:
        print(s)
    except UnicodeEncodeError:
        for c in s:
            try:
                print( c, end='')
            except UnicodeEncodeError:
                print( '?', end='')

NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

How do I download and save a file locally on iOS using objective C?

NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.

NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];

You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.

Have a read of these articles:

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide

Can I set variables to undefined or pass undefined as an argument?

The basic difference is that undefined and null represent different concepts.

If only null was available, you would not be able to determine whether null was set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefined fails, thereby allowing you to differentiate between null and undefined values:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

http://en.wikipedia.org/wiki/Undefined_value

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

no suitable HttpMessageConverter found for response type

This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

In Spring 4.0.9, we were able to send this

    JSONObject jsonCredential = new JSONObject();
    jsonCredential.put(APPLICATION_CREDENTIALS, data);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);

In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

The way Convertors work is that if you have it in your classpath, they get registered.

Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

Once we added I could see the converter being registered.

enter image description here

Get int value from enum in C#

Just cast the enum, e.g.

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

long something = (long)StarsInMilkyWay.Wolf424B;

npm install won't install devDependencies

So the way I got around this was in the command where i would normally run npm install or npm ci, i added NODE_ENV=build, and then NODE_ENV=production after the command, so my entire command came out to:

RUN NODE_ENV=build && npm ci && NODE_ENV=production

So far I haven't had any bad reactions, and my development dependencies which are used for building the application all worked / loaded correctly.

I find this to be a better solution than adding an additional command like npm install --only=dev because it takes less time, and enables me to use the npm ci command, which is faster and specifically designed to be run inside CI tools / build scripts. (See npi-ci documentation for more information on it)

Changing all files' extensions in a folder with one command on Windows

Just for people looking to do this in batch files, this code is working:

FOR /R "C:\Users\jonathan\Desktop\test" %%f IN (*.jpg) DO REN "%%f" *.png

In this example all files with .jpg extensions in the C:\Users\jonathan\Desktop\test directory are changed to *.png.

Connect to Oracle DB using sqlplus

it would be something like this

sqlplus -s /nolog  <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!

here

ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>

Adding a module (Specifically pymorph) to Spyder (Python IDE)

This worked for my purpose done within the Spyder Console

conda install -c anaconda pyserial

this format generally works however pymorph returned thus:

conda install -c anaconda pymorph Collecting package metadata (current_repodata.json): ...working... done Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve. Collecting package metadata (repodata.json): ...working... done Solving environment: ...working... failed with initial frozen solve. Retrying with flexible solve.

Note: you may need to restart the kernel to use updated packages.

PackagesNotFoundError: The following packages are not available from current channels:

  • pymorph

Current channels:

To search for alternate channels that may provide the conda package you're looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.

java.net.SocketTimeoutException: Read timed out under Tomcat

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

How to call another components function in angular2

It depends on the relation between your components (parent / child) but the best / generic way to make communicate components is to use a shared service.

See this doc for more details:

That being said, you could use the following to provide an instance of the com1 into com2:

<div>
  <com1 #com1>...</com1>
  <com2 [com1ref]="com1">...</com2>
</div>

In com2, you can use the following:

@Component({
  selector:'com2'
})
export class com2{
  @Input()
  com1ref:com1;

  function2(){
    // i want to call function 1 from com1 here
    this.com1ref.function1();
  }
}

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

Animate visibility modes, GONE and VISIBLE

You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.

how does multiplication differ for NumPy Matrix vs Array classes?

A pertinent quote from PEP 465 - A dedicated infix operator for matrix multiplication , as mentioned by @petr-viktorin, clarifies the problem the OP was getting at:

[...] numpy provides two different types with different __mul__ methods. For numpy.ndarray objects, * performs elementwise multiplication, and matrix multiplication must use a function call (numpy.dot). For numpy.matrix objects, * performs matrix multiplication, and elementwise multiplication requires function syntax. Writing code using numpy.ndarray works fine. Writing code using numpy.matrix also works fine. But trouble begins as soon as we try to integrate these two pieces of code together. Code that expects an ndarray and gets a matrix, or vice-versa, may crash or return incorrect results

The introduction of the @ infix operator should help to unify and simplify python matrix code.

How can I use querySelector on to pick an input element by name?

You can try 'input[name="pwd"]':

function checkForm(){
     var form = document.forms[0];
     var selectElement = form.querySelector('input[name="pwd"]');
     var selectedValue = selectElement.value;
}

take a look a this http://jsfiddle.net/2ZL4G/1/

How to remove ASP.Net MVC Default HTTP Headers?

In Asp.Net Core you can edit the web.config files like so:

<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

You can remove the server header in the Kestrel options:

            .UseKestrel(c =>
            {
                // removes the server header
                c.AddServerHeader = false;
            }) 

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

Get current controller in view

Create base class for all controllers and put here name attribute:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}

In view

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}

Controller example

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Webkit based browsers (like Google Chrome or Safari) has built-in developer tools. In Chrome you can open it Menu->Tools->Developer Tools. The Network tab allows you to see all information about every request and response:

enter image description here

In the bottom of the picture you can see that I've filtered request down to XHR - these are requests made by javascript code.

Tip: log is cleared every time you load a page, at the bottom of the picture, the black dot button will preserve log.

After analyzing requests and responses you can simulate these requests from your web-crawler and extract valuable data. In many cases it will be easier to get your data than parsing HTML, because that data does not contain presentation logic and is formatted to be accessed by javascript code.

Firefox has similar extension, it is called firebug. Some will argue that firebug is even more powerful but I like the simplicity of webkit.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

The question can be read as:

I was in detached-state with HEAD at 23b6772 and typed git reset origin/master (because I wanted to squash). Now I've changed my mind, how do I go back to HEAD being at 23b6772?

The straightforward answer being: git reset 23b6772

But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD and was Googling to see if there were any kind of shorthand.

It turns out there is!

git reset - (or in my case git cherry-pick -)

Which incidentally was the same as cd - to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.

How do I get the file name from a String containing the Absolute file path?

extract file name using java regex *.

public String extractFileName(String fullPathFile){
        try {
            Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
            Matcher regexMatcher = regex.matcher(fullPathFile);
            if (regexMatcher.find()){
                return regexMatcher.group(1);
            }
        } catch (PatternSyntaxException ex) {
            LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
        }
        return fullPathFile;
    }

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

How to dump a table to console?

The table.tostring metehod of metalua is actually very complete. It deals with nested tables, the indentation level is changeable, ... See https://github.com/fab13n/metalua/blob/master/src/lib/metalua/table2.lua

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

How to import large sql file in phpmyadmin

You will have to edit the php.ini file. change the following upload_max_filesize post_max_size to accommodate your file size.

Trying running phpinfo() to see their current value. If you are not at the liberty to change the php.ini file directly try ini_set()

If that is also not an option, you might like to give bigdump a try.

ios Upload Image and Text using HTTP POST

use below code. it will work fine for me.

+(void) sendHttpRequestWithArrayContent:(NSMutableArray *) array 
ToUrl:(NSString *) strUrl withHttpMethod:(NSString *) strMethod 
withBlock:(dictionary)block
{
if (![Utility isConnectionAvailableWithAlert:TRUE])
{
    [Utility showAlertWithTitle:@"" andMessage:@"No internet connection available"];
}


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;

[request setURL:[NSURL URLWithString:strUrl]];
[request setTimeoutInterval:120.0];
[request setHTTPMethod:strMethod];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body=[[NSMutableData alloc]init];

for (NSMutableDictionary *dict in array)
{
    if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSString class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[UIImage class]])
    {
        [body appendData:[self contentDataFormImage:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSMutableDictionary class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else
    {
        NSMutableData *dataBody = [NSMutableData data];
        [dataBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",@"image"] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        [dataBody appendData:[dict valueForKey:[[dict allKeys]objectAtIndex:0]]];

        [body appendData:dataBody];
    }
}

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
 {
     if (!data) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
          [dict setObject:[NSString stringWithFormat:@"%@",SomethingWentWrong] forKey:@"error"];
         block(dict);
         return ;
     }
     NSError *error = nil;
    // NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
     NSLog(@"%@",dict);
     if (!dict) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(dict);
         return ;
     }
     block(dict);

 }];

}
+(NSMutableData*) contentDataFormStringWithValue:(NSString*)strValue 
withKey:(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *data=[[NSMutableData alloc]init];
[data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"%@",strValue] dataUsingEncoding:NSUTF8StringEncoding]];  // title
return data;
}

+(NSMutableData*) contentDataFormImage:(UIImage*)image withKey:
(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData=UIImageJPEGRepresentation(image, 0.40);
[body appendData:imageData];

return body;
}

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

Don't return Strings in your methods but Customer objects it self and let JAXB take care of the de/serialization.

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

Due to PermGen removal some options were removed (like -XX:MaxPermSize), but options -Xms and -Xmx work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC.

Note that if you use any option which was removed in Java 8, you will see a warning upon application start:

$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

html5 audio player - jquery toggle click play/pause?

I'm not sure why, but I needed to use the old skool document.getElementById();

<audio id="player" src="http://audio.micronemez.com:8000/micronemez-radio.ogg"> </audio>
<a id="button" title="button">play sound</a>

and the JS:

$(document).ready(function() {
  var playing = false;

  $('a#button').click(function() {
      $(this).toggleClass("down");

      if (playing == false) {
          document.getElementById('player').play();
          playing = true;
          $(this).text("stop sound");

      } else {
        document.getElementById('player').pause();
        playing = false;
        $(this).text("restart sound");
      }

  });
});

Check out an example: http://jsfiddle.net/HY9ns/1/

Uninstall Node.JS using Linux command line?

I think Manoj Gupta had the best answer from what I'm seeing. However, the remove command doesn't get rid of any configuration folders or files that may be leftover. Use:

sudo apt-get purge --auto-remove nodejs

The purge command should remove the package and then clean up any configuration files. (see this question for more info on the difference between purge and remove). The auto-remove flag will do the same for packages that were installed by NodeJS.

See the accepted answer on this question for a better explanation.

Although don't forget to handle NPM! Josh's answer covers that.

Converting between datetime, Timestamp and datetime64

import numpy as np
import pandas as pd 

def np64toDate(np64):
    return pd.to_datetime(str(np64)).replace(tzinfo=None).to_datetime()

use this function to get pythons native datetime object

How to have multiple CSS transitions on an element?

It's possible to make the multiple transitions set with different values for duration, delay and timing function. To split different transitions use ,

button{
  transition: background 1s ease-in-out 2s, width 2s linear;
  -webkit-transition: background 1s ease-in-out 2s, width 2s linear; /* Safari */
}

Reference: https://kolosek.com/css-transition/

Comparison of DES, Triple DES, AES, blowfish encryption for data

Although TripleDESCryptoServiceProvider is a safe and good method but it's too slow. If you want to refer to MSDN you will get that advise you to use AES rather TripleDES. Please check below link: http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx you will see this attention in the remark section:

Note A newer symmetric encryption algorithm, Advanced Encryption Standard (AES), is available. Consider using the AesCryptoServiceProvider class instead of the TripleDESCryptoServiceProvider class. Use TripleDESCryptoServiceProvider only for compatibility with legacy applications and data.

Good luck

Append Char To String in C?

Create a new string (string + char)

#include <stdio.h>    
#include <stdlib.h>

#define ERR_MESSAGE__NO_MEM "Not enough memory!"
#define allocator(element, type) _allocator(element, sizeof(type))

/** Allocator function (safe alloc) */
void *_allocator(size_t element, size_t typeSize)
{
    void *ptr = NULL;
    /* check alloc */
    if( (ptr = calloc(element, typeSize)) == NULL)
    {printf(ERR_MESSAGE__NO_MEM); exit(1);}
    /* return pointer */
    return ptr;
}

/** Append function (safe mode) */
char *append(const char *input, const char c)
{
    char *newString, *ptr;

    /* alloc */
    newString = allocator((strlen(input) + 2), char);
    /* Copy old string in new (with pointer) */
    ptr = newString;
    for(; *input; input++) {*ptr = *input; ptr++;}
    /* Copy char at end */
    *ptr = c;
    /* return new string (for dealloc use free().) */
    return newString;
}

/** Program main */
int main (int argc, const char *argv[])
{
    char *input = "Ciao Mondo"; // i am italian :), this is "Hello World"
    char c = '!';
    char *newString;

    newString = append(input, c);
    printf("%s\n",newString);
    /* dealloc */
    free(newString);
    newString = NULL;

    exit(0);
}

              0   1   2   3    4    5   6   7   8   9  10   11
newString is [C] [i] [a] [o] [\32] [M] [o] [n] [d] [o] [!] [\0]

Don't alter the array size ([len +1], etc.) without know its exact size, it may damage other data. alloc an array with the new size and put the old data inside instead, remember that, for a char array, the last value must be \0; calloc() sets all values to \0, which is excellent for char arrays.

I hope this helps.

extract digits in a simple way from a python string

Without using regex, you can just do:

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))

Result:

>>> get_num(x)
120
>>> get_num(y)
90
>>> get_num(banana)
200
>>> get_num(orange)
300

EDIT :

Answering the follow up question.

If we know that the only period in a given string is the decimal point, extracting a float is quite easy:

def get_num(x):
    return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))

Result:

>>> get_num('dfgd 45.678fjfjf')
45.678

Is there a way to create interfaces in ES6 / Node 4?

there are packages that can simulate interfaces .

you can use es6-interface

error 1265. Data truncated for column when trying to load data from txt file

I had this issue when trying to convert an existing varchar column to enum. For me the issue was that there were existing values for that column that were not part of the enum's list of accepted values. So if your enum will only allow values, say ('dog', 'cat') but there is a row with bird in your table, the MODIFY COLUMN will fail with this error.

Is "else if" faster than "switch() case"?

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

how to open a page in new tab on button click in asp.net?

A simple solution:

<a href="https://www.google.com" target="_blank">
    <button type="button">Open new tab</button>
</a>

How to make responsive table

Basically

A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }
}

HTML

<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

Is this the proper way to do boolean test in SQL?

A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:

select * from users where active = 1 /* All Active Users */

or

select * from users where active = 0 /* All Inactive Users */

How to scp in Python?

Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

When is a github repository not empty, like .gitignore and license

Use pull --allow-unrelated-histories and push --force-with-lease

Use commands

git init
git add .
git commit -m "initial commit"
git remote add origin https://github.com/...
git pull origin master --allow-unrelated-histories
git push --force-with-lease

How to determine an object's class?

if (obj instanceof C) {
//your code
}

What is the use of <<<EOD in PHP?

there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings

you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.

nowdoc strings will not expand variables just like single quotes.

ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Laravel Check If Related Model Exists

After Php 7.1, The accepted answer won't work for all types of relationships.

Because depending of type the relationship, Eloquent will return a Collection, a Model or Null. And in Php 7.1 count(null) will throw an error.

So, to check if the relation exist you can use:

For relationships single: For example hasOne and belongsTo

if(!is_null($model->relation)) {
   ....
}

For relationships multiple: For Example: hasMany and belongsToMany

if ($model->relation->isNotEmpty()) {
   ....
}

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

Windows ignores JAVA_HOME: how to set JDK as default?

For my Case in 'Path' variable there was a parameter added like 'C:\ProgramData\Oracle\Java\javapath;'. This location was having java.exe, javaw.exe and javaws.exe from java 8 which is newly installed via jdk.exe from Oracle.

I've removed this text from Path where my Path already having %JAVA_HOME%\bin with it.

Now, the variable 'JAVA_HOME' is controlling my Java version which is I wanted.

Converting Symbols, Accent Letters to English Alphabet

I'm late to the party, but after facing this issue today, I found this answer to be very good:

String asciiName = Normalizer.normalize(unicodeName, Normalizer.Form.NFD)
    .replaceAll("[^\\p{ASCII}]", "");

Reference: https://stackoverflow.com/a/16283863

What does git push -u mean?

When you push a new branch the first time use: >git push -u origin

After that, you can just type a shorter command: >git push

The first-time -u option created a persistent upstream tracking branch with your local branch.

Append integer to beginning of list in Python

New lists can be made by simply adding lists together.

list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

How to get the CPU Usage in C#?

public int GetCpuUsage()
{
    var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
    cpuCounter.NextValue();
    System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
    return (int)cpuCounter.NextValue();
}

Original information in this link https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/

Automatically set appsettings.json for dev and release environments in asp.net core?

You can add the configuration name as the ASPNETCORE_ENVIRONMENT in the launchSettings.json as below

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:58446/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "environmentVariables": {
        ASPNETCORE_ENVIRONMENT": "$(Configuration)"
      }
    }
  }

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

Installing a specific version of angular with angular cli

You can just have package.json with specific version and do npm install and it will install that version. Also you dont need to depend on angular-cli to develop your project.

What is the equivalent of "!=" in Excel VBA?

Because the inequality operator in VBA is <>

If strTest <> "" Then
    .....

the operator != is used in C#, C++.

Minimal web server using netcat

If you're using Apline Linux, the BusyBox netcat is slightly different:

while true; do nc -l -p 8080 -e sh -c 'echo -e "HTTP/1.1 200 OK\n\n$(date)"'; done

And another way using printf:

while true; do nc -l -p 8080 -e sh -c "printf 'HTTP/1.1 200 OK\n\n%s' \"$(date)\""; done

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

How to fix "Incorrect string value" errors?

In my case, Incorrect string value: '\xCC\x88'..., the problem was that an o-umlaut was in its decomposed state. This question-and-answer helped me understand the difference between and ö. In PHP, the fix for me was to use PHP's Normalizer library. E.g., Normalizer::normalize('o¨', Normalizer::FORM_C).

What's the difference between next() and nextLine() methods from Scanner class?

I also got a problem concerning a delimiter. the question was all about inputs of

  1. enter your name.
  2. enter your age.
  3. enter your email.
  4. enter your address.

The problem

  1. I finished successfully with name, age, and email.
  2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

The solution

I used the delimiter for my scanner and went out successful.

Example

 public static void main (String args[]){
     //Initialize the Scanner this way so that it delimits input using a new line character.
    Scanner s = new Scanner(System.in).useDelimiter("\n");
    System.out.println("Enter Your Name: ");
    String name = s.next();
    System.out.println("Enter Your Age: ");
    int age = s.nextInt();
    System.out.println("Enter Your E-mail: ");
    String email = s.next();
    System.out.println("Enter Your Address: ");
    String address = s.next();

    System.out.println("Name: "+name);
    System.out.println("Age: "+age);
    System.out.println("E-mail: "+email);
    System.out.println("Address: "+address);
}

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

These are the steps I took (I'm on Linux).

  • Switched to Software rendering (works but is too slow)
  • Tried running on commanline and an error displayed.
  • Forced emulator to use the system graphic drivers.

First, as @jlars62 suggested, I tried using Switching the Graphics to "Software" and this DID work. However, the performance is far to slow so I dug a little deeper.

Then I tried running the device from the console, as @CaptainCrunch suggestion. (My device was created in Android Studio; emulator in the Sdk may be in a different place on your system)

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23

For me this produced the following error:

libGL error: unable to load driver: i965_dri.so 
libGL error: driver
pointer missing libGL error: failed to load driver: i965 
...

Which I tracked down (on ArchLinux) to mean it's using the wrong graphic drivers (Android Sdk comes with it's own). You can force the system ones on the commandline with -use-system-libs:

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23 -use-system-libs

To force Android Studio to do this you can intercept the call to "emulator" like so (See Mike42) :

$ cd ~/Android/Sdk/tools/
$ mv emulator emulator.0
$ touch emulator
$ chmod +x emulator

In the new emulator file add this:

#!/bin/sh
set -ex
$0.0 $@ -use-system-libs

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

How to import a single table in to mysql database using command line

To import a table into database, if table is already exist then add this line in your sql file DROP TABLE IF EXIST 'table_name' and run command mysql -u username -p database_name < import_sql_file.sql. Please verify the sql file path before execute the command.

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

How to change Screen buffer size in Windows Command Prompt from batch script

mode con lines=32766

sets the buffer, but also increases the window height to full screen, which is ugly.

You can change the settings directly in the registry :

:: escape the environment variable in the key name
set mySysRoot=%%SystemRoot%%

:: 655294544 equals 9999 lines in the GUI
reg.exe add "HKCU\Console\%mySysRoot%_system32_cmd.exe" /v ScreenBufferSize /t REG_DWORD /d 655294544 /f

:: We also need to change the Window Height, 3276880 = 50 lines
reg.exe add "HKCU\Console\%mySysRoot%_system32_cmd.exe" /v WindowSize /t REG_DWORD /d 3276880 /f

The next cmd.exe you start has the increase buffer.

So this doesn't work for the cmd.exe you are already in, but just use this in a pre-batch.cmd which than calls your main script.

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv