Programs & Examples On #Multiple browsers

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

On npm install: Unhandled rejection Error: EACCES: permission denied

sudo npm cache clean --force --unsafe-perm

and then npm i goes normally

Associative arrays in Shell scripts

Adding another option, if jq is available:

export NAMES="{
  \"Mary\":\"100\",
  \"John\":\"200\",
  \"Mary\":\"50\",
  \"John\":\"300\",
  \"Paul\":\"100\",
  \"Paul\":\"400\",
  \"David\":\"100\"
}"
export NAME=David
echo $NAMES | jq --arg v "$NAME" '.[$v]' | tr -d '"' 

AJAX POST and Plus Sign ( + ) -- How to Encode?

my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:

my solution (not the better way, but it works):

javascript:

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
  text = text.toString().replace(busca,reemplaza);return text;
}


function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas   
return code;
}

function to save:

function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();    
var result = null;
$.ajax({
datatype : "html",
data: myData,  
url: url,
success : function(result) {
    alert(result); // result ok                     
},
}); 
} // end function

function in php:

<?php
function save($pid,$code){
    $code= preg_replace("[\{1\}]","|",$code);
    $code= preg_replace("[\{0\}]","+",$code);
    mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>

How can I get a resource "Folder" from inside my jar File?

The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.

  private Path getFolderPath() throws URISyntaxException, IOException {
    URI uri = getClass().getClassLoader().getResource("folder").toURI();
    if ("jar".equals(uri.getScheme())) {
      FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
      return fileSystem.getPath("path/to/folder/inside/jar");
    } else {
      return Paths.get(uri);
    }
  }

Requires java 7+.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

I had this error when I tried to import (in MysqlWorkbench) from a PhpAdminMySQL export. After verifying I had disabled the unique keys and foreign keys with:

SET unique_checks=0;
SET foreign_key_checks = 0;

I still get the same error (MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint). The error occurred on this create statement.

DROP TABLE IF EXISTS `f1_pool`;
CREATE TABLE `f1_pool` (
 `id` int(11) NOT NULL,
 `name` varchar(45) NOT NULL,
 `description` varchar(45) DEFAULT NULL COMMENT 'Optional',
 `ownerId` int(11) NOT NULL,
 `lastmodified` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

No foreign key or unique index, so what is wrong here? Finally (after 90 minutes puzzling) I decided to restart MySQL and do the import again with one modification: I dropped all tables before doing the import. And there was no error, all functioned, tables and views restored. So my advice, if all looks ok, first try to restart MySQL!

How to print a list of symbols exported from a dynamic library

Use nm -a your.dylib

It will print all the symbols including globals

Chaining multiple filter() in Django, is this a bug?

From Django docs :

To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

  • It is clearly said that multiple conditions in a single filter() are applied simultaneously. That means that doing :
objs = Mymodel.objects.filter(a=True, b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False.

  • Successive filter(), in some case, will provide the same result. Doing :
objs = Mymodel.objects.filter(a=True).filter(b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False too. Since you obtain "first" a queryset with records which have a=True and then it's restricted to those who have b=False at the same time.

  • The difference in chaining filter() comes when there are multi-valued relations, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

Which means that it applies the successives filter() on the target model directly, not on previous filter()

If I take the example from the docs :

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

remember that it's the model Blog that is filtered, not the Entry. So it will treat the 2 filter() independently.

It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')

THIS ANSWER goes even further in the explanation. And the original question is similar.

Get year, month or day from numpy datetime64

As datetime is not stable in numpy I would use pandas for this:

In [52]: import pandas as pd

In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])

In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)

Pandas uses numpy datetime internally, but seems to avoid the shortages, that numpy has up to now.

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

cannot call member function without object

just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

I want my android application to be only run in portrait mode?

There are two ways,

  1. Add android:screenOrientation="portrait" for each Activity in Manifest File
  2. Add this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); in each java file.

Best font for coding

Funny, I was just researching this yesterday!

I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Android – Listen For Incoming SMS Messages

The accepted answer is correct and works on older versions of Android where Android OS asks for permissions at the app install, However on newer versions Android it doesn't work straight away because newer Android OS asks for permissions during runtime when the app requires that feature. Therefore in order to receive SMS on newer versions of Android using technique mentioned in accepted answer programmer must also implement code that will check and ask for permissions from user during runtime. In this case permissions checking functionality/code can be implemented in onCreate() of app's first activity. Just copy and paste following two methods in your first activity and call checkForSmsReceivePermissions() method at the end of onCreate().

    void checkForSmsReceivePermissions(){
    // Check if App already has permissions for receiving SMS
    if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.RECEIVE_SMS") == PackageManager.PERMISSION_GRANTED) {
        // App has permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Allowed");
    } else {
        // App don't have permissions to listen incoming SMS messages
        Log.d("adnan", "checkForSmsReceivePermissions: Denied");

        // Request permissions from user 
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECEIVE_SMS}, 43391);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 43391){
        if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.d("adnan", "Sms Receive Permissions granted");
        } else {
            Log.d("adnan", "Sms Receive Permissions denied");
        }
    }
}

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

What is the HTML tabindex attribute?

Controlling the order of tabbing (pressing the tab key to move focus) within the page.

Reference: http://www.w3.org/TR/html401/interact/forms.html#h-17.11.1

How to delete images from a private docker registry?

The current v2 registry now supports deleting via DELETE /v2/<name>/manifests/<reference>

See: https://github.com/docker/distribution/blob/master/docs/spec/api.md#deleting-an-image

Working usage: https://github.com/byrnedo/docker-reg-tool

Edit: The manifest <reference> above can be retrieved from requesting to

GET /v2/<name>/manifests/<tag>

and checking the Docker-Content-Digest header in the response.

Edit 2: You may have to run your registry with the following env set:

REGISTRY_STORAGE_DELETE_ENABLED="true"

Edit3: You may have to run garbage collection to free this disk space: https://docs.docker.com/registry/garbage-collection/

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Changing default startup directory for command prompt in Windows 7

Use Windows Terminal and configure a starting directory. Partial settings.json:

{
    // Make changes here to the cmd.exe profile.
    "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
    "name": "Command Prompt",
    "commandline": "cmd.exe",
    "hidden": false,
    "startingDirectory": "C:\\DEV"
},

How to get the date from the DatePicker widget in Android?

U can also use te Calendar.GregorianCalendar java class

    GregorianCalendar calendarBeg=new GregorianCalendar(datePicker.getYear(),
        datePicker.getMonth(),datePicker.getDayOfMonth());
    Date begin=calendarBeg.getTime();

Offset a background image from the right using CSS

background-position: calc(100% - 8px);

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Handle ModelState Validation in ASP.NET Web API

You can also throw exceptions as documented here: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

Note, to do what that article suggests, remember to include System.Net.Http

How do you append rows to a table using jQuery?

Try:

$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");

And in the partial, you should have:

<td>row1</td>
<td>row2</td>

Set focus to field in dynamically loaded DIV

As Omu pointed out, you must set the focus in a document ready function. jQuery provides it for you. And do select on an id. For example, if you have a login page:

$(function() { $("#login-user-name").focus(); }); // jQuery rocks!

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.

<mvc:annotation-driven> 

registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

How to increase buffer size in Oracle SQL Developer to view all records?

