Programs & Examples On #Tabbed document interface

Clearing NSUserDefaults

Note: This answer has been updated for Swift too.

What about to have it on one line?

Extending @Christopher Rogers answer – the accepted one.

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

and yes, sometime you may need to synchronize it,

[[NSUserDefaults standardUserDefaults] synchronize];

I've created a method to do this,

- (void) clearDefaults {
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Swift?

With swift its even more easy.

extension UserDefaults {
    class func clean() {
        guard let aValidIdentifier = Bundle.main.bundleIdentifier else { return }
        standard.removePersistentDomain(forName: aValidIdentifier)
        standard.synchronize()
    }
}

And usage:

UserDefaults.clean()

Run Stored Procedure in SQL Developer?

Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer. After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.

  • Under packages, select your desired package and right click on the package name (not on the stored procedure name).

  • You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below

I'm using SQL developer version 4.1.3.20

Can I use a min-height for table, tr or td?

height for td works like min-height:

td {
  height: 100px;
}

instead of

td {
  min-height: 100px;
}

Table cells will grow when the content does not fit.

https://jsfiddle.net/qz70zps4/

Calculating time difference in Milliseconds

In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.

jQuery not working with IE 11

The problem was caused because the page was an intranet site, & IE had compatibility mode set to default for this. IE11 does support addEventListener()

How to round down to nearest integer in MySQL?

It can be done in the following two ways:

  • select floor(desired_field_value) from table
  • select round(desired_field_value-0.5) from table

The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.

ImportError: no module named win32api

I didn't find the package of the most voted answer in my Python 3 dist.

I had the same problem and solved it installing the module pywin32:

In a normal python:

pip install pywin32

In anaconda:

conda install pywin32

My python installation (Intel® Distribution for Python) had some kind of dependency problem and was giving this error. After installing this module it stopped appearing.

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

how to convert object into string in php

There is an object serialization module, with the serialize function you can serialize any object.

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Django gives Bad Request (400) when DEBUG = False

For me, I got this error by not setting USE_X_FORWARDED_HOST to true. From the docs:

This should only be enabled if a proxy which sets this header is in use.

My hosting service wrote explicitly in their documentation that this setting must be used, and I get this 400 error if I forget it.

How to Apply global font to whole HTML document

You should be able to utilize the asterisk and !important elements within CSS.

html *
{
   font-size: 1em !important;
   color: #000 !important;
   font-family: Arial !important;
}

The asterisk matches everything (you could probably get away without the html too).

The !important ensures that nothing can override what you've set in this style (unless it is also important). (this is to help with your requirement that it should "ignore inner formatting of text" - which I took to mean that other styles could not overwrite these)

The rest of the style within the braces is just like any other styling and you can do whatever you'd like to in there. I chose to change the font size, color and family as an example.

How to show an alert box in PHP?

Try this:

Define a funciton:

<?php
function phpAlert($msg) {
    echo '<script type="text/javascript">alert("' . $msg . '")</script>';
}
?>

Call it like this:

<?php phpAlert(   "Hello world!\\n\\nPHP has got an Alert Box"   );  ?>

Client to send SOAP request and receive response

I wrote a more general helper class which accepts a string-based dictionary of custom parameters, so that they can be set by the caller without having to hard-code them. It goes without saying that you should only use such method when you want (or need) to manually issue a SOAP-based web service: in most common scenarios the recommended approach would be using the Web Service WSDL together with the Add Service Reference Visual Studio feature instead.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;

namespace Ryadel.Web.SOAP
{
    /// <summary>
    /// Helper class to send custom SOAP requests.
    /// </summary>
    public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        {
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var xmlStr = (useSOAP12)
                ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                      xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                      xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                      <soap12:Body>
                        <{0} xmlns=""{1}"">{2}</{0}>
                      </soap12:Body>
                    </soap12:Envelope>"
                : @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <soap:Body>
                           <{0} xmlns=""{1}"">{2}</{0}>
                        </soap:Body>
                    </soap:Envelope>";
            string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
            soapEnvelopeXml.LoadXml(s);

            // Create the web request
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction ?? url);
            webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
            webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
            webRequest.Method = "POST";

            // Insert SOAP envelope
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            // Send request and retrieve result
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
    }
}

For additional info & details regarding this class you can also read this post on my blog.

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

Android overlay a view ontop of everything?

The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).

Add mMyDrawable to mMyView as its overlay:

mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

Is it safe to delete the "InetPub" folder?

Don't delete the folder or you will create a registry problem. However, if you do not want to use IIS, search the web for turning it off. You might want to check out "www.blackviper.com" because he lists all Operating System "services" (Not "Computer Services" - both are in Administrator Tools) with extra information for what you can and cannot disable to change to manual. If I recall correctly, he had some IIS info and how to turn it off.

How to get PID of process I've just started within java program?

There is an open-source library that has such a function, and it has cross-platform implementations: https://github.com/OpenHFT/Java-Thread-Affinity

It may be overkill just to get the PID, but if you want other things like CPU and thread id, and specifically thread affinity, it may be adequate for you.

To get the current thread's PID, just call Affinity.getAffinityImpl().getProcessId().

This is implemented using JNA (see arcsin's answer).

How to enable production mode?

In environment.ts file set production to true

export const environment = {
  production: true
};

Get element of JS object with an index

I know it's a late answer, but I think this is what OP asked for.

myobj[Object.keys(myobj)[0]];

python requests file upload

(2018) the new python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}

r = requests.post(url, files=files)
r.text

Reloading submodules in IPython

I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run() that others might find useful (I have anyway)

del the submodule you wish to reload on run from sys.modules in iPython:

In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!

Now your script will recursively reload this submodule:

In[3]: %run myscript.py

How to create a temporary directory/folder in Java?

I like the multiple attempts at creating a unique name but even this solution does not rule out a race condition. Another process can slip in after the test for exists() and the if(newTempDir.mkdirs()) method invocation. I have no idea how to completely make this safe without resorting to native code, which I presume is what's buried inside File.createTempFile().

Angular + Material - How to refresh a data source (mat-table)

I don't know if the ChangeDetectorRef was required when the question was created, but now this is enough:

import { MatTableDataSource } from '@angular/material/table';

// ...

dataSource = new MatTableDataSource<MyDataType>();

refresh() {
  this.myService.doSomething().subscribe((data: MyDataType[]) => {
    this.dataSource.data = data;
  }
}

Example:
StackBlitz

React setState not updating state

Using async/await

async changeHandler(event) {
    await this.setState({ yourName: event.target.value });
    console.log(this.state.yourName);
}

How to add anchor tags dynamically to a div in Javascript?

I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul>, you can do this:

$("div#id").append('<ul>');
var ul = $("div#id > ul");

ul.append('<li><a href="' + url + '">' + text + '</a></li>');

How to set ChartJS Y axis title?

For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067

For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so

Chart.types.Line.extend({
    name: "LineAlt",
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var ctx = this.chart.ctx;
        ctx.save();
        // text alignment and color
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.fillStyle = this.options.scaleFontColor;
        // position
        var x = this.scale.xScalePaddingLeft * 0.4;
        var y = this.chart.height / 2;
        // change origin
        ctx.translate(x, y);
        // rotate text
        ctx.rotate(-90 * Math.PI / 180);
        ctx.fillText(this.datasets[0].label, 0, 0);
        ctx.restore();
    }
});

calling it like this

var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
    // make enough space on the right side of the graph
    scaleLabel: "          <%=value%>"
});

Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals


Fiddle - http://jsfiddle.net/wyox23ga/


enter image description here

Get element from within an iFrame

Below code will help you to find out iframe data.

let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;

Importing a Maven project into Eclipse from Git