After you fetch the first 50 rows in the query windows, simply click on any column to get focus on the query window, then once selected do ctrl + end key

This will load the full result set (all rows)

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

Grunt watch error - Waiting...Fatal error: watch ENOSPC

After doing some research found the solution. Run the below command.

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

Simple way to convert datarow array to datatable

DataTable dataTable = new DataTable();
dataTable = OldDataTable.Tables[0].Clone();
foreach(DataRow dr in RowData.Tables[0].Rows)
{
 DataRow AddNewRow = dataTable.AddNewRow();
 AddNewRow.ItemArray = dr.ItemArray;
 dataTable.Rows.Add(AddNewRow);
}

How do I embed PHP code in JavaScript?

Yes, you can, provided your JavaScript code is embedded into a PHP file.

How to see the proxy settings on windows?

You can use a tool called: NETSH

To view your system proxy information via command line:

netsh.exe winhttp show proxy

Another way to view it is to open IE, then click on the "gear" icon, then Internet options -> Connections tab -> click on LAN settings

Change color and appearance of drop down arrow

Unless you plan on creating your own drop down list (and not using a standard library drop down list), you are stuck. The DDL control's look is going to be based upon the system you are running and/or the browser that is rendering the output.

How to output a multiline string in Bash?

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

Is it possible to validate the size and type of input=file in html5

I could do this (demo):

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
    <form >
        <input type="file" id="f" data-max-size="32154" />
        <input type="submit" />
    </form>
<script>
$(function(){
    $('form').submit(function(){
        var isOk = true;
        $('input[type=file][data-max-size]').each(function(){
            if(typeof this.files[0] !== 'undefined'){
                var maxSize = parseInt($(this).attr('max-size'),10),
                size = this.files[0].size;
                isOk = maxSize > size;
                return isOk;
            }
        });
        return isOk;
    });
});
</script>
</body>
</html>

Constant pointer vs Pointer to constant

Please refer the following link for better understanding about the difference between Const pointer and Pointer on a constant value.

constant pointer vs pointer on a constant value

Can I run HTML files directly from GitHub, instead of just viewing their source?

You might want to use raw.githack.com. It supports GitHub, Bitbucket, Gitlab and GitHub gists.

GitHub

Before:

https://raw.githubusercontent.com/[user]/[repository]/[branch]/[filename.ext]

In your case .html extension

After:

Development (throttled)

https://raw.githack.com/[user]/[repository]/[branch]/[filename.ext]

Production (CDN)

https://rawcdn.githack.com/[user]/[repository]/[branch]/[filename.ext]

In your case .html extension


raw.githack.com also supports other services:

Bitbucket

Before:

https://bitbucket.org/[user]/[repository]/raw/[branch]/[filename.ext]

After:

Development (throttled)

https://bb.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

Production (CDN)

https://bbcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

GitLab

Before:

https://gitlab.com/[user]/[repository]/raw/[branch]/[filename.ext]

After:

Development (throttled)

https://gl.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

Production (CDN)

https://glcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

GitHub gists

Before:

https://gist.githubusercontent.com/[user]/[gist]/raw/[revision]/[filename.ext]

After:

Development (throttled)

https://gist.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]

Production (CDN)

https://gistcdn.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]


Update: rawgit was discontinued

How to use Git?

Have a look at git for designers for great one page article/high level intro to the topic. (That link is broken: Here is a link to another Git for Designers )

I would start at http://git-scm.com/documentation, there are documents and great video presentations for non-software-developer/cs users. Git for beginners have some basic stuff.

How to set maximum fullscreen in vmware?

From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Error: [$injector:unpr] Unknown provider: $routeProvider

In angular 1.4 +, in addition to adding the dependency

angular.module('myApp', ['ngRoute'])

,we also need to reference the separate angular-route.js file

<script src="angular.js">
<script src="angular-route.js">

see https://docs.angularjs.org/api/ngRoute

jQuery: Check if div with certain class name exists

To test for div elements explicitly:

if( $('div.mydivclass').length ){...}

Print ArrayList

public void printList(ArrayList<Address> list){
    for(Address elem : list){
        System.out.println(elem+"  ");
    }
}

How to squash all git commits into one?

As of git 1.6.2, you can use git rebase --root -i.

For each commit except the first, change pick to squash.

jQuery deferreds and promises - .then() vs .done()

There is a very simple mental mapping in response that was a bit hard to find in the other answers:

Using number as "index" (JSON)

JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.

The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

Android: Remove all the previous activities from the back stack

One possible solution what I can suggest you is to add android:launchMode="singleTop" in the manifest for my ProfileActivity. and when log out is clicked u can logoff starting again you LoginActivity. on logout u can call this.

Intent in = new Intent(Profile.this,Login.class);
                in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in);
                finish();

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

How do I create a copy of an object in PHP?

According to previous comment, if you have another object as a member variable, do following:

class MyClass {
  private $someObject;

  public function __construct() {
    $this->someObject = new SomeClass();
  }

  public function __clone() {
    $this->someObject = clone $this->someObject;
  }

}

Now you can do cloning:

$bar = new MyClass();
$foo = clone $bar;

How do android screen coordinates work?

For Android API level 13 and you need to use this:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x; 
int maxY = size.y;

Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.

The 'getWidth()' for screen size is deprecated since API 13

Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.

          int maxX=getwidht();
          int maxY=getHeight();

as simple as that.

Remove all the elements that occur in one list from another

Sets versus list comprehension benchmark on Python 3.8

(adding up to Moinuddin Quadri's benchmarks)

tldr: Use Arkku's set solution, it's even faster than promised in comparison!

Checking existing files against a list

In my example I found it to be 40 times (!) faster to use Arkku's set solution than the pythonic list comprehension for a real world application of checking existing filenames against a list.

List comprehension:

%%time
import glob
existing = [int(os.path.basename(x).split(".")[0]) for x in glob.glob("*.txt")]
wanted = list(range(1, 100000))
[i for i in wanted if i not in existing]

Wall time: 28.2 s

Sets

%%time
import glob
existing = [int(os.path.basename(x).split(".")[0]) for x in glob.glob("*.txt")]
wanted = list(range(1, 100000))
set(wanted) - set(existing)

Wall time: 689 ms

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android

Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android".

refer https://developer.android.com/guide/topics/manifest/manifest-element#nspace

How to get $HOME directory of different user in bash script?

If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}

Here's a usage example:

da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"

JQuery: How to get selected radio button value?

To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.

$('input[name=radioName]:checked', '#myForm').val()

OR by only

$('form input[type=radio]:checked').val();

Substring in excel

I believe we can start from basic to achieve desired result.

For example, I had a situation to extract data after "/". The given excel field had a value of 2rko6xyda14gdl7/VEERABABU%20MATCHA%20IN131621.jpg . I simply wanted to extract the text from "I5" cell after slash symbol. So firstly I want to find where "/" symbol is (FIND("/",I5). This gives me the position of "/". Then I should know the length of text, which i can get by LEN(I5).so total length minus the position of "/" . which is LEN(I5)-(FIND("/",I5)) . This will first find the "/" position and then get me the total text that needs to be extracted. The RIGHT function is RIGHT(I5,12) will simply extract all the values of last 12 digits starting from right most character. So I will replace the above function "LEN(I5)-(FIND("/",I5))" for 12 number in the RIGHT function to get me dynamically the number of characters I need to extract in any given cell and my solution is presented as given below

The approach was

=RIGHT(I5,LEN(I5)-(FIND("/",I5))) will give me out as VEERABABU%20MATCHA%20IN131621.jpg . I think I am clear.

Rotating a point about another point (2D)

float s = sin(angle); // angle is in radians
float c = cos(angle); // angle is in radians

For clockwise rotation :

float xnew = p.x * c + p.y * s;
float ynew = -p.x * s + p.y * c;

For counter clockwise rotation :

float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;

How do I pass a method as a parameter in Python

Yes; functions (and methods) are first class objects in Python. The following works:

def foo(f):
    print "Running parameter f()."
    f()

def bar():
    print "In bar()."

foo(bar)

Outputs:

Running parameter f().
In bar().

These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.

Accidentally committed .idea directory files into git

You can remove it from the repo and commit the change.

git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"

After that, you can push it to the remote and every checkout/clone after that will be ok.

Recover unsaved SQL query scripts

You can find files here, when you closed SSMS window accidentally

C:\Windows\System32\SQL Server Management Studio\Backup Files\Solution1

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

Can vue-router open a link in a new tab?

I think that you can do something like this:

let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');

It worked for me.

MySQL Error 1093 - Can't specify target table for update in FROM clause

This is what I did for updating a Priority column value by 1 if it is >=1 in a table and in its WHERE clause using a subquery on same table to make sure that at least one row contains Priority=1 (because that was the condition to be checked while performing update) :


UPDATE My_Table
SET Priority=Priority + 1
WHERE Priority >= 1
AND (SELECT TRUE FROM (SELECT * FROM My_Table WHERE Priority=1 LIMIT 1) as t);

I know it's a bit ugly but it does works fine.

Difference between a User and a Login in SQL Server

I think this is a very useful question with good answer. Just to add my two cents from the MSDN Create a Login page:

A login is a security principal, or an entity that can be authenticated by a secure system. Users need a login to connect to SQL Server. You can create a login based on a Windows principal (such as a domain user or a Windows domain group) or you can create a login that is not based on a Windows principal (such as an SQL Server login).

Note:
To use SQL Server Authentication, the Database Engine must use mixed mode authentication. For more information, see Choose an Authentication Mode.

As a security principal, permissions can be granted to logins. The scope of a login is the whole Database Engine. To connect to a specific database on the instance of SQL Server, a login must be mapped to a database user. Permissions inside the database are granted and denied to the database user, not the login. Permissions that have the scope of the whole instance of SQL Server (for example, the CREATE ENDPOINT permission) can be granted to a login.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Get all photos from Instagram which have a specific hashtag with PHP

Since Nov 17, 2015 you have to authenticate users to make any (even such as "get some pictures who have specific hashtag") requests. See the Instagram Platform Changelog:

Apps created on or after Nov 17, 2015: All API endpoints require a valid access_token. Apps created before Nov 17, 2015: Unaffected by new API behavior until June 1, 2016.

this makes now all answers given here before June 1, 2016 no longer useful.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Combining two sorted lists in Python

People seem to be over complicating this.. Just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..or shorter (and without modifying l1):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.

If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime objects)

Using the timeit.Timer().repeat() (which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2) is substantially quicker:

merge_sorted_lists took..

[9.7439379692077637, 9.8844599723815918, 9.552299976348877]

sorted(l1+l2) took..

[2.860386848449707, 2.7589840888977051, 2.7682540416717529]

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Using select2 jquery library:

$('#selector').val(arrayOfValues).trigger('change')

How do you make an anchor link non-clickable or disabled?

Write this a single line of jQuery Code

$('.hyperlink').css('pointer-events','none');

if you want to write in css file

.hyperlink{
    pointer-events: none;
}

stale element reference: element is not attached to the page document

According to @Abhishek Singh's you need to understand the problem:

What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure

and you can not refer to it anymore (imagine what element's ID has changed).

Follow the code:

class TogglingPage {
  @FindBy(...)
  private WebElement btnTurnOff;

  @FindBy(...)
  private WebElement btnTurnOn;

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();          // when clicked, button should swap into btnTurnOn
    this.btnTurnOn.isDisplayed();
    this.btnTurnOn.click();           // when clicked, button should swap into btnTurnOff
    this.btnTurnOff.isDisplayed();    // throws an exception
    return new TogglingPage();
  }
}

Now, let us wonder why?

  1. btnTurnOff was found by a driver - ok
  2. btnTurnOff was replaced by btnTurnOn - ok
  3. btnTurnOn was found by a driver. - ok
  4. btnTurnOn was replaced by btnTurnOff - ok
  5. we call this.btnTurnOff.isDisplayed(); on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button.

Possible fix:

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();

    TogglingPage newPage = new TogglingPage();
    newPage.btnTurnOn.isDisplayed();
    newPage.btnTurnOn.click();

    TogglingPage newerPage = new TogglingPage();
    newerPage.btnTurnOff.isDisplayed();    // ok
    return newerPage;
  }

Ignore python multiple return value

If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.

# Example 1: a is 1 and b is [2, 3]

a, *b = [1, 2, 3]

# Example 2: a is 1, b is [2, 3], and c is 4

a, *b, c = [1, 2, 3, 4]

# Example 3: b is [1, 2] and c is 3

*b, c = [1, 2, 3]       

# Example 4: a is 1 and b is []

a, *b = [1]

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

Re-doing a reverted merge in Git

I just found this post when facing the same problem. I find above wayyy to scary to do reset hards etc. I'll end up deleting something I don't want to, and won't be able to get it back.

Instead I checked out the commit I wanted the branch to go back to e.g. git checkout 123466t7632723. Then converted to a branch git checkout my-new-branch. I then deleted the branch I didn't want any more. Of course this will only work if you are able to throw away the branch you messed up.

Allowed memory size of X bytes exhausted

PHP's config can be set in multiple places:

  1. master system php.ini (usually in /etc somewhere)
  2. somewhere in Apache's configuration (httpd.conf or a per-site .conf file, via php_value)
  3. CLI & CGI can have a different php.ini (use the command php -i | grep memory_limit to check the CLI conf)
  4. local .htaccess files (also php_value)
  5. in-script (via ini_set())

In PHPinfo's output, the "Master" value is the compiled-in default value, and the "Local" value is what's actually in effect. It can be either unchanged from the default, or overridden in any of the above locations.

Also note that PHP generally has different .ini files for command-line and webserver-based operation. Checking phpinfo() from the command line will report different values than if you'd run it in a web-based script.

How to enter special characters like "&" in oracle database?

You can either use the backslash character to escape a single character or symbol

'Java_22 \& Oracle_14'

or braces to escape a string of characters or symbols

'{Java_22 & Oracle_14}'

How to add an onchange event to a select box via javascript?

replace:

transport_select.onChange = function(){toggleSelect(transport_select_id);};

with:

transport_select.onchange = function(){toggleSelect(transport_select_id);};

on'C'hange >> on'c'hange


You can use addEventListener too.

X close button only using css

_x000D_
_x000D_
<div style="width: 10px; height: 10px; position: relative; display: flex; justify-content: center;">
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(45deg); border-radius: 2px;"></div>
   <div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(-45deg); border-radius: 2px;"></div>
</div>
_x000D_
_x000D_
_x000D_