Instead of constantly generating project metadata via import->maven command, you can generate your project metadata once and the place it in your git repository along with the rest of your source code. After than, using import->git command will import a proper maven-enabled project, assuming you have maven tools installed.

Make sure to place into the source control system all files in project dir that start with '.' such as .classpath and .project along with the entire contents of the .settings directory.

Rails 4 LIKE query - ActiveRecord adds quotes

Try

 def self.search(search, page = 1 )
    paginate :per_page => 5, :page => page,
      :conditions => ["name LIKE  ? OR postal_code like ?", "%#{search}%","%#{search}%"],   order => 'name'
  end

See the docs on AREL conditions for more info.

How to reshape data from long to wide format

Using base R aggregate function:

aggregate(value ~ name, dat1, I)

# name           value.1  value.2  value.3  value.4
#1 firstName      0.4145  -0.4747   0.0659   -0.5024
#2 secondName    -0.8259   0.1669  -0.8962    0.1681

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

How can I make XSLT work in chrome?

I started testing this and ran into the local file / Chrome security issue. A very simple workaround is put the XML and XSL file in, say, Dropbox public folder and get links to both files. Put the link to the XSL transform in the XML head. Use the XML link in Chrome AND IT WORKS!

C# Double - ToString() formatting with two decimal places but no rounding

The following rounds the numbers, but only shows up to 2 decimal places (removing any trailing zeros), thanks to .##.

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case the reason was since the remote repo artifact (non-central) had dependencies from the Maven Central in the .pom file, and the older version of mvn (older than 3.6.0) was used. So, it tried to check the Maven Central artifacts mentioned in the remote repo's .pom for the specific artifact I've added to my dependencies and faced the Maven Central http access issue behind the scenes (I believe the same as described there: Maven dependencies are failing with a 501 error - that is about using https access to Maven Central by default and prohibiting the http access).

Using more recent Maven (from 3.1 to 3.6.0) made it use https to check Maven Central repo dependencies mentioned in the .pom files of the remote repositories and I no longer face the issue.

How to store token in Local or Session Storage in Angular 2?

Adding onto Bojan Kogoj's answer:

In your app.module.ts, add a new provider for storage.

@NgModule({
   providers: [
      { provide: Storage, useValue: localStorage }
   ],
   imports:[],
   declarations:[]
})

And then you can use DI to get it wherever you need it.

 @Injectable({
    providedIn:'root'
 })
 export class StateService {
    constructor(private storage: Storage) { }
 }

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

Protip: Testing json on a local Node.js server? Make sure you don't already have something routing to that path

'/:url(app|assets|stuff|etc)';

C# - Print dictionary

More cleaner way using LINQ

var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);

Set value of hidden field in a form using jQuery's ".val()" doesn't work

$('input[name=hidden_field_name]').val('newVal');

worked for me, when neither

$('input[id=hidden_field_id]').val('newVal');

nor

$('#hidden_field_id').val('newVal');

did.

HTML5 Number Input - Always show 2 decimal places

Take a look at this:

 <input type="number" step="0.01" />

Using npm behind corporate proxy .pac

You can check Fiddler if NPM is giving Authentication error. It is easy to install and configure. Set Fiddler Rule to Automatically Authenticated.In .npmrc set these properties

registry=http://registry.npmjs.org
proxy=http://127.0.0.1:8888
https-proxy=http://127.0.0.1:8888
http-proxy=http://127.0.0.1:8888
strict-ssl=false

It worked for me :)

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Send JSON data from Javascript to PHP?

using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.

Chrome: Uncaught SyntaxError: Unexpected end of input

Trying to parse an empty JSON can be the cause of this error.

When you receive a response from the server or whatever, check first if it's not empty. For example:

function parseJSON(response) {
    if (response.status === 204 || response.status === 205) {
        return null;
    }
    return response.json();
}

Then you can fetch with:

fetch(url, options).then(parseJSON); 

how to convert JSONArray to List of Object using camel-jackson

I had similar json response coming from client. Created one main list class, and one POJO class.

Call a url from javascript

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

what is the difference between const_iterator and iterator?

if you have a list a and then following statements

list<int>::iterator it; // declare an iterator
    list<int>::const_iterator cit; // declare an const iterator 
    it=a.begin();
    cit=a.begin();

you can change the contents of the element in the list using “it” but not “cit”, that is you can use “cit” for reading the contents not for updating the elements.

*it=*it+1;//returns no error
    *cit=*cit+1;//this will return error

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

How to force div to appear below not next to another?

what u can also do i place an extra "dummy" div before your last div.

Make it 1 px heigh and the width as much needed to cover the container div/body

This will make the last div appear under it, starting from the left.

Pass Javascript Array -> PHP

You can transfer array from javascript to PHP...

Javascript... ArraySender.html

<script language="javascript">

//its your javascript, your array can be multidimensional or associative

plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info'; 
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3'; 
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4'; 
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5'; 

function convertJsArr2Php(JsArr){
    var Php = '';
    if (Array.isArray(JsArr)){  
        Php += 'array(';
        for (var i in JsArr){
            Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
            if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
                Php += ', ';
            }
        }
        Php += ')';
        return Php;
    }
    else{
        return '\'' + JsArr + '\'';
    }
}


function ajaxPost(str, plArrayC){
    var xmlhttp;
    if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
    else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
    xmlhttp.open("POST",str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send('Array=' + plArrayC);
}

ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>

and PHP Code... ArrayReader.php

<?php 

eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);

?>

How do you properly determine the current script directory?

First.. a couple missing use-cases here if we're talking about ways to inject anonymous code..

code.compile_command()
code.interact()
imp.load_compiled()
imp.load_dynamic()
imp.load_module()
__builtin__.compile()
loading C compiled shared objects? example: _socket?)

But, the real question is, what is your goal - are you trying to enforce some sort of security? Or are you just interested in whats being loaded.

If you're interested in security, the filename that is being imported via exec/execfile is inconsequential - you should use rexec, which offers the following:

This module contains the RExec class, which supports r_eval(), r_execfile(), r_exec(), and r_import() methods, which are restricted versions of the standard Python functions eval(), execfile() and the exec and import statements. Code executed in this restricted environment will only have access to modules and functions that are deemed safe; you can subclass RExec add or remove capabilities as desired.

However, if this is more of an academic pursuit.. here are a couple goofy approaches that you might be able to dig a little deeper into..

Example scripts:

./deep.py

print ' >> level 1'
execfile('deeper.py')
print ' << level 1'

./deeper.py

print '\t >> level 2'
exec("import sys; sys.path.append('/tmp'); import deepest")
print '\t << level 2'

/tmp/deepest.py

print '\t\t >> level 3'
print '\t\t\t I can see the earths core.'
print '\t\t << level 3'

./codespy.py

import sys, os

def overseer(frame, event, arg):
    print "loaded(%s)" % os.path.abspath(frame.f_code.co_filename)

sys.settrace(overseer)
execfile("deep.py")
sys.exit(0)

Output

loaded(/Users/synthesizerpatel/deep.py)
>> level 1
loaded(/Users/synthesizerpatel/deeper.py)
    >> level 2
loaded(/Users/synthesizerpatel/<string>)
loaded(/tmp/deepest.py)
        >> level 3
            I can see the earths core.
        << level 3
    << level 2
<< level 1

Of course, this is a resource-intensive way to do it, you'd be tracing all your code.. Not very efficient. But, I think it's a novel approach since it continues to work even as you get deeper into the nest. You can't override 'eval'. Although you can override execfile().

Note, this approach only coveres exec/execfile, not 'import'. For higher level 'module' load hooking you might be able to use use sys.path_hooks (Write-up courtesy of PyMOTW).

Thats all I have off the top of my head.

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