How to render a DateTime in a specific format in ASP.NET MVC 3?

Simple formatted output inside of the model

@String.Format("{0:d}", model.CreatedOn)

or in the foreach loop

@String.Format("{0:d}", item.CreatedOn)

How do I determine file encoding in OS X?

Just use:

file -I <filename>

That's it.

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

How to disassemble a memory range with GDB?

This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump:

objdump -d program

This should give you its dissassembly. You can add -S if you want it source-annotated.

What is the mouse down selector in CSS?

I think you mean the active state

 button:active{
  //some styling
 }

These are all the possible pseudo states a link can have in CSS:

a:link {color:#FF0000;}    /* unvisited link, same as regular 'a' */
a:hover {color:#FF00FF;}   /* mouse over link */
a:focus {color:#0000FF;}   /* link has focus */
a:active {color:#0000FF;}  /* selected link */
a:visited {color:#00FF00;} /* visited link */

See also: http://www.w3.org/TR/selectors/#the-user-action-pseudo-classes-hover-act

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

How to run jenkins as a different user

ISSUE 1:

Started by user anonymous

That does not mean that Jenkins started as an anonymous user.

It just means that the person who started the build was not logged in. If you enable Jenkins security, you can create usernames for people and when they log in, the

"Started by anonymous" 

will change to

"Started by < username >". 

Note: You do not have to enable security in order to run jenkins or to clone correctly.

If you want to enable security and create users, you should see the options at Manage Jenkins > Configure System.


ISSUE 2:

The "can't clone" error is a different issue altogether. It has nothing to do with you logging in to jenkins or enabling security. It just means that Jenkins does not have the credentials to clone from your git SCM.

Check out the Jenkins Git Plugin to see how to set up Jenkins to work with your git repository.

Hope that helps.

Create XML in Javascript

Simply use

var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);

It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.

How to add white spaces in HTML paragraph

You can try it by adding &nbsp;

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

Difference between "as $key => $value" and "as $value" in PHP foreach

Sample Array: Left ones are the keys, right one are my values

$array = array(
        'key-1' => 'value-1', 
        'key-2' => 'value-2',
        'key-3' => 'value-3',
        );

Example A: I want only the values of $array

foreach($array as $value) {    
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'     
}

Example B: I want each value AND key of $array

foreach($array as $key => $value) {                 
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'  

    echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'    

    echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
    $array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1            
}

Line Break in HTML Select Option?

No, browsers don't provide this formatting option.

You could probably fake it with some checkboxes with <label>s, and JS to turn it into a fly out menu.

Automatic confirmation of deletion in powershell

You just need to add a /A behind the line.

Example:

get-childitem C:\temp\ -exclude *.svn-base,".svn" -recurse | foreach ($_) {remove-item $_.fullname} /a

Replace only text inside a div using jquery

Find the text nodes (nodeType==3) and replace the textContent:

$('#one').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});

Note that as per the docs you can replace the hard-coded 3 in the above with Node.TEXT_NODE which is much clearer what you're doing.

_x000D_
_x000D_
$('#one').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>
_x000D_
_x000D_
_x000D_

What is the difference between git clone and checkout?

One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone of your chosen upstream repo. So you have effectively a personal checkout of everything, without putting some 'lock' on those files in the reference repo.

Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

Shrink a YouTube video to responsive width

Okay, looks like big solutions.

Why not to add width: 100%; directly in your iframe. ;)

So your code would looks something like <iframe style="width: 100%;" ...></iframe>

Try this it'll work as it worked in my case.

Enjoy! :)

How to check string length with JavaScript

As for the question which event you should use for this: use the input event, and fall back to keyup/keydown in older browsers.

Here’s an example, DOM0-style:

someElement.oninput = function() {
  this.onkeydown = null;
  // Your code goes here
};
someElement.onkeydown = function() {
  // Your code goes here
};

The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)

P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you’ll see that it (incorrectly) counts as two characters.

How to convert a string to lower case in Bash?

Simple way

echo "Hi all" | awk '{ print tolower($0); }'

Can an Option in a Select tag carry multiple values?

I was actually wondering this today, and I achieved it by using the php explode function, like this:

HTML Form (in a file I named 'doublevalue.php':

    <form name="car_form" method="post" action="doublevalue_action.php">
            <select name="car" id="car">
                    <option value="">Select Car</option>
                    <option value="BMW|Red">Red BMW</option>
                    <option value="Mercedes|Black">Black Mercedes</option>
            </select>
            <input type="submit" name="submit" id="submit" value="submit">
    </form>

PHP action (in a file I named doublevalue_action.php)

    <?php
            $result = $_POST['car'];
            $result_explode = explode('|', $result);
            echo "Model: ". $result_explode[0]."<br />";
            echo "Colour: ". $result_explode[1]."<br />";
    ?>

As you can see in the first piece of code, we're creating a standard HTML select box, with 2 options. Each option has 1 value, which has a separator (in this instance, '|') to split the values (in this case, model and colour).

On the action page, I'm exploding the results into an array, then calling each one. As you can see, I've separated and labelled them so you can see the effect this is causing.

I hope this helps someone :)

Text in a flex container doesn't wrap in IE11

Me too I encountered this issue.

The only alternative is to define a width (or max-width) in the child elements. IE 11 is a bit stupid, and me I just spent 20 minutes to realize this solution.

.parent {
  display: flex;
  flex-direction: column;
  width: 800px;
  border: 1px solid red;
  align-items: center;
}
.child {
  border: 1px solid blue;
  max-width: 800px;
  @media (max-width:960px){ // <--- Here we go. The text won't wrap ? we will make it break !
    max-width: 600px;
  }
  @media (max-width:600px){
    max-width: 400px;
  }
  @media (max-width:400px){
    max-width: 150px;
  }
}

<div class="parent">
  <div class="child">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="child">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
</div>

"SyntaxError: Unexpected token < in JSON at position 0"

I had the same error message following a tutorial. Our issue seems to be 'url: this.props.url' in the ajax call. In React.DOM when you are creating your element, mine looks like this.

ReactDOM.render(
    <CommentBox data="/api/comments" pollInterval={2000}/>,
    document.getElementById('content')
);

Well, this CommentBox does not have a url in its props, just data. When I switched url: this.props.url -> url: this.props.data, it made the right call to the server and I got back the expected data.

I hope it helps.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

I solved this using following

if(tabLayout_chemistCategory.getTabCount()<4)
    {
        tabLayout_chemistCategory.setTabGravity(TabLayout.GRAVITY_FILL);
    }else
    {
        tabLayout_chemistCategory.setTabMode(TabLayout.MODE_SCROLLABLE);

    }

Converting string from snake_case to CamelCase in Ruby

Benchmark for pure Ruby solutions

I took every possibilities I had in mind to do it with pure ruby code, here they are :

  • capitalize and gsub

    'app_user'.capitalize.gsub(/_(\w)/){$1.upcase}
    
  • split and map using & shorthand (thanks to user3869936’s answer)

    'app_user'.split('_').map(&:capitalize).join
    
  • split and map (thanks to Mr. Black’s answer)

    'app_user'.split('_').map{|e| e.capitalize}.join
    

And here is the Benchmark for all of these, we can see that gsub is quite bad for this. I used 126 080 words.

                              user     system      total        real
capitalize and gsub  :      0.360000   0.000000   0.360000 (  0.357472)
split and map, with &:      0.190000   0.000000   0.190000 (  0.189493)
split and map        :      0.170000   0.000000   0.170000 (  0.171859)

Redis - Connect to Remote Server

Setting tcp-keepalive to 60 (it was set to 0) in server's redis configuration helped me resolve this issue.

Kubernetes how to make Deployment to update image

I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID

Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example

imagename:buildID

once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as

imagename:env:buildID

here evn:buildid is the azure devops variable which having value of build ID.

so now every time I have new changes to build(CI) and deploy(CD).

please comment if you need build definition for CI/CD.

What could cause java.lang.reflect.InvocationTargetException?

I had a java.lang.reflect.InvocationTargetException error from a statement calling a logger object in an external class inside a try / catch block in my class.

Stepping through the code in the Eclipse debugger & hovering the mouse over the logger statement I saw the logger object was null (some external constants needed to be instantiated at the very top of my class).

How do I get Month and Date of JavaScript in 2 digit format?

Why not use padStart ?

_x000D_
_x000D_
var dt = new Date();

year  = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day   = dt.getDate().toString().padStart(2, "0");

console.log(year + '/' + month + '/' + day);
_x000D_
_x000D_
_x000D_

This will always return 2 digit numbers even if the month or day is less than 10.

Notes:

  • This will only work with Internet Explorer if the js code is transpiled using babel.
  • getFullYear() returns the 4 digit year and doesn't require padStart.
  • getMonth() returns the month from 0 to 11.
    • 1 is added to the month before padding to keep it 1 to 12
  • getDate() returns the day from 1 to 31.
    • the 7th day will return 07 and so we do not need to add 1 before padding the string.

Slack clean all messages (~8K) in a channel

!!UPDATE!!

as @niels-van-reijmersdal metioned in comment.

This feature has been removed. See this thread for more info: twitter.com/slackhq/status/467182697979588608?lang=en

!!END UPDATE!!

Here is a nice answer from SlackHQ in twitter, and it works without any third party stuff. https://twitter.com/slackhq/status/467182697979588608?lang=en

You can bulk delete via the archives (http://my.slack.com/archives ) page for a particular channel: look for "delete messages" in menu

No Persistence provider for EntityManager named

You need the following jar files in the classpath:

  1. antlr-2.7.6.jar
  2. commons-collections-3.1.jar
  3. dom4j-1.6.1.jar
  4. hibernate-commons-annotations-4.0.1.Final.jar
  5. hibernate-core-4.0.1.Final.jar
  6. hibernate-entitymanager.jar
  7. hibernate-jpa-2.0-api-1.0.0.Final.jar
  8. javassist-3.9.0.jar
  9. jboss-logging-3.1.1.GA.jar
  10. jta-1.1.jar
  11. slf4j-api-1.5.8.jar
  12. xxx-jdbc-driver.jar

Can someone give an example of cosine similarity, in a very simple, graphical way?

Using @Bill Bell example, two ways to do this in [R]

a = c(2,1,0,2,0,1,1,1)

b = c(2,1,1,1,1,0,1,1)

d = (a %*% b) / (sqrt(sum(a^2)) * sqrt(sum(b^2)))

or taking advantage of crossprod() method's performance...

e = crossprod(a, b) / (sqrt(crossprod(a, a)) * sqrt(crossprod(b, b)))

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

What is "not assignable to parameter of type never" error in typescript?

I was able to get past this by using the Array keyword instead of empty brackets:

const enhancers: Array<any> = [];

Use:

if (typeof devToolsExtension === 'function') {
  enhancers.push(devToolsExtension())
}

How to hide a div with jQuery?

If you want the element to keep its space then you need to use,

$('#myDiv').css('visibility','hidden')

If you dont want the element to retain its space, then you can use,

$('#myDiv').css('display','none')

or simply,

$('#myDiv').hide();

jQuery: Check if special characters exists in string

var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
    for(i = 0; i < specialChars.length;i++){
        if(string.indexOf(specialChars[i]) > -1){
            return true
        }
    }
    return false;
}

if(check($('#Search').val()) == false){
    // Code that needs to execute when none of the above is in the string
}else{
    alert('Your search string contains illegal characters.');
}

Select distinct values from a large DataTable column

Sorry to post answer for very old thread. my answer may help other in future.

string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

    //Following function will return Distinct records for Name, City and State column.
    public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
       {
           DataTable dtUniqRecords = new DataTable();
           dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
           return dtUniqRecords;
       }

Assign variable value inside if-statement

I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into

int v;
if((v = someMethod()) != 0) return true;

There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.

Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.

Partly cherry-picking a commit with Git

Building on Mike Monkiewicz answer you can also specify a single or more files to checkout from the supplied sha1/branch.

git checkout -p bc66559 -- path/to/file.java 

This will allow you to interactively pick the changes you want to have applied to your current version of the file.

CSS3 equivalent to jQuery slideUp and slideDown?

I changed your solution, so that it works in all modern browsers:

css snippet:

-webkit-transition: height 1s ease-in-out;
-moz-transition: height 1s ease-in-out;
-ms-transition: height 1s ease-in-out;
-o-transition: height 1s ease-in-out;
transition: height 1s ease-in-out;

js snippet:

    var clone = $('#this').clone()
                .css({'position':'absolute','visibility':'hidden','height':'auto'})
                .addClass('slideClone')
                .appendTo('body');

    var newHeight = $(".slideClone").height();
    $(".slideClone").remove();
    $('#this').css('height',newHeight + 'px');

here's the full example http://jsfiddle.net/RHPQd/

Setting attribute disabled on a SPAN element does not prevent click events

There is a dirty trick, what I have used:

I am using bootstrap, so I just added .disabled class to the element which I want to disable. Bootstrap handles the rest of the things.

Suggestion are heartily welcome towards this.

Adding class on run time:

$('#element').addClass('disabled');

How to delete a file via PHP?

I know this question is a bit old, but this is something simple that works for me very well to delete images off my project I'm working on.

unlink(dirname(__FILE__) . "/img/tasks/" . 'image.jpg');

The dirname(__FILE__) section prints out the base path to your project. The /img/tasks/ are two folders down from my base path. And finally, there's my image I want to delete which you can make into anything you need to.

With this I have not had any problem getting to my files on my server and deleting them.

return string with first match Regex

If you only need the first match, then use re.search instead of re.findall:

>>> m = re.search('\d+', 'aa33bbb44')
>>> m.group()
'33'
>>> m = re.search('\d+', 'aazzzbbb')
>>> m.group()
Traceback (most recent call last):
  File "<pyshell#281>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'

Then you can use m as a checking condition as:

>>> m = re.search('\d+', 'aa33bbb44')
>>> if m:
        print('First number found = {}'.format(m.group()))
    else:
        print('Not Found')


First number found = 33

Log all queries in mysql

(Note: For mysql-5.6+ this won't work. There's a solution that applies to mysql-5.6+ if you scroll down or click here.)