how to set image from url for imageView

if you are making a RecyclerView and using an adapter, what worked for me was:

@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
    MODEL model = LIST.get(position);
    holder.TEXTVIEW.setText(service.getTitle());
    holder.TEXTVIEW.setText(service.getDesc());

    Context context = holder.IMAGEVIEW.getContext();
    Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}

how to add css class to html generic control div?

To add a class to a div that is generated via the HtmlGenericControl way you can use:

div1.Attributes.Add("class", "classname"); 

If you are using the Panel option, it would be:

panel1.CssClass = "classname";

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

It might mean the application is already installed for another user on your device. Users share applications. I don't know why they do but they do. So if one user updates an application is updated for the other user also. If you uninstall on one, it doesn't remove the app from the system on the other.

How to support UTF-8 encoding in Eclipse

Try this

  • 1) Window > Preferences > General > Content Types, set UTF-8 as the default encoding for all content types.

  • 2) Window > Preferences > General > Workspace, set Text file encoding to Other : UTF-8

How to select the first row for each group in MySQL?

Best performance and easy to use:

SELECT id, code,
SUBSTRING_INDEX( GROUP_CONCAT(price ORDER BY id DESC), ',', 1) first_found_price
FROM stocks
GROUP BY code
ORDER BY id DESC

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

How can I get the root domain URI in ASP.NET?

HttpContext.Current.Request.Url can get you all the info on the URL. And can break down the url into its fragments.

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

Selenium -- How to wait until page is completely loaded

It seems that you need to wait for the page to be reloaded before clicking on the "Add" button. In this case you could wait for the "Add Item" element to become stale before clicking on the reloaded element:

WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");

// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));

//trigger the reaload of the page
driver.findElement(By.id("...")).click();

// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));

// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();

'nuget' is not recognized but other nuget commands working

Nuget.exe is placed at .nuget folder of your project. It can't be executed directly in Package Manager Console, but is executed by Powershell commands because these commands build custom path for themselves.

My steps to solve are:


Update

NuGet can be easily installed in your project using the following command:

Install-Package NuGet.CommandLine

.prop('checked',false) or .removeAttr('checked')?

use checked : true, false property of the checkbox.

jQuery:

if($('input[type=checkbox]').is(':checked')) {
    $(this).prop('checked',true);
} else {
    $(this).prop('checked',false);
}

Change Circle color of radio button

There is an xml attribute for it:

android:buttonTint="yourcolor"

Is quitting an application frowned upon?

All of my applications have quit buttons... and I quite frequently get positive comments from users because of it. I don't care if the platform was designed in a fashion that applications shouldn't need them. Saying "don't put them there" is kind of ridiculous. If the user wants to quit... I provide them the access to do exactly that. I don't think it reduces how Android operates at all and seems like a good practice. I understand the life cycle... and my observation has been that Android doesn't do a good job at handling it.... and that is a basic fact.

How to implement common bash idioms in Python?

You can use python instead of bash with the ShellPy library.

Here is an example that downloads avatar of Python user from Github:

import json
import os
import tempfile

# get the api answer with curl
answer = `curl https://api.github.com/users/python
# syntactic sugar for checking returncode of executed process for zero
if answer:
    answer_json = json.loads(answer.stdout)
    avatar_url = answer_json['avatar_url']

    destination = os.path.join(tempfile.gettempdir(), 'python.png')

    # execute curl once again, this time to get the image
    result = `curl {avatar_url} > {destination}
    if result:
        # if there were no problems show the file
        p`ls -l {destination}
    else:
        print('Failed to download avatar')

    print('Avatar downloaded')
else:
    print('Failed to access github api')

As you can see, all expressions inside of grave accent ( ` ) symbol are executed in shell. And in Python code, you can capture results of this execution and perform actions on it. For example:

log = `git log --pretty=oneline --grep='Create'

This line will first execute git log --pretty=oneline --grep='Create' in shell and then assign the result to the log variable. The result has the following properties:

stdout the whole text from stdout of the executed process

stderr the whole text from stderr of the executed process

returncode returncode of the execution

This is general overview of the library, more detailed description with examples can be found here.

Swift convert unix time to date and time

You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:

let date = NSDate(timeIntervalSince1970: 1415637900)

How do I add an existing Solution to GitHub from Visual Studio 2013

  • From the Team Explorer menu click "add" under the Git repository section (you'll need to add the solution directory to the Local Git Repository)
  • Open the solution from Team Explorer (right click on the added solution - open)
  • Click on the commit button and look for the link "push"

Visual Studio should now ask your GitHub credentials and then proceed to upload your solution.

Since I have my Windows account connected to Visual Studio to work with Team Foundation I don't know if it works without an account, Visual Studio will keep track of who commits so if you are not logged in it will probably ask you to first.

How to send an email with Gmail as provider using Python?

I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

enter image description here

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

Fastest JSON reader/writer for C++

http://lloyd.github.com/yajl/

http://www.digip.org/jansson/

Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)

map function for objects (instead of arrays)

EDIT: The canonical way using newer JavaScript features is -

const identity = x =>
  x

const omap = (f = identity, o = {}) =>
  Object.fromEntries(
    Object.entries(o).map(([ k, v ]) =>
      [ k, f(v) ]
    )
  )

Where o is some object and f is your mapping function. Or we could say, given a function from a -> b, and an object with values of type a, produce an object with values of type b. As a pseudo type signature -

// omap : (a -> b, { a }) -> { b }

The original answer was written to demonstrate a powerful combinator, mapReduce which allows us to think of our transformation in a different way

  1. m, the mapping function – gives you a chance to transform the incoming element before…
  2. r, the reducing function – this function combines the accumulator with the result of the mapped element

Intuitively, mapReduce creates a new reducer we can plug directly into Array.prototype.reduce. But more importantly, we can implement our object functor implementation omap plainly by utilizing the object monoid, Object.assign and {}.

_x000D_
_x000D_
const identity = x =>_x000D_
  x_x000D_
  _x000D_
const mapReduce = (m, r) =>_x000D_
  (a, x) => r (a, m (x))_x000D_
_x000D_
const omap = (f = identity, o = {}) =>_x000D_
  Object_x000D_
    .keys (o)_x000D_
    .reduce_x000D_
      ( mapReduce_x000D_
          ( k => ({ [k]: f (o[k]) })_x000D_
          , Object.assign_x000D_
          )_x000D_
      , {}_x000D_
      )_x000D_
          _x000D_
const square = x =>_x000D_
  x * x_x000D_
  _x000D_
const data =_x000D_
  { a : 1, b : 2, c : 3 }_x000D_
  _x000D_
console .log (omap (square, data))_x000D_
// { a : 1, b : 4, c : 9 }
_x000D_
_x000D_
_x000D_

Notice the only part of the program we actually had to write is the mapping implementation itself –

k => ({ [k]: f (o[k]) })

Which says, given a known object o and some key k, construct an object and whose computed property k is the result of calling f on the key's value, o[k].

We get a glimpse of mapReduce's sequencing potential if we first abstract oreduce

// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
  Object
    .keys (o)
    .reduce
      ( mapReduce
          ( k => [ k, o[k] ]
          , f
          )
      , r
      )

// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
  oreduce
    ( mapReduce
        ( ([ k, v ]) =>
            ({ [k]: f (v) })
        , Object.assign
        )
    , {}
    , o
    )

Everything works the same, but omap can be defined at a higher-level now. Of course the new Object.entries makes this look silly, but the exercise is still important to the learner.

You won't see the full potential of mapReduce here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.

OWIN Startup Class Missing

Have a look for the Startup.cs file, you might be missing one of these. This file is the entry point for OWIN, so it sounds like this is missing. Take a look at OWIN Startup class here to understand whats going on.

As your error specifies, you can disable this in the web.config by doing the following...

To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config

#1071 - Specified key was too long; max key length is 767 bytes

The answer about why you get error message was already answered by many users here. My answer is about how to fix and use it as it be.

Refer from this link.

  1. Open MySQL client (or MariaDB client). It is a command line tool.
  2. It will ask your password, enter your correct password.
  3. Select your database by using this command use my_database_name;

Database changed

  1. set global innodb_large_prefix=on;

Query OK, 0 rows affected (0.00 sec)

  1. set global innodb_file_format=Barracuda;

Query OK, 0 rows affected (0.02 sec)

  1. Go to your database on phpMyAdmin or something like that for easy management. > Select database > View table structure > Go to Operations tab. > Change ROW_FORMAT to DYNAMIC and save changes.
  2. Go to table's structure tab > Click on Unique button.
  3. Done. Now it should has no errors.

The problem of this fix is if you export db to another server (for example from localhost to real host) and you cannot use MySQL command line in that server. You cannot make it work there.

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

What is Ruby's double-colon `::`?

Surprisingly, all 10 answers here say the same thing. The '::' is a namespace resolution operator, and yes it is true. But there is one gotcha that you have to realize about the namespace resolution operator when it comes to the constant lookup algorithm. As Matz delineates in his book, 'The Ruby Programming Language', constant lookup has multiple steps. First, it searches a constant in the lexical scope where the constant is referenced. If it does not find the constant within the lexical scope, it then searches the inheritance hierarchy. Because of this constant lookup algorithm, below we get the expected results:

module A
  module B
      PI = 3.14
      module C
        class E
          PI = 3.15
        end
        class F < E
          def get_pi
            puts PI
          end
        end
      end
  end
end
f = A::B::C::F.new
f.get_pi
> 3.14

While F inherits from E, the B module is within the lexical scope of F. Consequently, F instances will refer to the constant PI defined in the module B. Now if module B did not define PI, then F instances will refer to the PI constant defined in the superclass E.

But what if we were to use '::' rather than nesting modules? Would we get the same result? No!

By using the namespace resolution operator when defining nested modules, the nested modules and classes are no longer within the lexical scope of their outer modules. As you can see below, PI defined in A::B is not in the lexical scope of A::B::C::D and thus we get uninitialized constant when trying to refer to PI in the get_pi instance method:

module A
end

module A::B
  PI = 3.14
end

module A::B::C
  class D
    def get_pi
      puts PI
    end
  end
end
d = A::B::C::D.new
d.get_pi
NameError: uninitialized constant A::B::C::D::PI
Did you mean?  A::B::PI

How to search and replace text in a file?

My variant, one word at a time on the entire file.

I read it into memory.

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)

C# : Converting Base Class to Child Class

You can copy value of Parent Class to a Child class. For instance, you could use reflection if that is the case.

Mocha / Chai expect.to.throw not catching thrown errors

You have to pass a function to expect. Like this:

expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));

The way you are doing it, you are passing to expect the result of calling model.get('z'). But to test whether something is thrown, you have to pass a function to expect, which expect will call itself. The bind method used above creates a new function which when called will call model.get with this set to the value of model and the first argument set to 'z'.

A good explanation of bind can be found here.

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

following this link:

How To: Eclipse Maven install build jar with dependencies

i found out that this is not workable solution because the class loader doesn't load jars from within jars, so i think that i will unpack the dependencies inside the jar.

Staging Deleted files

Since Git 2.0.0, git add will also stage file deletions.

Git 2.0.0 Docs - git-add

< pathspec >…

Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to update the index to match the current state of the directory as a whole (e.g. specifying dir will record not just a file dir/file1 modified in the working tree, a file dir/file2 added to the working tree, but also a file dir/file3 removed from the working tree. Note that older versions of Git used to ignore removed files; use --no-all option if you want to add modified or new files but ignore removed ones.

Absolute vs relative URLs

In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

Java math function to convert positive int to negative and negative to positive?

x = -x;

This is probably the most trivial question I have ever seen anywhere.

... and why you would call this trivial function 'reverse()' is another mystery.

Neatest way to remove linebreaks in Perl

To extend Ted Cambron's answer above and something that hasn't been addressed here: If you remove all line breaks indiscriminately from a chunk of entered text, you will end up with paragraphs running into each other without spaces when you output that text later. This is what I use:

sub cleanLines{

    my $text = shift;

    $text =~ s/\r/ /; #replace \r with space
    $text =~ s/\n/ /; #replace \n with space
    $text =~ s/  / /g; #replace double-spaces with single space

    return $text;
}

The last substitution uses the g 'greedy' modifier so it continues to find double-spaces until it replaces them all. (Effectively substituting anything more that single space)

How to edit a text file in my terminal

If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).

If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").

Once the edition is done, hit ESC again, then type :wq to save your work or :q! to quit without saving.

For quick reference, here you have a text-based cheat sheet.

How to clear form after submit in Angular 2?

To angular version 4, you can use this:

this.heroForm.reset();

But, you could need a initial value like:

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

It is important to resolve null problem in your object reference.

reference link, Search for "reset the form flags".

With ng-bind-html-unsafe removed, how do I inject HTML?

For me, the simplest and most flexible solution is:

<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>

And add function to your controller:

$scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
}

Don't forget add $sce to your controller's initialization.

"Submit is not a function" error in JavaScript

You should use this code :

_x000D_
_x000D_
$(document).on("ready", function () {_x000D_
       _x000D_
        document.frmProduct.submit();_x000D_
    });
_x000D_
_x000D_
_x000D_

Spring Bean Scopes

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

What is the difference between Hibernate and Spring Data JPA

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

I would recommend to use w.r.t JPA as you can switch between different ORMS.

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

How to check if string contains Latin characters only?

All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:

if (!str.match(/^[\d]+$/)) {
    //contains other characters as well
}

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

How to import set of icons into Android Studio project

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

How to run Node.js as a background process and never die?

nohup node server.js > /dev/null 2>&1 &

  1. nohup means: Do not terminate this process even when the stty is cut off.
  2. > /dev/null means: stdout goes to /dev/null (which is a dummy device that does not record any output).
  3. 2>&1 means: stderr also goes to the stdout (which is already redirected to /dev/null). You may replace &1 with a file path to keep a log of errors, e.g.: 2>/tmp/myLog
  4. & at the end means: run this command as a background task.

Should I always use a parallel stream when possible?

Never parallelize an infinite stream with a limit. Here is what happens:

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
            IntStream.iterate(0, i -> i + 1)
                .parallel()
                .skip(1)
                .findFirst()
                .getAsInt());
    }

Result

    Exception in thread "main" java.lang.OutOfMemoryError
        at ...
        at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
        at InfiniteTest.main(InfiniteTest.java:24)
    Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
        at ...

Same if you use .limit(...)

Explanation here: Java 8, using .parallel in a stream causes OOM error

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

public static void main(String[] args) {
    // let's count to 1 in parallel
    System.out.println(
            IntStream.range(1, 1000_000_000)
                    .parallel()
                    .skip(100)
                    .findFirst()
                    .getAsInt());
}

This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

SQL server ignore case in a where expression

Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one:

SELECT balance FROM people WHERE email = '[email protected]'
  COLLATE SQL_Latin1_General_CP1_CI_AS 

How to configure Eclipse build path to use Maven dependencies?

Right click on the project Configure > convert to Maven project

Then you can see all the Maven related Menu for you project.

How can I install the Beautiful Soup module on the Mac?

sudo yum remove python-beautifulsoup

OR

sudo easy_install -m BeautifulSoup

can remove old version 3

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

My problem started after i changed the Target name.

My own custom UI classes had the Module name set to the old target name.

I changed the target name to the new one and it works fine now.

Programmatically find the number of cores on a machine

On Linux, you can read the /proc/cpuinfo file and count the cores.

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

Heroku: How to push different local Git branches to Heroku/master

You should check out heroku_san, it solves this problem quite nicely.

For example, you could:

git checkout BRANCH
rake qa deploy

It also makes it easy to spin up new Heroku instances to deploy a topic branch to new servers:

git checkout BRANCH
# edit config/heroku.yml with new app instance and shortname
rake shortname heroku:create deploy # auto creates deploys and migrates

And of course you can make simpler rake tasks if you do something frequently.

Overcoming "Display forbidden by X-Frame-Options"

Use this line given below instead of header() function.

echo "<script>window.top.location = 'https://apps.facebook.com/yourappnamespace/';</script>";

Quicksort with Python

Quicksort with Python

In real life, we should always use the builtin sort provided by Python. However, understanding the quicksort algorithm is instructive.

My goal here is to break down the subject such that it is easily understood and replicable by the reader without having to return to reference materials.

The quicksort algorithm is essentially the following:

  1. Select a pivot data point.
  2. Move all data points less than (below) the pivot to a position below the pivot - move those greater than or equal to (above) the pivot to a position above it.
  3. Apply the algorithm to the areas above and below the pivot

If the data are randomly distributed, selecting the first data point as the pivot is equivalent to a random selection.

Readable example:

First, let's look at a readable example that uses comments and variable names to point to intermediate values:

def quicksort(xs):
    """Given indexable and slicable iterable, return a sorted list"""
    if xs: # if given list (or tuple) with one ordered item or more: 
        pivot = xs[0]
        # below will be less than:
        below = [i for i in xs[1:] if i < pivot] 
        # above will be greater than or equal to:
        above = [i for i in xs[1:] if i >= pivot]
        return quicksort(below) + [pivot] + quicksort(above)
    else: 
        return xs # empty list

To restate the algorithm and code demonstrated here - we move values above the pivot to the right, and values below the pivot to the left, and then pass those partitions to same function to be further sorted.

Golfed:

This can be golfed to 88 characters:

q=lambda x:x and q([i for i in x[1:]if i<=x[0]])+[x[0]]+q([i for i in x[1:]if i>x[0]])

To see how we get there, first take our readable example, remove comments and docstrings, and find the pivot in-place:

def quicksort(xs):
    if xs: 
        below = [i for i in xs[1:] if i < xs[0]] 
        above = [i for i in xs[1:] if i >= xs[0]]
        return quicksort(below) + [xs[0]] + quicksort(above)
    else: 
        return xs

Now find below and above, in-place:

def quicksort(xs):
    if xs: 
        return (quicksort([i for i in xs[1:] if i < xs[0]] )
                + [xs[0]] 
                + quicksort([i for i in xs[1:] if i >= xs[0]]))
    else: 
        return xs

Now, knowing that and returns the prior element if false, else if it is true, it evaluates and returns the following element, we have:

def quicksort(xs):
    return xs and (quicksort([i for i in xs[1:] if i < xs[0]] )
                   + [xs[0]] 
                   + quicksort([i for i in xs[1:] if i >= xs[0]]))

Since lambdas return a single epression, and we have simplified to a single expression (even though it is getting more unreadable) we can now use a lambda:

quicksort = lambda xs: (quicksort([i for i in xs[1:] if i < xs[0]] )
                        + [xs[0]] 
                        + quicksort([i for i in xs[1:] if i >= xs[0]]))

And to reduce to our example, shorten the function and variable names to one letter, and eliminate the whitespace that isn't required.

q=lambda x:x and q([i for i in x[1:]if i<=x[0]])+[x[0]]+q([i for i in x[1:]if i>x[0]])

Note that this lambda, like most code golfing, is rather bad style.

In-place Quicksort, using the Hoare Partitioning scheme

The prior implementation creates a lot of unnecessary extra lists. If we can do this in-place, we'll avoid wasting space.

The below implementation uses the Hoare partitioning scheme, which you can read more about on wikipedia (but we have apparently removed up to 4 redundant calculations per partition() call by using while-loop semantics instead of do-while and moving the narrowing steps to the end of the outer while loop.).

def quicksort(a_list):
    """Hoare partition scheme, see https://en.wikipedia.org/wiki/Quicksort"""
    def _quicksort(a_list, low, high):
        # must run partition on sections with 2 elements or more
        if low < high: 
            p = partition(a_list, low, high)
            _quicksort(a_list, low, p)
            _quicksort(a_list, p+1, high)
    def partition(a_list, low, high):
        pivot = a_list[low]
        while True:
            while a_list[low] < pivot:
                low += 1
            while a_list[high] > pivot:
                high -= 1
            if low >= high:
                return high
            a_list[low], a_list[high] = a_list[high], a_list[low]
            low += 1
            high -= 1
    _quicksort(a_list, 0, len(a_list)-1)
    return a_list

Not sure if I tested it thoroughly enough:

def main():
    assert quicksort([1]) == [1]
    assert quicksort([1,2]) == [1,2]
    assert quicksort([1,2,3]) == [1,2,3]
    assert quicksort([1,2,3,4]) == [1,2,3,4]
    assert quicksort([2,1,3,4]) == [1,2,3,4]
    assert quicksort([1,3,2,4]) == [1,2,3,4]
    assert quicksort([1,2,4,3]) == [1,2,3,4]
    assert quicksort([2,1,1,1]) == [1,1,1,2]
    assert quicksort([1,2,1,1]) == [1,1,1,2]
    assert quicksort([1,1,2,1]) == [1,1,1,2]
    assert quicksort([1,1,1,2]) == [1,1,1,2]

Conclusion

This algorithm is frequently taught in computer science courses and asked for on job interviews. It helps us think about recursion and divide-and-conquer.

Quicksort is not very practical in Python since our builtin timsort algorithm is quite efficient, and we have recursion limits. We would expect to sort lists in-place with list.sort or create new sorted lists with sorted - both of which take a key and reverse argument.

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

define ANDROID_SDK_ROOT as environment variable where your SDK is residing, default path would be "C:\Program Files (x86)\Android\android-sdk" and restart computer to take effect.

Convert string to decimal number with 2 decimal places in Java

This line is your problem:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);

And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.

How to count duplicate value in an array in javascript

var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
// here we will collect only unique items from the array
var uniqueChars = [];

// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount, 
// put it into the uniqueChars array
  if (uniqueChars.indexOf(i) == -1) {
    uniqueChars.push(i);
  } 
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item 
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
  let letterAccumulator = 0;
  for (i of uniqueCount) {
    if (i == x) {letterAccumulator++;}
  }
  console.log(`${x} = ${letterAccumulator}`);
}

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

If Android Studio directly opening your project instead of setup window, then just close the windows of all projects. Now you will able to see the startup window. If SDK is missing then it will provide option to download SDK and other required tools.

It works for me.

Compare two objects in Java with possible null values

boolean compare(String str1, String str2) {
    if(str1==null || str2==null) {
        //return false; if you assume null not equal to null
        return str1==str2;
    }
    return str1.equals(str2);
}

is this what you desired?

Set icon for Android application

It's better to do this through Android Studio rather than the file browser as it updates all icon files with the correct resolution for each.

To do so go to menu File ? New ? Image Asset. This will open a new dialogue and then make sure Launcher Icons is selected (Which it is by default) and then browse to the directory of your icon (it doesn't have to be in the project resources) and then once selected make sure other settings are to your liking and hit done.

Now all resolutions are saved into their respective folders, and you don't have to worry about copying it yourself or using tools, etc.

Enter image description here

Don't forget "Shape - none" for a transparent background.

Please don't edit my answer without asking.

How to create a jQuery function (a new jQuery method or plugin)?

Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoring within the jquery docs.

Its worth noting that jquery is just javascript, so there is nothing special about a "jquery method".

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Your error states that cross-env is not installed.

'cross-env' is not recognized as an internal or external command, operable program or batch file.

You just need to run

npm install cross-env

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00

Take multiple lists into dataframe

Just adding that using the first approach it can be done as -

pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))

Best Practices: working with long, multiline strings in PHP?

Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.

If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:

$text = "Hello, {$vars->name},\r\n\r\n"
    . "The second line starts two lines below.\r\n"
    . ".. Third line... etc";

This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

How can I pipe stderr, and not stdout?

In Bash, you can also redirect to a subshell using process substitution:

command > >(stdlog pipe)  2> >(stderr pipe)

For the case at hand:

command 2> >(grep 'something') >/dev/null

How to document Python code using Doxygen

The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.

How does Google calculate my location on a desktop?

According to Google Maps' own help:
If your browser cannot show images, get a new one!

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

How do we change the URL of a working GitLab install?

GitLab Omnibus

For an Omnibus install, it is a little different.

The correct place in an Omnibus install is:

/etc/gitlab/gitlab.rb
    external_url 'http://gitlab.example.com'

Finally, you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart so the changes apply.


I was making changes in the wrong places and they were getting blown away.

The incorrect paths are:

/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf

Pay attention to those warnings that read:

# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I used Laravel 8, This is my solution

Goto: storage/framework/cache/data
set permission directory data is 777

It's worked for me

Export a list into a CSV or TXT file in R

I export lists into YAML format with CPAN YAML package.

l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")

Bonus of YAML that it's a human readable text format so it's easy to read/share/import/etc

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Recursive mkdir() system call on Unix

I'm not allowed to comment on the first (and accepted) answer (not enough rep), so I'll post my comments as code in a new answer. The code below is based on the first answer, but fixes a number of problems:

  • If called with a zero-length path, this does not read or write the character before the beginning of array opath[] (yes, "why would you call it that way?", but on the other hand "why would you not fix the vulnerability?")
  • the size of opath is now PATH_MAX (which isn't perfect, but is better than a constant)
  • if the path is as long as or longer than sizeof(opath) then it is properly terminated when copied (which strncpy() doesn't do)
  • you can specify the mode of the written directory, just as you can with the standard mkdir() (although if you specify non-user-writeable or non-user-executable then the recursion won't work)
  • main() returns the (required?) int
  • removed a few unnecessary #includes
  • I like the function name better ;)
// Based on http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>

static void mkdirRecursive(const char *path, mode_t mode) {
    char opath[PATH_MAX];
    char *p;
    size_t len;

    strncpy(opath, path, sizeof(opath));
    opath[sizeof(opath) - 1] = '\0';
    len = strlen(opath);
    if (len == 0)
        return;
    else if (opath[len - 1] == '/')
        opath[len - 1] = '\0';
    for(p = opath; *p; p++)
        if (*p == '/') {
            *p = '\0';
            if (access(opath, F_OK))
                mkdir(opath, mode);
            *p = '/';
        }
    if (access(opath, F_OK))         /* if path is not terminated with / */
        mkdir(opath, mode);
}


int main (void) {
    mkdirRecursive("/Users/griscom/one/two/three", S_IRWXU);
    return 0;
}

Where IN clause in LINQ

public List<State> GetcountryCodeStates(List<string> countryCodes)
{
    List<State> states = new List<State>();
    states = (from a in _objdatasources.StateList.AsEnumerable()
    where countryCodes.Any(c => c.Contains(a.CountryCode))
    select a).ToList();
    return states;
}

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

php - get numeric index of associative array


  $a = array(
      'blue' => 'nice',
      'car' => 'fast',
      'number' => 'none'
  );  
var_dump(array_search('car', array_keys($a)));
var_dump(array_search('blue', array_keys($a)));
var_dump(array_search('number', array_keys($a)));

Build Step Progress Bar (css and jquery)

What I would do is use the same trick often use for hovering on buttons. Prepare an image that has 2 parts: (1) a top half which is greyed out, meaning incomplete, and (2) a bottom half which is colored in, meaning completed. Use the same image 4 times to make up the 4 steps of the progress bar, and align top for incomplete steps, and align bottom for incomplete steps.

In order to take advantage of image alignment, you'd have to use the image as the background for 4 divs, rather than using the img element.

This is the CSS for background image alignment:

div.progress-incomplete {
  background-position: top;
}
div.progress-finished {
  background-position: bottom;
}

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

How do I remove packages installed with Python's easy_install?

To uninstall an .egg you need to rm -rf the egg (it might be a directory) and remove the matching line from site-packages/easy-install.pth

Bootstrap table without stripe / borders

I expanded the Bootstrap table styles as Davide Pastore did, but with that method the styles are applied to all child tables as well, and they don't apply to the footer.

A better solution would be imitating the core Bootstrap table styles, but with your new class:

.table-borderless>thead>tr>th
.table-borderless>thead>tr>td
.table-borderless>tbody>tr>th
.table-borderless>tbody>tr>td
.table-borderless>tfoot>tr>th
.table-borderless>tfoot>tr>td {
    border: none;
}

Then when you use <table class='table table-borderless'> only the specific table with the class will be bordered, not any table in the tree.

Whether a variable is undefined

function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

How do I define and use an ENUM in Objective-C?

With current projects you may want to use the NS_ENUM() or NS_OPTIONS() macros.

typedef NS_ENUM(NSUInteger, PlayerState) {
        PLAYER_OFF,
        PLAYER_PLAYING,
        PLAYER_PAUSED
    };

Adding a newline into a string in C#

Use Environment.NewLine whenever you want in any string. An example:

string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";

text = text.Replace("@", "@" + System.Environment.NewLine);

How do you set the document title in React?

You can use the following below with document.title = 'Home Page'

import React from 'react'
import { Component } from 'react-dom'


class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

or You can use this npm package npm i react-document-title

import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';


class App extends Component{


  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Happy Coding!!!

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

Extracting text from HTML file using Python

Here is a version of xperroni's answer which is a bit more complete. It skips script and style sections and translates charrefs (e.g., &#39;) and HTML entities (e.g., &amp;).

It also includes a trivial plain-text-to-html inverse converter.

"""
HTML <-> text conversions.
"""
from HTMLParser import HTMLParser, HTMLParseError
from htmlentitydefs import name2codepoint
import re

class _HTMLToText(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self._buf = []
        self.hide_output = False

    def handle_starttag(self, tag, attrs):
        if tag in ('p', 'br') and not self.hide_output:
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = True

    def handle_startendtag(self, tag, attrs):
        if tag == 'br':
            self._buf.append('\n')

    def handle_endtag(self, tag):
        if tag == 'p':
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = False

    def handle_data(self, text):
        if text and not self.hide_output:
            self._buf.append(re.sub(r'\s+', ' ', text))

    def handle_entityref(self, name):
        if name in name2codepoint and not self.hide_output:
            c = unichr(name2codepoint[name])
            self._buf.append(c)

    def handle_charref(self, name):
        if not self.hide_output:
            n = int(name[1:], 16) if name.startswith('x') else int(name)
            self._buf.append(unichr(n))

    def get_text(self):
        return re.sub(r' +', ' ', ''.join(self._buf))

def html_to_text(html):
    """
    Given a piece of HTML, return the plain text it contains.
    This handles entities and char refs, but not javascript and stylesheets.
    """
    parser = _HTMLToText()
    try:
        parser.feed(html)
        parser.close()
    except HTMLParseError:
        pass
    return parser.get_text()

def text_to_html(text):
    """
    Convert the given text to html, wrapping what looks like URLs with <a> tags,
    converting newlines to <br> tags and converting confusing chars into html
    entities.
    """
    def f(mo):
        t = mo.group()
        if len(t) == 1:
            return {'&':'&amp;', "'":'&#39;', '"':'&quot;', '<':'&lt;', '>':'&gt;'}.get(t)
        return '<a href="%s">%s</a>' % (t, t)
    return re.sub(r'https?://[^] ()"\';]+|[&\'"<>]', f, text)

How to sort the letters in a string alphabetically in Python

>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']

sorted returns a list, so you can make it a string again using join:

>>> c = ''.join(b)

which joins the items of b together with an empty string '' in between each item.

>>> print c
'ENOVWZ'

How to print the values of slices

If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]), here's a code example showing how to do that:

package main

import (
    "fmt"
    "strings"
)

func main() {
    test := []string{"one", "two", "three"}     // The slice of data
    semiformat := fmt.Sprintf("%q\n", test)     // Turn the slice into a string that looks like ["one" "two" "three"]
    tokens := strings.Split(semiformat, " ")    // Split this string by spaces
    fmt.Printf(strings.Join(tokens, ", "))      // Join the Slice together (that was split by spaces) with commas
}

Go Playground

How to add element to C++ array?

Use a vector:

#include <vector>

void foo() {
    std::vector <int> v;
    v.push_back( 1 );       // equivalent to v[0] = 1
}

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

Note that Matt's code will result in an extra comma at the end of the string; using COALESCE (or ISNULL for that matter) as shown in the link in Lance's post uses a similar method but doesn't leave you with an extra comma to remove. For the sake of completeness, here's the relevant code from Lance's link on sqlteam.com:

DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
    CAST(EmpUniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

How to normalize a 2-dimensional numpy array in python less verbose?

In case you are trying to normalize each row such that its magnitude is one (i.e. a row's unit length is one or the sum of the square of each element in a row is one):

import numpy as np

a = np.arange(0,27,3).reshape(3,3)

result = a / np.linalg.norm(a, axis=-1)[:, np.newaxis]
# array([[ 0.        ,  0.4472136 ,  0.89442719],
#        [ 0.42426407,  0.56568542,  0.70710678],
#        [ 0.49153915,  0.57346234,  0.65538554]])

Verifying:

np.sum( result**2, axis=-1 )
# array([ 1.,  1.,  1.]) 

How to get Android GPS location

Give it a try :

public LatLng getLocation()
    {
     // Get the location manager
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
     Criteria criteria = new Criteria();
     String bestProvider = locationManager.getBestProvider(criteria, false);
     Location location = locationManager.getLastKnownLocation(bestProvider);
     Double lat,lon;
     try {
       lat = location.getLatitude ();
       lon = location.getLongitude ();
       return new LatLng(lat, lon);
     }
     catch (NullPointerException e){
         e.printStackTrace();
       return null;
     }
    }

How to check task status in Celery?

Old question but I recently ran into this problem.

If you're trying to get the task_id you can do it like this:

import celery
from celery_app import add
from celery import uuid

task_id = uuid()
result = add.apply_async((2, 2), task_id=task_id)

Now you know exactly what the task_id is and can now use it to get the AsyncResult:

# grab the AsyncResult 
result = celery.result.AsyncResult(task_id)

# print the task id
print result.task_id
09dad9cf-c9fa-4aee-933f-ff54dae39bdf

# print the AsyncResult's status
print result.status
SUCCESS

# print the result returned 
print result.result
4

how to instanceof List<MyType>?

    if (list instanceof List && ((List) list).stream()
                                             .noneMatch((o -> !(o instanceof MyType)))) {}

How do I set an absolute include path in PHP?

Not directly answering your question but something to remember:

When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.

from: http://us2.php.net/manual/en/function.include.php#84052

Equivalent of Oracle's RowID in SQL Server

if you just want basic row numbering for a small dataset, how about someting like this?

SELECT row_number() OVER (order by getdate()) as ROWID, * FROM Employees

python BeautifulSoup parsing table

Updated Answer

If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html.

Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries

Then following codes does the job perfectly (No need of beautifulsoup and fancy html):

import pandas as pd
import requests

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()

Output

First five lines of the table from the Website

Pythonic way to combine FOR loop and IF statement

As per The Zen of Python (if you are wondering whether your code is "Pythonic", that's the place to go):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Flat is better than nested.
  • Readability counts.

The Pythonic way of getting the sorted intersection of two sets is:

>>> sorted(set(a).intersection(xyz))
[0, 4, 6, 7, 9]

Or those elements that are xyz but not in a:

>>> sorted(set(xyz).difference(a))
[12, 242]

But for a more complicated loop you may want to flatten it by iterating over a well-named generator expression and/or calling out to a well-named function. Trying to fit everything on one line is rarely "Pythonic".


Update following additional comments on your question and the accepted answer

I'm not sure what you are trying to do with enumerate, but if a is a dictionary, you probably want to use the keys, like this:

>>> a = {
...     2: 'Turtle Doves',
...     3: 'French Hens',
...     4: 'Colly Birds',
...     5: 'Gold Rings',
...     6: 'Geese-a-Laying',
...     7: 'Swans-a-Swimming',
...     8: 'Maids-a-Milking',
...     9: 'Ladies Dancing',
...     0: 'Camel Books',
... }
>>>
>>> xyz = [0, 12, 4, 6, 242, 7, 9]
>>>
>>> known_things = sorted(set(a.iterkeys()).intersection(xyz))
>>> unknown_things = sorted(set(xyz).difference(a.iterkeys()))
>>>
>>> for thing in known_things:
...     print 'I know about', a[thing]
...
I know about Camel Books
I know about Colly Birds
I know about Geese-a-Laying
I know about Swans-a-Swimming
I know about Ladies Dancing
>>> print '...but...'
...but...
>>>
>>> for thing in unknown_things:
...     print "I don't know what happened on the {0}th day of Christmas".format(thing)
...
I don't know what happened on the 12th day of Christmas
I don't know what happened on the 242th day of Christmas

How do I get the current username in .NET using C#?

In case it's helpful to others, when I upgraded an app from c#.net 3.5 app to Visual Studio 2017 this line of code User.Identity.Name.Substring(4); threw this error "startIndex cannot be larger than length of string" (it didn't baulk before).

It was happy when I changed it to System.Security.Principal.WindowsIdentity.GetCurrent().Name however I ended up using Environment.UserName; to get the logged in Windows user and without the domain portion.

Specify an SSH key for git push for a given domain

As someone else mentioned, core.sshCommand config can be used to override SSH key and other parameters.

Here is an exmaple where you have an alternate key named ~/.ssh/workrsa and want to use it for all repositories cloned under ~/work.

  1. Create a new .gitconfig file under ~/work:
[core]
  sshCommand = "ssh -i ~/.ssh/workrsa"
  1. In your global git config ~/.gitconfig, add:
[includeIf "gitdir:~/work/"]
  path = ~/work/.gitconfig

Android Studio doesn't recognize my device

I am sorry that i bothered you all. The problem was my device is cloned in different places in device manager. It was gone when I tried to update driver for my phone in "Other devices" list, and before i have been updating it in wrong sections. Thank you all.

Better way to represent array in java properties file

Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/

You can have multiple values against a key as in key=value1,value2 and you can read this into an array as configuration.getAsStringArray("key")

How to set default values in Rails?

In Ruby on Rails v3.2.8, using the after_initialize ActiveRecord callback, you can call a method in your model that will assign the default values for a new object.

after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well (see ActiveRecord Callbacks).

So, IMO it should look something like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    # required to check an attribute for existence to weed out existing records
    self.bar = default_value unless self.attribute_whose_presence_has_been_validated
  end
end

Foo.bar = default_value for this instance unless the instance contains an attribute_whose_presence_has_been_validated previously on save/update. The default_value will then be used in conjunction with your view to render the form using the default_value for the bar attribute.

At best this is hacky...

EDIT - use 'new_record?' to check if instantiating from a new call

Instead of checking an attribute value, use the new_record? built-in method with rails. So, the above example should look like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo, if: 'new_record?'
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    self.bar = default_value
  end
end

This is much cleaner. Ah, the magic of Rails - it's smarter than me.

How to resize a VirtualBox vmdk file

Throw it away and start again. Ignore all these answers - don't waste your time.

Return Index of an Element in an Array Excel VBA

Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.

Function array_return_index(arr As Variant, val As Variant, Optional array_start_at_zero As Boolean = True) As Variant

Dim pos
pos = Application.Match(val, arr, False)

If Not IsError(pos) Then
    If array_start_at_zero = True Then
        pos = pos - 1
        'initializing array at 0
    End If
   array_return_index = pos
Else
   array_return_index = False
End If

End Function

Sub array_return_index_test()
Dim pos, arr, val

arr = Array(1, 2, 4, 5)
val = 1

'When array starts at zero
pos = array_return_index(arr, val)
If IsNumeric(pos) Then
MsgBox "Array starting at 0; Value found at : " & pos
Else
MsgBox "Not found"
End If

'When array starts at one
pos = array_return_index(arr, val, False)
If IsNumeric(pos) Then
MsgBox "Array starting at 1; Value found at : " & pos
Else
MsgBox "Not found"
End If



End Sub

What is a NullPointerException, and how do I fix it?

A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.

In general, it's because something hasn't been initialized properly.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

Add the following dependency in your pom.xml file and if you are using IntelliJ then add the same jars to WEB-INF->lib folder.... path is Project Structure -> Atrifacts -> Select jar from Available Elements pane and double click. It will add to respective folder

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>3.0.1.RELEASE</version>
</dependency>

Java: Check the date format of current string is according to required format or not

Here's a simple method:

public static boolean checkDatePattern(String padrao, String data) {
    try {
        SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
        format.parse(data);
        return true;
    } catch (ParseException e) {
        return false;
    }
}

How to get the index of an item in a list in a single step?

That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.

Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...

private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
    cb.DisplayMember = "Name";
    cb.ValueMember = "ItemCode";
    cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();

    if (!string.IsNullOrEmpty(defVal))
    {
        var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
        if (i>=0) cb.SelectedIndex = i;
    }
}

How to switch databases in psql?

You can connect to a database with \c <database> or \connect <database>.

What does ||= (or-equals) mean in Ruby?

a ||= b

is equivalent to

a || a = b

and not

a = a || b

because of the situation where you define a hash with a default (the hash will return the default for any undefined keys)

a = Hash.new(true) #Which is: {}

if you use:

a[10] ||= 10 #same as a[10] || a[10] = 10

a is still:

{}

but when you write it like so:

a[10] = a[10] || 10

a becomes:

{10 => true}

because you've assigned the value of itself at key 10, which defaults to true, so now the hash is defined for the key 10, rather than never performing the assignment in the first place.

MySQL Creating tables with Foreign Keys giving errno: 150

I encountered the same problem, but I check find that I hadn't the parent table. So I just edit the parent migration in front of the child migration. Just do it.

How to concatenate strings in twig

{{ ['foo', 'bar'|capitalize]|join }}

As you can see this works with filters and functions without needing to use set on a seperate line.

how to run a command at terminal from java program?

You need to run it using bash executable like this:

Runtime.getRuntime().exec("/bin/bash -c your_command");

Update: As suggested by xav, it is advisable to use ProcessBuilder instead:

String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.

Create a view model class like this:

public class EmployeeAddViewModel
{
    public Employee employee { get; set; }
    public Dictionary<int, string> staffTypes { get; set; }
    // really? a 1-to-many for genders
    public Dictionary<int, string> genderTypes { get; set; }

    public EmployeeAddViewModel() { }
    public EmployeeAddViewModel(int id)
    {
        employee = someEntityContext.Employees
            .Where(e => e.ID == id).SingleOrDefault();

        // instantiate your dictionaries

        foreach(var staffType in someEntityContext.StaffTypes)
        {
            staffTypes.Add(staffType.ID, staffType.Type);
        }

        // repeat similar loop for gender types
    }
}

Controller:

[HttpGet]
public ActionResult Add()
{
    return View(new EmployeeAddViewModel());
}

[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
    if(ModelState.IsValid)
    {
        Employee.Add(vm.Employee);
        return View("Index"); // or wherever you go after successful add
    }

    return View(vm);
}

Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:

@Html.DropDownListFor(model => model.employee.staffTypeID,
    new SelectList(model.staffTypes, "ID", "Type"))

and similarly for the gender dropdown

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(model.genderTypes, "ID", "Gender"))

Update per comments

For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList... below, you would use your IEnumerable.

@Html.DropDownListFor(model => model.employee.genderID,
    new SelectList(new SelectList()
    {
        new { ID = 1, Gender = "Male" },
        new { ID = 2, Gender = "Female" }
    }, "ID", "Gender"))

Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:

ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1  | Gender     | 1         | Male        | male gender       | 1
2  | State      | 50        | Hawaii      | 50th state        | 1
3  | Gender     | 2         | Female      | female gender     | 1
4  | State      | 49        | Alaska      | 49th state        | 1
5  | OrderType  | 1         | Web         | online order      | 1

I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.

Hope this helps!

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

How to add an element to the beginning of an OrderedDict?

EDIT (2019-02-03) Note that the following answer only works on older versions of Python. More recently, OrderedDict has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.

I just wrote a subclass of OrderedDict in a project of mine for a similar purpose. Here's the gist.

Insertion operations are also constant time O(1) (they don't require you to rebuild the data structure), unlike most of these solutions.

>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])

Git Clone - Repository not found

As mentioned by others the error may occur if the url is wrong.

However, the error may also occur if the repo is a private repo and you do not have access or wrong credentials.

Instead of

git clone https://github.com/NAME/repo.git

try

git clone https://username:[email protected]/NAME/repo.git


You can also use

git clone https://[email protected]/NAME/repo.git

and git will prompt for the password (thanks to leanne for providing this hint in the comments).

How can I escape double quotes in XML attributes values?

A double quote character (") can be escaped as &quot;, but here's the rest of the story...

Double quote character must be escaped in this context:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need not be escaped in most contexts:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

RewriteEngine On

RewriteRule ^(wordpress)($|/) - [L]

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How copy data from Excel to a table using Oracle SQL Developer

It's not exactly copy and paste but you can import data from Excel using Oracle SQL Developer.

Navigate to the table you want to import the data into and click on the Data tab.

After clicking on the data tab you should notice a drop down that says Actions... indicating the position of the Data tab and Actions... drop down

Click Actions... and select the bottom option Import Data...

Then just follow the wizard to select the correct sheet, and columns that you want to import.

EDIT : To view the data tab :

  1. Select the SCHEMA where your table is created.(Choose from the Connections tab on the left pane).
  2. Right click on the SCHEMA and choose SCHEMA BROWSER.
  3. Select your table from the list (by giving your schema).
  4. Now you will see the DATA tab.
  5. Click on Actions and Import Data...

Spring Boot without the web server

You can create something like this:

@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).web(false).run(args);
  }
}

And

@Component
public class CommandLiner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    // Put your logic here
  }

}

The dependency is still there though but not used.

Change background color of R plot

I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")