If you don't want or cannot restart the MySQL server you can proceed like this on your running server:

  • Create your log tables on the mysql database
  CREATE TABLE `slow_log` (
   `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
                          ON UPDATE CURRENT_TIMESTAMP,
   `user_host` mediumtext NOT NULL,
   `query_time` time NOT NULL,
   `lock_time` time NOT NULL,
   `rows_sent` int(11) NOT NULL,
   `rows_examined` int(11) NOT NULL,
   `db` varchar(512) NOT NULL,
   `last_insert_id` int(11) NOT NULL,
   `insert_id` int(11) NOT NULL,
   `server_id` int(10) unsigned NOT NULL,
   `sql_text` mediumtext NOT NULL,
   `thread_id` bigint(21) unsigned NOT NULL
  ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log'
  CREATE TABLE `general_log` (
   `event_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
                          ON UPDATE CURRENT_TIMESTAMP,
   `user_host` mediumtext NOT NULL,
   `thread_id` bigint(21) unsigned NOT NULL,
   `server_id` int(10) unsigned NOT NULL,
   `command_type` varchar(64) NOT NULL,
   `argument` mediumtext NOT NULL
  ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='General log'
  • Enable Query logging on the database
SET global general_log = 1;
SET global log_output = 'table';
  • View the log
select * from mysql.general_log
  • Disable Query logging on the database
SET global general_log = 0;

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

How to change text color of simple list item

The simplest way to do this without needing to create anything extra would be to just modify the simple list TextView:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, strings) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setTextColor({YourColorHere});
                return textView;
            }
        };

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I have the same question.

You should add some dependencies in build.gradle, just looks like this

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':libcocos2dx')
    compile 'com.google.firebase:firebase-ads:11.6.0'
// the key point line
    compile 'com.google.android.gms:play-services-auth:11.6.0'
}

What does %w(array) mean?

Excerpted from the documentation for Percent Strings at http://ruby-doc.org/core/doc/syntax/literals_rdoc.html#label-Percent+Strings:

Besides %(...) which creates a String, the % may create other types of object. As with strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

These are the types of percent strings in ruby:
...
%w: Array of Strings

SQL: Combine Select count(*) from multiple tables

SELECT 
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')

This is an easy way.

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

moment.js 24h format

You can use

 moment("15", "hh").format('LT') 

to convert the time to 12 hours format like this 3:00 PM

Decimal values in SQL for dividing results

There may be other ways to get your desired result.

Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)

jQuery get html of container including the container itself

Firefox doesn't support outerHTML, so you need to define a function to help support it:

function outerHTML(node) {
    return node.outerHTML || (
        function(n) {
            var div = document.createElement('div');
            div.appendChild( n.cloneNode(true) );
            var h = div.innerHTML;
            div = null;
            return h;
        }
    )(node);
}

Then, you can use outerHTML:

var x = outerHTML($('#container').get(0));
$('#save').val(x);

How to both read and write a file in C#

This thread seems to answer your question : simultaneous-read-write-a-file

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

Continue For loop

You can use a GoTo:

Do

    '... do stuff your loop will be doing

    ' skip to the end of the loop if necessary:
    If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop 

    '... do other stuff if the condition is not met

ContinueLoop:
Loop

Difference between Python's Generators and Iterators

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

In summary: Iterators are objects that have an __iter__ and a __next__ (next in Python 2) method. Generators provide an easy, built-in way to create instances of Iterators.

A function with yield in it is still a function, that, when called, returns an instance of a generator object:

def a_function():
    "when called, returns generator object"
    yield

A generator expression also returns a generator:

a_generator = (i for i in range(0))

For a more in-depth exposition and examples, keep reading.

A Generator is an Iterator

Specifically, generator is a subtype of iterator.

>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True

We can create a generator several ways. A very common and simple way to do so is with a function.

Specifically, a function with yield in it is a function, that, when called, returns a generator:

>>> def a_function():
        "just a function definition with yield in it"
        yield
>>> type(a_function)
<class 'function'>
>>> a_generator = a_function()  # when called
>>> type(a_generator)           # returns a generator
<class 'generator'>

And a generator, again, is an Iterator:

>>> isinstance(a_generator, collections.Iterator)
True

An Iterator is an Iterable

An Iterator is an Iterable,

>>> issubclass(collections.Iterator, collections.Iterable)
True

which requires an __iter__ method that returns an Iterator:

>>> collections.Iterable()
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    collections.Iterable()
TypeError: Can't instantiate abstract class Iterable with abstract methods __iter__

Some examples of iterables are the built-in tuples, lists, dictionaries, sets, frozen sets, strings, byte strings, byte arrays, ranges and memoryviews:

>>> all(isinstance(element, collections.Iterable) for element in (
        (), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True

Iterators require a next or __next__ method

In Python 2:

>>> collections.Iterator()
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    collections.Iterator()
TypeError: Can't instantiate abstract class Iterator with abstract methods next

And in Python 3:

>>> collections.Iterator()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Iterator with abstract methods __next__

We can get the iterators from the built-in objects (or custom objects) with the iter function:

>>> all(isinstance(iter(element), collections.Iterator) for element in (
        (), [], {}, set(), frozenset(), '', b'', bytearray(), range(0), memoryview(b'')))
True

The __iter__ method is called when you attempt to use an object with a for-loop. Then the __next__ method is called on the iterator object to get each item out for the loop. The iterator raises StopIteration when you have exhausted it, and it cannot be reused at that point.

From the documentation

From the Generator Types section of the Iterator Types section of the Built-in Types documentation:

Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() [__next__() in Python 3] methods. More information about generators can be found in the documentation for the yield expression.

(Emphasis added.)

So from this we learn that Generators are a (convenient) type of Iterator.

Example Iterator Objects

You might create object that implements the Iterator protocol by creating or extending your own object.

class Yes(collections.Iterator):

    def __init__(self, stop):
        self.x = 0
        self.stop = stop

    def __iter__(self):
        return self

    def next(self):
        if self.x < self.stop:
            self.x += 1
            return 'yes'
        else:
            # Iterators must raise when done, else considered broken
            raise StopIteration

    __next__ = next # Python 3 compatibility

But it's easier to simply use a Generator to do this:

def yes(stop):
    for _ in range(stop):
        yield 'yes'

Or perhaps simpler, a Generator Expression (works similarly to list comprehensions):

yes_expr = ('yes' for _ in range(stop))

They can all be used in the same way:

>>> stop = 4             
>>> for i, y1, y2, y3 in zip(range(stop), Yes(stop), yes(stop), 
                             ('yes' for _ in range(stop))):
...     print('{0}: {1} == {2} == {3}'.format(i, y1, y2, y3))
...     
0: yes == yes == yes
1: yes == yes == yes
2: yes == yes == yes
3: yes == yes == yes

Conclusion

You can use the Iterator protocol directly when you need to extend a Python object as an object that can be iterated over.

However, in the vast majority of cases, you are best suited to use yield to define a function that returns a Generator Iterator or consider Generator Expressions.

Finally, note that generators provide even more functionality as coroutines. I explain Generators, along with the yield statement, in depth on my answer to "What does the “yield” keyword do?".

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

Semi-transparent color layer over background-image?

You can also add opacity to your overlay color.

Instead of doing

background: url('../img/bg/diagonalnoise.png');
background-color: rgba(248, 247, 216, 0.7);

You can do:

background: url('../img/bg/diagonalnoise.png');

Then create a new style for the opacity color:

.colorStyle{
    background-color: rgba(248, 247, 216, 0.7);
    opacity: 0.8;
}

Change the opacity to whatever number you want below 1. Then you make this color style the same size as your image. It should work.

how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

Vim: How to insert in visual block mode?

Try this

After selecting a block of text, press Shift+i or capital I.

Lowercase i will not work.

Then type the things you want and finally to apply it to all lines, press Esc twice.




If this doesn't work...

Check if you have +visualextra enabled in your version of Vim.

You can do this by typing in :ver and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)

Enabling it is outside the scope of this question but I'm sure you can find it somewhere.

C - error: storage size of ‘a’ isn’t known

Your struct is called struct xyx but a is of type struct xyz. Once you fix that, the output is 100.

#include <stdio.h>

struct xyx {
    int x;
    int y;
    char c;
    char str[20];
    int arr[2];
};

int main(void)
{
    struct xyx a;
    a.x = 100;
    printf("%d\n", a.x);
    return 0;
}

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

Getting the exception value in Python

use str

try:
    some_method()
except Exception as e:
    s = str(e)

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?

Angular 2 Date Input not binding to date value

In your component

let today: string;

ngOnInit() {
  this.today = new Date().toISOString().split('T')[0];
}

and in your html file

<input name="date" [(ngModel)]="today" type="date" required>

How to compare Boolean?

Try this:

if (Boolean.TRUE.equals(yourValue)) { ... }

As additional benefit this is null-safe.

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Command line to remove an environment variable from the OS level configuration

This has been covered quite a bit, but there's a crucial piece of information that's missing. Hopefully, I can help to clear up how this works and give some relief to weary travellers. :-)

Delete From Current Process

Obviously, everyone knows that you just do this to delete an environment variable from your current process:

set FOO=

Persistent Delete

There are two sets of environment variables, system-wide and user.

Delete User Environment Variable:

reg delete "HKCU\Environment" /v FOO /f

Delete System-Wide Environment Variable:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOO

Apply Value Without Rebooting

Here's the magic information that's missing! You're wondering why after you do this, when you launch a new command window, the environment variable is still there. The reason is because explorer.exe has not updated its environment. When one process launches another, the new process inherits the environment from the process that launched it.

There are two ways to fix this without rebooting. The most brute-force way is to kill your explorer.exe process and start it again. You can do that from Task Manager. I don't recommend this method, however.

The other way is by telling explorer.exe that the environment has changed and that it should reread it. This is done by broadcasting a Windows message (WM_SETTINGCHANGE). This can be accomplished with a simple PowerShell script. You could easily write one to do this, but I found one in Update Window Settings After Scripted Changes:

if (-not ("win32.nativemethods" -as [type])) {
    add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageTimeout(
            IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
            uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
        "@
}

$HWND_BROADCAST = [intptr]0xffff;
$WM_SETTINGCHANGE = 0x1a;
$result = [uintptr]::zero

[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE,[uintptr]::Zero, "Environment", 2, 5000, [ref]$result);

Summary

So to delete a user environment variable named "FOO" and have the change reflected in processes you launch afterwards, do the following.

  1. Save the PowerShell script to a file (we'll call it updateenv.ps1).
  2. Do this from the command line: reg delete "HKCU\Environment" /v FOO /f
  3. Run updateenv.ps1.
  4. Close and reopen your command prompt, and you'll see that the environment variable is no longer defined.

Note, you'll probably have to update your PowerShell settings to allow you to run this script, but I'll leave that as a Google-fu exercise for you.

Java Date vs Calendar

Btw "date" is usually tagged as "obsolete / deprecated" (I dont know exactly why) - something about it is wrote there Java: Why is the Date constructor deprecated, and what do I use instead?

It looks like it's a problem of the constructor only- way via new Date(int year, int month, int day), recommended way is via Calendar and set params separately .. (Calendar cal = Calendar.getInstance(); )

How to set image on QPushButton?

This is old but it is still useful, Fully tested with QT5.3.

Be carreful, example concerning the ressources path :

In my case I created a ressources directory named "Ressources" in the source directory project.

The folder "ressources" contain pictures and icons.Then I added a prefix "Images" in Qt So the pixmap path become:

QPixmap pixmap(":/images/Ressources/icone_pdf.png");

JF

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Most efficient way to check if a file is empty in Java on Windows

This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:

Using Apache Commons FileUtils

private void printEmptyFileName(final File file) throws IOException {
    /*Arbitrary big-ish number that definitely is not an empty file*/
    int limit = 4096;
    if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
        System.out.println("File is empty: " + file.getName());
    }        
}

How do you show animated GIFs on a Windows Form (c#)

Public Class Form1

    Private animatedimage As New Bitmap("C:\MyData\Search.gif")
    Private currentlyanimating As Boolean = False

    Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Me.Invalidate()

    End Sub

    Private Sub AnimateImage()

        If currentlyanimating = True Then
            ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
            currentlyanimating = False
        End If

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        AnimateImage()
        ImageAnimator.UpdateFrames(animatedimage)
        e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click

        currentlyanimating = False
        ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
        BtnStart.Enabled = True
        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click

        currentlyanimating = True
        AnimateImage()
        BtnStart.Enabled = False
        BtnStop.Enabled = True

    End Sub

End Class

Android studio: emulator is running but not showing up in Run App "choose a running device"

  1. start device from genymotion button (have to install genymotion before and setup genymotion folder location on settings)
  2. run application
  3. choose genymotion running device

Android Studio is slow (how to speed up)?

This worked for me!
Open build.gradle (it's inside your project) and change the both jcenter to mavenCentral

(you can do it in Global file too: C:\Program Files\AndroidStudio\plugins\android\lib\templates\gradle-projects\NewAndroidProject\root\build.gradle.ftl however, you will need to do this modification again after AndroidStudio upgrade)

Map and filter an array at the same time

Using reduce, you can do this in one Array.prototype function. This will fetch all even numbers from an array.

_x000D_
_x000D_
var arr = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
var brr = arr.reduce((c, n) => {_x000D_
  if (n % 2 !== 0) {_x000D_
    return c;_x000D_
  }_x000D_
  c.push(n);_x000D_
  return c;_x000D_
}, []);_x000D_
_x000D_
document.getElementById('mypre').innerHTML = brr.toString();
_x000D_
<h1>Get all even numbers</h1>_x000D_
<pre id="mypre"> </pre>
_x000D_
_x000D_
_x000D_

You can use the same method and generalize it for your objects, like this.

var arr = options.reduce(function(c,n){
  if(somecondition) {return c;}
  c.push(n);
  return c;
}, []);

arr will now contain the filtered objects.

How to check if element exists using a lambda expression?

While the accepted answer is correct, I'll add a more elegant version (in my opinion):

boolean idExists = tabPane.getTabs().stream()
    .map(Tab::getId)
    .anyMatch(idToCheck::equals);

Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate.

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

ALTER DATABASE failed because a lock could not be placed on database

I will add this here in case someone will be as lucky as me.

When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.

Check if you have any processes in KILL/RollBack state for master database

SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'

If you have the same issue, just the KILL command will probably not help. You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

Show or hide element in React

React circa 2020

In the onClick callback, call the state hook's setter function to update the state and re-render:

_x000D_
_x000D_
const Search = () => {_x000D_
  const [showResults, setShowResults] = React.useState(false)_x000D_
  const onClick = () => setShowResults(true)_x000D_
  return (_x000D_
    <div>_x000D_
      <input type="submit" value="Search" onClick={onClick} />_x000D_
      { showResults ? <Results /> : null }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
const Results = () => (_x000D_
  <div id="results" className="search-results">_x000D_
    Some Results_x000D_
  </div>_x000D_
)_x000D_
_x000D_
ReactDOM.render(<Search />, document.querySelector("#container"))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

React circa 2014

The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:

_x000D_
_x000D_
var Search = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return { showResults: false };_x000D_
    },_x000D_
    onClick: function() {_x000D_
        this.setState({ showResults: true });_x000D_
    },_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <input type="submit" value="Search" onClick={this.onClick} />_x000D_
                { this.state.showResults ? <Results /> : null }_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Results = React.createClass({_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div id="results" className="search-results">_x000D_
                Some Results_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render( <Search /> , document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

Unable to connect with remote debugger

The other answers here were missing one crucial step for me. In AndroidManifest.xml I needed to add usesCleartextTraffic:

    <application
      ...
      android:usesCleartextTraffic="true">

You probably don't want to keep this in the production release of your app though, unless you want to support insecure http requests.

After I added this to my AndroidManifest.xml, then I followed Tom Aranda's answer, and the emulator was finally able to connect to the debugger.

Angular ng-if not true

Use like this

<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>

OperationalError, no such column. Django

I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:

python manage.py makemigrations snippets
python manage.py migrate

And that should resolve the error. Enjoy.

Compare objects in Angular

Assuming that the order is the same in both objects, just stringify them both and compare!

JSON.stringify(obj1) == JSON.stringify(obj2);

Retrieve a single file from a repository

for bitbucket directly from browser (I used safari...) right-click on 'View Raw" and choose "Download Linked File":

enter image description here

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

Convert list of dictionaries to a pandas DataFrame

In pandas 16.2, I had to do pd.DataFrame.from_records(d) to get this to work.

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

Convert XML to JSON (and back) using Javascript

Here' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.

var obj = {name: "Super", Surname: "Man", age: 23};

var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);

Run cmd commands through Java

You can't run cd this way, because cd isn't a real program; it's a built-in part of the command-line, and all it does is change the command-line's environment. It doesn't make sense to run it in a subprocess, because then you're changing that subprocess's environment — but that subprocess closes immediately, discarding its environment.

To set the current working directory in your actual Java program, you should write:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");

Get Value From Select Option in Angular 4

As a general (see Stackblitz here: https://stackblitz.com/edit/angular-gh2rjx):

HTML

<select [(ngModel)]="selectedOption">
   <option *ngFor="let o of options">
      {{o.name}}
   </option>
</select>
<button (click)="print()">Click me</button>

<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>

Typescript

export class AppComponent {
  selectedOption: string;
  printedOption: string;

  options = [
    { name: "option1", value: 1 },
    { name: "option2", value: 2 }
  ]
  print() {
    this.printedOption = this.selectedOption;
  }
}

In your specific case you can use ngModel like this:

<form class="form-inline" (ngSubmit)="HelloCorp()">
     <div class="select">
         <select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
             <option *ngFor="let corporation of corporations"></option>    
         </select>
         <button type="submit" class="btn btn-primary manage">Submit</button>
     </div>
</form>

HelloCorp() {
  console.log("My input: ", corporationObj);
}

Convert string to title case with JavaScript

john smith -> John Smith

'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

Model backing a DB Context has changed; Consider Code First Migrations

This error occurs when you have database is not in sync with your model and vice versa. To overcome this , follow the below steps -

a) Add a migration file using add-migration <{Migration File Name}> through the nuget package manager console. This migration file will have the script to sync anything not in sync between Db and code.

b) Update the database using update-database command. This will update the database with the latest changes in your model.

If this does not help, try these steps after adding the line of code in the Application_Start method of Global.asax.cs file -

Database.SetInitializer<VidlyDbContext>(new DropCreateDatabaseIfModelChanges<VidlyDbContext>());

Reference - http://robertgreiner.com/2012/05/unable-to-update-database-to-match-the-current-model-pending-changes/

Bootstrap: Collapse other sections when one is expanded

The Method Works Properly For me:

var lanopt = $(".language-option");

lanopt.on("show.bs.collapse",".collapse", function(){
   lanopt.find(".collapse.in").collapse("hide");
});

Find number of decimal places in decimal value regardless of culture

Using recursion you can do:

private int GetDecimals(decimal n, int decimals = 0)  
{  
    return n % 1 != 0 ? GetDecimals(n * 10, decimals + 1) : decimals;  
}

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

How to obtain the total numbers of rows from a CSV file in Python?

To do it you need to have a bit of code like my example here:

file = open("Task1.csv")
numline = len(file.readlines())
print (numline)

I hope this helps everyone.

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

jQuery Combobox/select autocomplete?

[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.

Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.

(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var input,
              that = this,
              wasOpen = false,
              select = this.element.hide(),
              selected = select.children(":selected"),
              defaultValue = selected.text() || "",
              wrapper = this.wrapper = $("<span>")
                .addClass("ui-combobox")
                .insertAfter(select);

            function removeIfInvalid(element) {
                var value = $(element).val(),
                  matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
                  valid = false;
                select.children("option").each(function () {
                    if ($(this).text().match(matcher)) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                if (!valid) {
                    // remove invalid value, as it didn't match anything
                    $(element).val(defaultValue);
                    select.val(defaultValue);
                    input.data("ui-autocomplete").term = "";
                }
            }

            input = $("<input>")
              .appendTo(wrapper)
              .val(defaultValue)
              .attr("title", "")
              .addClass("ui-state-default ui-combobox-input")
              .width(select.width())
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  autoFocus: true,
                  source: function (request, response) {
                      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                      response(select.children("option").map(function () {
                          var text = $(this).text();
                          if (this.value && (!request.term || matcher.test(text)))
                              return {
                                  label: text.replace(
                                    new RegExp(
                                      "(?![^&;]+;)(?!<[^<>]*)(" +
                                      $.ui.autocomplete.escapeRegex(request.term) +
                                      ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>"),
                                  value: text,
                                  option: this
                              };
                      }));
                  },
                  select: function (event, ui) {
                      ui.item.option.selected = true;
                      that._trigger("selected", event, {
                          item: ui.item.option
                      });
                  },
                  change: function (event, ui) {
                      if (!ui.item) {
                          removeIfInvalid(this);
                      }
                  }
              })
              .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                  .append("<a>" + item.label + "</a>")
                  .appendTo(ul);
            };

            $("<a>")
              .attr("tabIndex", -1)
              .appendTo(wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("ui-corner-right ui-combobox-toggle")
              .mousedown(function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .click(function () {
                  input.focus();

                  // close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);

How to crop an image using C#?

There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping

Register the control

<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>

Resizing

<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1" 
     X="10" Y="10" X2="50" Y2="50" />

Cropping in code behind - Call Crop method when button clicked for example;

wci1.Crop(Server.MapPath("images/sample1.jpg"));

Posting form to different MVC post action depending on the clicked submit button

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

In this way you don't need to do anything special on the server side.

Of course, you can use Url extensions methods in your Razor to specify the form action.

For browsers supporting HMTL5: simply define your submit buttons like this:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

On CentOS 5.x, a simple yum update openssl updated the openssl package which updated the system ca-bundle.crt file and fixed the problem for me.

The same may be true for other distributions.