Programs & Examples On #Phpfox

phpFox is a social networking platform created in PHP. This CMS is based on the MVC structure. Most of its functionality is similar to Facebook. It was founded by Raymond Benc in July 2005.

Eclipse Indigo - Cannot install Android ADT Plugin

I had the same problem. This helped for me:

  1. Go to Help->Install Software
  2. Click on "Available Software Sites"
  3. Click on Add: Name: "Helios" Location: "http://download.eclipse.org/releases/helios"
  4. Try to install Android Development Tools

How do I loop through a date range?

DateTime begindate = Convert.ToDateTime("01/Jan/2018");
DateTime enddate = Convert.ToDateTime("12 Feb 2018");
 while (begindate < enddate)
 {
    begindate= begindate.AddDays(1);
    Console.WriteLine(begindate + "  " + enddate);
 }

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

When increasing the size of VARCHAR column on a large table could there be any problems?

Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.

Auto-Submit Form using JavaScript

Try this,

HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");

Exception: There is already an open DataReader associated with this Connection which must be closed first

This exception also happens if don't use transactions properly. In my case, I put transaction.Commit() right after command.ExecuteReaderAsync(), and did not wait to commit the transaction until reader.ReadAsync() were called. The proper order:

  1. Create transaction.
  2. Create reader.
  3. Read the data.
  4. Commit the transaction.

How do I vertically align text in a div?

Try to embed a table element.

_x000D_
_x000D_
<div>_x000D_
  <table style='width:200px; height:100px;'>_x000D_
    <td style='vertical-align:middle;'>_x000D_
      copenhagen_x000D_
    </td>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Concat strings by & and + in VB.Net

My 2 cents:

If you are concatenating a significant amount of strings, you should be using the StringBuilder instead. IMO it's cleaner, and significantly faster.

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If you use multiple users at android, verify that the app is uninstalled everywhere.

In plain English, what does "git reset" do?

The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset and git checkout.

After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:

That is basically it. The reset command overwrites these three trees in a specific order, stopping when you tell it to.

  1. Move whatever branch HEAD points to (stop if --soft)
  2. THEN, make the Index look like that (stop here unless --hard)
  3. THEN, make the Working Directory look like that

There are also --merge and --keep options, but I would rather keep things simpler for now - that will be for another article.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

Convert utf8-characters to iso-88591 and back in PHP

In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):

$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Where can I find the assembly System.Web.Extensions dll?

EDIT:

The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.

ORIGINAL

It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:

HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\

I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

Navigating there I can see the actual System.Web.Extensions dll.

EDIT:

I found my .NET 4.0 version in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll

I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).

Dynamically Dimensioning A VBA Array?

You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:

  • Add
  • Count
  • Remove
  • Item(index)

Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.

Error: Local workspace file ('angular.json') could not be found

I also faced same issue and i just executed below command.

ng update @angular/cli --migrate-only --from=1.6.4

It simply delete angular-cli.json and create angular.json. You can find this in logs.

Once you start execution. You will be able to see below logs in your terminal.

        Updating karma configuration
        Updating configuration
        Removing old config file (.angular-cli.json)
        Writing config file (angular.json)
        Some configuration options have been changed, please make sure to update any                                     
        npm scripts which you may have modified.
        DELETE .angular-cli.json
        CREATE angular.json (3599 bytes)
        UPDATE karma.conf.js (962 bytes)
        UPDATE src/tsconfig.spec.json (324 bytes)
        UPDATE package.json (1405 bytes)
        UPDATE tsconfig.json (407 bytes)
        UPDATE tslint.json (3026 bytes)

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect:

SELECT
   CAST(
      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
   AS DATETIME)

Open a PDF using VBA in Excel

Use Shell "program file path file path you want to open".

Example:

Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"

CSS - Syntax to select a class within an id

.navigationLevel2 li { color: #aa0000 }

How to output loop.counter in python jinja template?

Inside of a for-loop block, you can access some special variables including loop.index --but no loop.counter. From the official docs:

Variable    Description
loop.index  The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex   The number of iterations from the end of the loop (1 indexed)
loop.revindex0  The number of iterations from the end of the loop (0 indexed)
loop.first  True if first iteration.
loop.last   True if last iteration.
loop.length The number of items in the sequence.
loop.cycle  A helper function to cycle between a list of sequences. See the explanation below.
loop.depth  Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem   The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem   The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val)  True if previously called with a different value (or not called at all).

Can't access Tomcat using IP address

You need allow ip based access for tomcat in server.xml, by default its disabled. Open server.xml search for "

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           URIEncoding="UTF-8"
           redirectPort="8443" />

Here add a new attribute useIPVHosts="true" so it looks like this,

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           URIEncoding="UTF-8"
           redirectPort="8443"
           useIPVHosts="true" />

Now restart tomcat, it should work

Azure SQL Database "DTU percentage" metric

To check the accurate usage for your services be it is free (as per always free or 12 months free) or Pay-As-You-Go, it is important to monitor the usage so that you know upfront on the cost incurred or when to upgrade your service tier.

To check your free service usage and its limits, Go to search in Portal, search with "Subscription" and click on it. you will see the details of each service that you have used.

In case of free azure from Microsoft, you get to see the cost incurred for each one.

Visit Check usage of free services included with your Azure free account enter image description here

Hope this helps someone!

CardView not showing Shadow in Android L

Check you're not using android:layerType="software" in your RecyclerView.

Changing it to android:layerType="hardware" solved the issue for me.

concatenate char array in C

Have a look at the strcat function.

In particular, you could try this:

const char* name = "hello";
const char* extension = ".txt";

char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */

How to add a new line in textarea element?

I think you are confusing the syntax of different languages.

  • &#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

  • \n is the linefeed character literal (ASCII 10) in a Javascript string.

  • <br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

_x000D_
_x000D_
T.innerText = "Position of LF: " + t.value.indexOf("\n");_x000D_
_x000D_
p1.innerHTML = t.value;_x000D_
p2.innerHTML = t.value.replace("\n", "<br/>");_x000D_
p3.innerText = t.value.replace("\n", "<br/>");
_x000D_
<textarea id="t">Line 1&#10;Line 2</textarea>_x000D_
_x000D_
<p id='T'></p>_x000D_
<p id='p1'></p>_x000D_
<p id='p2'></p>_x000D_
<p id='p3'></p>
_x000D_
_x000D_
_x000D_

A few points to note about Html:

  • The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
  • The P element renders all contiguous white spaces (including new lines) as one space.
  • The LF character does not render to a new line or line break in HTML.
  • The TEXTAREA renders LF as a new line inside the text area box.

how to convert image to byte array in java?

If you are using JDK 7 you can use the following code..

import java.nio.file.Files;
import java.io.File;

File fi = new File("myfile.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath())

Run Function After Delay

This answer is just useful to understand how you can make delay using JQuery delay function.

Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.

Here is the simple solution:

$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);

It is completely simple:

  1. .html() will change the text of .alert-element
  2. .fadeIn(500) will fade in after 500 milliseconds
  3. JQuery delay(5000) function will make 5000 milliseconds of delay before calling next function
  4. .fadeOut(1000) at the end of the statement will fade out the .alert-element

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date

How to pass a value from one Activity to another in Android?

Its simple If you are passing String X from A to B.
A--> B

In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity

Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);

In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)

Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");

This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call

intent.getIntExtra("KEY");

You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.

TransactionTooLargeException

How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.

How to create a JPA query with LEFT OUTER JOIN

Write this;

 SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'

Because your Student entity has One To Many relationship with ClassTbl entity.

Is a DIV inside a TD a bad idea?

It breaks semantics, that's all. It works fine, but there may be screen readers or something down the road that won't enjoy processing your HTML if you "break semantics".

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

The solution for this is that remove this following dependency:

implementation 'com.android.support:design:26.1.0'

put general dependencies as:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:support-compat:26.1.0'
    implementation 'com.android.support:multidex:1.0.3'    
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.facebook.android:audience-network-sdk:4.99.1'
}

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Happened a lot for me with Xcode 4.2.1 on Lion. Updated to 4.3.2 and it doesnt happen anymore. Glad they fixed it.

What are the differences between B trees and B+ trees?

  1. In a B tree search keys and data are stored in internal or leaf nodes. But in a B+-tree data is stored only in leaf nodes.
  2. Full scan of a B+ tree is very easy because all data are found in leaf nodes. Full scan of a B tree requires a full traversal.
  3. In a B tree, data may be found in leaf nodes or internal nodes. Deletion of internal nodes is very complicated. In a B+ tree, data is only found in leaf nodes. Deletion of leaf nodes is easy.
  4. Insertion in B tree is more complicated than B+ tree.
  5. B+ trees store redundant search keys but B tree has no redundant value.
  6. In a B+ tree, leaf node data is ordered as a sequential linked list but in a B tree the leaf node cannot be stored using a linked list. Many database systems' implementations prefer the structural simplicity of a B+ tree.

Parsing a comma-delimited std::string

void ExplodeString( const std::string& string, const char separator, std::list<int>& result ) {
    if( string.size() ) {
        std::string::const_iterator last = string.begin();
        for( std::string::const_iterator i=string.begin(); i!=string.end(); ++i ) {
            if( *i == separator ) {
                const std::string str(last,i);
                int id = atoi(str.c_str());
                result.push_back(id);
                last = i;
                ++ last;
            }
        }
        if( last != string.end() ) result.push_back( atoi(&*last) );
    }
}

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

HTML5 Canvas Rotate Image

As @markE mention in his answer

the alternative is to untranslate & unrotate after drawing

It is much faster than context save and restore.

Here is an example

// translate and rotate
this.context.translate(x,y);
this.context.rotate(radians);
this.context.translate(-x,-y);

this.context.drawImage(...);    

// untranslate and unrotate
this.context.translate(x, y);
this.context.rotate(-radians);
this.context.translate(-x,-y);

Generating random numbers with normal distribution in Excel

Use the NORMINV function together with RAND():

=NORMINV(RAND(),10,7)

To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.


Sample output (column A), 500 numbers generated with this formula:

enter image description here

Spring Rest POST Json RequestBody Content type not supported

If you use lombok, you can get that error if you screw up naming of @JsonDeserialize, for example:

@Value
@Builder(toBuilder = true)
@JsonDeserialize(builder = SomeClass.SomeOtherClassBuilder.class)
public class SomeClass {
    ...
    public static class SomeOtherClassBuilder {
        ...
    }
}

It should be:

@Value
@Builder(toBuilder = true)
@JsonDeserialize(builder = SomeClass.SomeClassBuilder.class)
public class SomeClass {
    ...
    public static class SomeClassBuilder {
        ...
    }
}

It is very easy to do that when you do refactoring of class name and forget about Builder... and then you have many hours of joy while you search for reason of error, while having as help only extremely unhelpful exception message.

ExtJs Gridpanel store refresh

reload the ds to refresh grid.

ds.reload();

How to detect string which contains only spaces?

You can Trim your String value by creating a trim function for your Strings.

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

now it will be available for your every String and you can use it as

str.trim().length// Result will be 0

You can also use this method to remove the white spaces at the start and end of the String i.e

"  hello  ".trim(); // Result will be "hello"

Get the distance between two geo points

There are a couple of methods you could use, but to determine which one is best we first need to know if you are aware of the user's altitude, as well as the altitude of the other points?

Depending on the level of accuracy you are after, you could look into either the Haversine or Vincenty formulae...

These pages detail the formulae, and, for the less mathematically inclined also provide an explanation of how to implement them in script!

Haversine Formula: http://www.movable-type.co.uk/scripts/latlong.html

Vincenty Formula: http://www.movable-type.co.uk/scripts/latlong-vincenty.html

If you have any problems with any of the meanings in the formulae, just comment and I'll do my best to answer them :)

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

Way to run Excel macros from command line or batch file?

you could write a vbscript to create an instance of excel via the createobject() method, then open the workbook and run the macro. You could either call the vbscript directly, or call the vbscript from a batch file.

Here is a resource I just stumbled accross: http://www.codeguru.com/forum/showthread.php?t=376401

Enable remote connections for SQL Server Express 2012

The correct way to connect to remote SQL Server (without opening UDP port 1434 and enabling SQL Server Browser) is to use ip and port instead of named instance.

Using ip and port instead of named instance is also safer, as it reduces the attack surface area.

Perhaps 2 pictures speak 2000 words...

This method uses the specified port (this is what most people want I believe)..

enter image description here

This method requires opening UDP port 1434 and SQL Server Browser running..

enter image description here

Download TS files from video stream

Copy and paste one of the .ts video files into a new tab in Chrome. Remove the identifying number of the .ts file (0,1,2,3 etc. or whatever number it is) and change the extension from ".ts" to ".mp4". That should bring up the video file in your browser as usual.

Cygwin Make bash command not found

I had the same problem and it was due to several installations of cygwin.

Check the link (the icon) that you click on to start the terminal. In case it does not point to the directory of your updated cygwin installation, you have the wrong installation of cygwin. When updating, double check the location of cygwin, and start exactly this instance of cygwin.

cor shows only NA or 1 for correlations - Why?

The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.

How do you synchronise projects to GitHub with Android Studio?

For Android Studio 0.8.9: VCS --> Import into version contraol --> Share project on Github. It doesn't give you option to share in a specific repository or at least I couldn't find (my limitation!).

You can add your github info here: File --> Settings --> Version COntraol --> Github.

Force GUI update from UI Thread

Think I have the answer, distilled from the above and a little experimentation.

progressBar.Value = progressBar.Maximum - 1;
progressBar.Maximum = progressBar.Value;

I tried decrementing the value and the screen updated even in debug mode, but that would not work for setting progressBar.Value to progressBar.Maximum, because you cannot set the progress bar value above the maximum, so I first set the progressBar.Value to progressBar.Maximum -1, then set progressBar.Maxiumum to equal progressBar.Value. They say there is more than one way of killing a cat. Sometimes I'd like to kill Bill Gates or whoever it is now :o).

With this result, I did not even appear to need to Invalidate(), Refresh(), Update(), or do anything to the progress bar or its Panel container or the parent Form.

Merging two images with PHP

Merger two image png and jpg/png [Image Masking]

//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);

//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

list($src_w, $src_h) = getimagesize($src_url);

//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);

//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);

imagecopymerge_alpha

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
    {
        $cut = imagecreatetruecolor($src_w, $src_h);
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

What is the easiest way to ignore a JPA field during persistence?

To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.

but then jackson will not serialize the field when converting to JSON.

If you need mix JPA with JSON(omit by JPA but still include in Jackson) use @JsonInclude :

@JsonInclude()
@Transient
private String token;

TIP:

You can also use JsonInclude.Include.NON_NULL and hide fields in JSON during deserialization when token == null:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Transient
private String token;

iFrame src change event detection?

You may want to use the onLoad event, as in the following example:

<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>

The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)

If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location, as in the following example:

<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>

How to get HttpClient to pass credentials along with the request?

Ok so I took Joshoun code and made it generic. I am not sure if I should implement singleton pattern on SynchronousPost class. Maybe someone more knowledgeble can help.

Implementation

//I assume you have your own concrete type. In my case I have am using code first with a class called FileCategory

FileCategory x = new FileCategory { CategoryName = "Some Bs"};
SynchronousPost<FileCategory>test= new SynchronousPost<FileCategory>();
test.PostEntity(x, "/api/ApiFileCategories"); 

Generic Class here. You can pass any type

 public class SynchronousPost<T>where T :class
    {
        public SynchronousPost()
        {
            Client = new WebClient { UseDefaultCredentials = true };
        }

        public void PostEntity(T PostThis,string ApiControllerName)//The ApiController name should be "/api/MyName/"
        {
            //this just determines the root url. 
            Client.BaseAddress = string.Format(
         (
            System.Web.HttpContext.Current.Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
            System.Web.HttpContext.Current.Request.Url.Scheme,
            System.Web.HttpContext.Current.Request.Url.Host,
            System.Web.HttpContext.Current.Request.Url.Port
           );
            Client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=utf-8");
            Client.UploadData(
                                 ApiControllerName, "Post", 
                                 Encoding.UTF8.GetBytes
                                 (
                                    JsonConvert.SerializeObject(PostThis)
                                 )
                             );  
        }
        private WebClient Client  { get; set; }
    }

My Api classs looks like this, if you are curious

public class ApiFileCategoriesController : ApiBaseController
{
    public ApiFileCategoriesController(IMshIntranetUnitOfWork unitOfWork)
    {
        UnitOfWork = unitOfWork;
    }

    public IEnumerable<FileCategory> GetFiles()
    {
        return UnitOfWork.FileCategories.GetAll().OrderBy(x=>x.CategoryName);
    }
    public FileCategory GetFile(int id)
    {
        return UnitOfWork.FileCategories.GetById(id);
    }
    //Post api/ApileFileCategories

    public HttpResponseMessage Post(FileCategory fileCategory)
    {
        UnitOfWork.FileCategories.Add(fileCategory);
        UnitOfWork.Commit(); 
        return new HttpResponseMessage();
    }
}

I am using ninject, and repo pattern with unit of work. Anyways, the generic class above really helps.

How do I set the driver's python version in spark?

I had the same problem, just forgot to activate my virtual environment. For anyone out there who also had a mental blank.

How do you extract IP addresses from files using a regex in a linux shell?

I usually start with grep, to get the regexp right.

# [multiple failed attempts here]
grep    '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*'                 file  # good?
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file  # good enough

Then I'd try and convert it to sed to filter out the rest of the line. (After reading this thread, you and I aren't going to do that anymore: we're going to use grep -o instead)

sed -ne 's/.*\([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\).*/\1/p  # FAIL

That's when I usually get annoyed with sed for not using the same regexes as anyone else. So I move to perl.

$ perl -nle '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/ and print $&'

Perl's good to know in any case. If you've got a teeny bit of CPAN installed, you can even make it more reliable at little cost:

$ perl -MRegexp::Common=net -nE '/$RE{net}{IPV4}/ and say $&' file(s)

How to get a JavaScript object's class?

If you need to not only GET class but also EXTEND it from having just an instance, write:

let's have

 class A{ 
   constructor(name){ 
     this.name = name
   }
 };

 const a1 = new A('hello a1');

so to extend A having the instance only use:

const a2 = new (Object.getPrototypeOf(a)).constructor('hello a2')
// the analog of const a2 = new A()

console.log(a2.name)//'hello a2'

Get current AUTO_INCREMENT value for any table

Query to check percentage "usage" of AUTO_INCREMENT for all tables of one given schema (except columns with type bigint unsigned):

SELECT 
  c.TABLE_NAME,
  c.COLUMN_TYPE,
  c.MAX_VALUE,
  t.AUTO_INCREMENT,
  IF (c.MAX_VALUE > 0, ROUND(100 * t.AUTO_INCREMENT / c.MAX_VALUE, 2), -1) AS "Usage (%)" 
FROM 
  (SELECT 
     TABLE_SCHEMA,
     TABLE_NAME,
     COLUMN_TYPE,
     CASE 
        WHEN COLUMN_TYPE LIKE 'tinyint(1)' THEN 127
        WHEN COLUMN_TYPE LIKE 'tinyint(1) unsigned' THEN 255
        WHEN COLUMN_TYPE LIKE 'smallint(%)' THEN 32767
        WHEN COLUMN_TYPE LIKE 'smallint(%) unsigned' THEN 65535
        WHEN COLUMN_TYPE LIKE 'mediumint(%)' THEN 8388607
        WHEN COLUMN_TYPE LIKE 'mediumint(%) unsigned' THEN 16777215
        WHEN COLUMN_TYPE LIKE 'int(%)' THEN 2147483647
        WHEN COLUMN_TYPE LIKE 'int(%) unsigned' THEN 4294967295
        WHEN COLUMN_TYPE LIKE 'bigint(%)' THEN 9223372036854775807
        WHEN COLUMN_TYPE LIKE 'bigint(%) unsigned' THEN 0
        ELSE 0
     END AS "MAX_VALUE" 
   FROM 
     INFORMATION_SCHEMA.COLUMNS
     WHERE EXTRA LIKE '%auto_increment%'
   ) c

   JOIN INFORMATION_SCHEMA.TABLES t ON (t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME)

WHERE
 c.TABLE_SCHEMA = 'YOUR_SCHEMA' 
ORDER BY
 `Usage (%)` DESC;

What are the differences between numpy arrays and matrices? Which one should I use?

As per the official documents, it's not anymore advisable to use matrix class since it will be removed in the future.

https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

As other answers already state that you can achieve all the operations with NumPy arrays.

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Write a number with two decimal places SQL Server

Generally you can define the precision of a number in SQL by defining it with parameters. For most cases this will be NUMERIC(10,2) or Decimal(10,2) - will define a column as a Number with 10 total digits with a precision of 2 (decimal places).

Edited for clarity

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

You didn't specify a GradientType:

background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */

source: http://www.colorzilla.com/gradient-editor/

Regex not operator

You could capture the (2001) part and replace the rest with nothing.

public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

  • .* match anything
  • \( match a ( character
  • ( begin capture
  • [0-9]{4} any single digit four times
  • ) end capture
  • \) match a ) character
  • .* anything (rest of string)

How to Update/Drop a Hive Partition?

Alter table table_name drop partition (partition_name);

Using setTimeout to delay timing of jQuery actions

Try this:

function explode(){
  alert("Boom!");
}
setTimeout(explode, 2000);

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

Convert from java.util.date to JodaTime

java.util.Date date = ...
DateTime dateTime = new DateTime(date);

Make sure date isn't null, though, otherwise it acts like new DateTime() - I really don't like that.

How to define two angular apps / modules in one page?

I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps

Hope this will help

How to close a Java Swing application from the code

I guess a EXIT_ON_CLOSE

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

before System.exit(0) is better since you can write a Window Listener to make some cleaning operations before actually leaving the app.

That window listener allows you to defined:

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");
    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;
        public void actionPerformed(ActionEvent e) {
            if (frame.isDisplayable()) {
                alreadyDisposed = true;
                frame.dispose();
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000);        //first delay 2 seconds
    timer.setRepeats(false);
    timer.start();
}

public void windowClosed(WindowEvent e) {
    //This will only be seen on standard output.
    displayMessage("WindowListener method called: windowClosed.");
}

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

How to set a value of a variable inside a template code?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.

How to remove numbers from string using Regex.Replace?

You can do it with a LINQ like solution instead of a regular expression:

string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());

A quick performance test shows that this is about five times faster than using a regular expression.

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

DateTimePicker time picker in 24 hour but displaying in 12hr?

I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.

 $(function() {
    $('.datetimepicker').datetimepicker({
        format: 'MM-DD-YYYY HH:mm '
    });
});

How do I run a Python program?

What I just did, to open a simple python script by double clicking. I just added a batch file to the directory containing the script:

@echo off
python exercise.py
pause>nul

(I have the python executable on my system path. If not one would need include its complete path of course.)

Then I just can double click on the batch file to run the script. The third line keeps the cmd window from being dismissed as soon as the script ends, so you can see the results. :) When you're done just close the command window.

C# MessageBox dialog result

Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
    case DialogResult.Yes:
        SaveChanges();
        break;
    case DialogResult.No:
        Rollback();
        break;
    default:
        break;
}

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Recently Google has lauched something called App Password. By creating an app-password for my mailer instance solved the issue for me.

https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=1-636228492770322608-2743677043&rd=1

Is it possible to set a number to NaN or infinity?

When using Python 2.4, try

inf = float("9e999")
nan = inf - inf

I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999") fixed it. Don't use inf = 9e999, you need convert it from string. -inf gives the -Infinity.

How to set the 'selected option' of a select dropdown list with jquery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
  $('#YourID option:selected').attr("selected",null);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Uncaught TypeError: data.push is not a function

Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

var history = [];
history.push("what a mess");

replacing it for:

var history123 = [];
history123.push("pray for a better language");

works as expected.

How do I Convert DateTime.now to UTC in Ruby?

You can set an ENV if you want your Time.now and DateTime.now to respond in UTC time.

require 'date'
Time.now #=> 2015-11-30 11:37:14 -0800
DateTime.now.to_s #=> "2015-11-30T11:37:25-08:00"
ENV['TZ'] = 'UTC'
Time.now #=> 2015-11-30 19:37:38 +0000
DateTime.now.to_s #=> "2015-11-30T19:37:36+00:00"

test if display = none

As @Agent_9191 and @partick mentioned you should use

$('tbody :visible').highlight(myArray[i]); // works for all children of tbody that are visible

or

$('tbody:visible').highlight(myArray[i]); // works for all visible tbodys

Additionally, since you seem to be applying a class to the highlighted words, instead of using jquery to alter the background for all matched highlights, just create a css rule with the background color you need and it gets applied directly once you assign the class.

.highlight { background-color: #FFFF88; }

Group query results by month and year in postgresql

Postgres has few types of timestamps:

timestamp without timezone - (Preferable to store UTC timestamps) You find it in multinational database storage. The client in this case will take care of the timezone offset for each country.

timestamp with timezone - The timezone offset is already included in the timestamp.

In some cases, your database does not use the timezone but you still need to group records in respect with local timezone and Daylight Saving Time (e.g. https://www.timeanddate.com/time/zone/romania/bucharest)

To add timezone you can use this example and replace the timezone offset with yours.

"your_date_column" at time zone '+03'

To add the +1 Summer Time offset specific to DST you need to check if your timestamp falls into a Summer DST. As those intervals varies with 1 or 2 days, I will use an aproximation that does not affect the end of month records, so in this case i can ignore each year exact interval.

If more precise query has to be build, then you have to add conditions to create more cases. But roughly, this will work fine in splitting data per month in respect with timezone and SummerTime when you find timestamp without timezone in your database:

SELECT 
    "id", "Product", "Sale",
    date_trunc('month', 
        CASE WHEN 
            Extract(month from t."date") > 03 AND
            Extract(day from t."date") > 26 AND
            Extract(hour from t."date") > 3 AND
            Extract(month from t."date") < 10 AND
            Extract(day from t."date") < 29 AND
            Extract(hour from t."date") < 4
        THEN 
            t."date" at time zone '+03' -- Romania TimeZone offset + DST
        ELSE
            t."date" at time zone '+02' -- Romania TimeZone offset 
        END) as "date"
FROM 
    public."Table" AS t
WHERE 1=1
    AND t."date" >= '01/07/2015 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
    AND t."date" < '01/07/2017 00:00:00'::TIMESTAMP WITHOUT TIME ZONE
GROUP BY date_trunc('month', 
    CASE WHEN 
        Extract(month from t."date") > 03 AND
        Extract(day from t."date") > 26 AND
        Extract(hour from t."date") > 3 AND
        Extract(month from t."date") < 10 AND
        Extract(day from t."date") < 29 AND
        Extract(hour from t."date") < 4
    THEN 
        t."date" at time zone '+03' -- Romania TimeZone offset + DST
    ELSE
        t."date" at time zone '+02' -- Romania TimeZone offset 
    END)

How do you UrlEncode without using System.Web?

Here's an example of sending a POST request that properly encodes parameters using application/x-www-form-urlencoded content type:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
    };
    var result = client.UploadValues("http://foo.com", values);
}

java.io.StreamCorruptedException: invalid stream header: 7371007E

This exception may also occur if you are using Sockets on one side and SSLSockets on the other. Consistency is important.

Lining up labels with radio buttons in bootstrap

This is all nicely lined up including the field label. Lining up the field label was the tricky part.

enter image description here

HTML Code:

<div class="form-group">
    <label class="control-label col-md-5">Create a</label>
    <div class="col-md-7">
        <label class="radio-inline control-label">
            <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
        </label>
        <label class="radio-inline control-label">
            <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
        </label>
    </div>
</div>

CSHTML / Razor Code:

<div class="form-group">
    @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
    <div class="col-md-7">
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
        </label>
        <label class="radio-inline control-label">
            @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
        </label>
    </div>
</div>

VBA - Select columns using numbers?

In this way, you can start to select data even behind column "Z" and select a lot of columns.

Sub SelectColumNums()
    Dim xCol1 As Integer, xNumOfCols as integer
    xCol1 = 26
    xNumOfCols = 17
    Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub

Gson: Directly convert String to JsonObject (no POJO)

use JsonParser; for example:

JsonParser parser = new JsonParser();
JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

This is how we can set it in run-time:

public class Program
{
    public static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case this error was specific to the hello-world docker image. I used the nginx image instead of the hello-world image and the error was resolved.

What JSON library to use in Scala?

I use PLAY JSON library you can find the mavn repo for only the JSON library not the whole framework here

    val json = "com.typesafe.play" %% "play-json" % version
    val typesafe = "typesafe.com" at "http://repo.typesafe.com/typesafe/releases/"

A very good tutorials about how to use them, are available here:

http://mandubian.com/2012/09/08/unveiling-play-2-dot-1-json-api-part1-jspath-reads-combinators/

http://mandubian.com/2012/10/01/unveiling-play-2-dot-1-json-api-part2-writes-format-combinators/

http://mandubian.com/2012/10/29/unveiling-play-2-dot-1-json-api-part3-json-transformers/

How to send string from one activity to another?

You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher

UIDevice uniqueIdentifier deprecated - What to do now?

If someone stumble upon to this question, when searching for an alternative. I have followed this approach in IDManager class, This is a collection from different solutions. KeyChainUtil is a wrapper to read from keychain. You can also use the hashed MAC address as a kind of unique ID.

/*  Apple confirmed this bug in their system in response to a Technical Support Incident 
    request. They said that identifierForVendor and advertisingIdentifier sometimes 
    returning all zeros can be seen both in development builds and apps downloaded over the 
    air from the App Store. They have no work around and can't say when the problem will be fixed. */
#define kBuggyASIID             @"00000000-0000-0000-0000-000000000000"

+ (NSString *) getUniqueID {
    if (NSClassFromString(@"ASIdentifierManager")) {
        NSString * asiID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        if ([asiID compare:kBuggyASIID] == NSOrderedSame) {
            NSLog(@"Error: This device return buggy advertisingIdentifier.");
            return [IDManager getUniqueUUID];
        } else {
            return asiID;
        }

    } else {
        return [IDManager getUniqueUUID];
    }
}


+ (NSString *) getUniqueUUID {
    NSError * error;
    NSString * uuid = [KeychainUtils getPasswordForUsername:kBuyassUser andServiceName:kIdOgBetilngService error:&error];
    if (error) {
        NSLog(@"Error geting unique UUID for this device! %@", [error localizedDescription]);
        return nil;
    }
    if (!uuid) {
        DLog(@"No UUID found. Creating a new one.");
        uuid = [IDManager GetUUID];
        uuid = [Util md5String:uuid];
        [KeychainUtils storeUsername:USER_NAME andPassword:uuid forServiceName:SERVICE_NAME updateExisting:YES error:&error];
        if (error) {
            NSLog(@"Error getting unique UUID for this device! %@", [error localizedDescription]);
            return nil;
        }
    }
    return uuid;
}

/* NSUUID is after iOS 6. */
+ (NSString *)GetUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

#pragma mark - MAC address
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Last fallback for unique identifier
+ (NSString *) getMACAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }

    if ((buf = malloc(len)) == NULL) {
        printf("Error: Memory allocation error\n");
        return NULL;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2\n");
        free(buf); // Thanks, Remy "Psy" Demerest
        return NULL;
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];

    free(buf);
    return outstring;
}

+ (NSString *) getHashedMACAddress
{
    NSString * mac = [IDManager getMACAddress];
    return [Util md5String:mac];
}

+ (NSString *)md5String:(NSString *)plainText
{
    if(plainText == nil || [plainText length] == 0)
        return nil;

    const char *value = [plainText UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);

    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    NSString * retString = [NSString stringWithString:outputString];
    [outputString release];
    return retString;
}

How to read existing text files without defining path

You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.

So it could relate to the current directory (get it from Directory.GetCurrentDirectory()) or to the application executable path (eg. Application.ExecutablePath comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath() with one element of the Environment.SpecialFolder enumeration).

Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!

In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.

Inserting records into a MySQL table using Java

this can also be done like this if you don't want to use prepared statements.

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

Using a different font with twitter bootstrap

The easiest way I've seen is to use Google Fonts.

Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.

Google's link to your font

Then add this to your custom.css:

h1, h2, h3, h4, h5, h6 {
    font-family: 'Your Font' !important;
}
p, div {
    font-family: 'Your Font' !important;
}

or

body {
   font-family: 'Your Font' !important;
}

How to monitor network calls made from iOS Simulator

Wireshark it

Select your interface

enter image description here

Add filter start the capture

enter image description here


Testing

Click on any action or button that would trigger a GET/POST/PUT/DELETE request

You will see it on listed in the wireshark

enter image description here

If you want to know more details about one specific packet, just select it and Follow > HTTP Stream.

enter image description here

hope this help others !!

Wait for a void async method

The best solution is to use async Task. You should avoid async void for several reasons, one of which is composability.

If the method cannot be made to return Task (e.g., it's an event handler), then you can use SemaphoreSlim to have the method signal when it is about to exit. Consider doing this in a finally block.

C# : Out of Memory exception

OutOfMemoryException (on 32-bit machines) is just as often about Fragmentation as actual hard limits on memory - you'll find lots about this, but here's my first google hit briefly discussing it: http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx. (@Anthony Pegram is referring to the same problem in his comment above).

That said, there is one other possibility that comes to mind for your code above: As you're using the "IEnumerable" constructor to the List, you may not giving the object any hints as to the size of the collection you're passing to the List constructor. If the object you are passing is is not a collection (does not implement the ICollection interface), then behind-the-scenes the List implementation is going to need to grow several (or many) times, each time leaving behind a too-small array that needs to be garbage collected. The garbage collector probably won't get to those discarded arrays fast enough, and you'll get your error.

The simplest fix for this would be to use the List(int capacity) constructor to tell the framework what backing array size to allocate (even if you're estimating and just guessing "50000" for example), and then use the AddRange(IEnumerable collection) method to actually populate your list.

So, simplest "Fix" if I'm right: replace

List<Vehicle> vList = new List<Vehicle>(selectedVehicles);

with

List<Vehicle> vList = new List<Vehicle>(50000);  
vList.AddRange(selectedVehicles);

All the other comments and answers still apply in terms of overall design decisions - but this might be a quick fix.

Note (as @Alex commented below), this is only an issue if selectedVehicles is not an ICollection.

Create Table from View

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView

Generating random, unique values C#

Try this:

private void NewNumber()
  {
     Random a = new Random(Guid.newGuid().GetHashCode());
     MyNumber = a.Next(0, 10);
  }

Some Explnations:

Guid : base on here : Represents a globally unique identifier (GUID)

Guid.newGuid() produces a unique identifier like "936DA01F-9ABD-4d9d-80C7-02AF85C822A8"

and it will be unique in all over the universe base on here

Hash code here produce a unique integer from our unique identifier

so Guid.newGuid().GetHashCode() gives us a unique number and the random class will produce real random numbers throw this

Sample: https://rextester.com/ODOXS63244

generated ten random numbers with this approach with result of:

-1541116401
7
-1936409663
3
-804754459
8
1403945863
3
1287118327
1
2112146189
1
1461188435
9
-752742620
4
-175247185
4
1666734552
7

we got two 1s next to each other, but the hash codes do not same.

"The import org.springframework cannot be resolved."

Add these dependencies

</dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
</dependencies>

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

Get the current URL with JavaScript?

To get the path, you can use:

_x000D_
_x000D_
console.log('document.location', document.location.href);_x000D_
console.log('location.pathname',  window.location.pathname); // Returns path only_x000D_
console.log('location.href', window.location.href); // Returns full URL
_x000D_
_x000D_
_x000D_

Completely removing phpMyAdmin

I had to run the following command:

sudo apt-get autoremove phpmyadmin

Then I cleared my cache and it worked!

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had the exact same error. It turned out that it was something was caused by something completely, though. It was missing write permissions in a cache folder. But IIS reported error 0x8007000d which is wildly confusing.

How to Alter Constraint

You can not alter constraints ever but you can drop them and then recreate.

Have look on this

ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;

and then recreate it with ON DELETE CASCADE like this

ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
    ON DELETE CASCADE;

hope this help

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

My problem solved with these :

1- Add this to your head :

<base href="/" />

2- Use this in app.config

$locationProvider.html5Mode(true);

How to type ":" ("colon") in regexp?

In most regex implementations (including Java's), : has no special meaning, neither inside nor outside a character class.

Your problem is most likely due to the fact the - acts as a range operator in your class:

[A-Za-z0-9.,-:]*

where ,-: matches all ascii characters between ',' and ':'. Note that it still matches the literal ':' however!

Try this instead:

[A-Za-z0-9.,:-]*

By placing - at the start or the end of the class, it matches the literal "-". As mentioned in the comments by Keoki Zee, you can also escape the - inside the class, but most people simply add it at the end.

A demo:

public class Test {
    public static void main(String[] args) {
        System.out.println("8:".matches("[,-:]+"));      // true: '8' is in the range ','..':'
        System.out.println("8:".matches("[,:-]+"));      // false: '8' does not match ',' or ':' or '-'
        System.out.println(",,-,:,:".matches("[,:-]+")); // true: all chars match ',' or ':' or '-'
    }
}

Google maps API V3 - multiple markers on exact same spot

I used this alongside jQuery and it does the job:

var map;
var markers = [];
var infoWindow;

function initialize() {
    var center = new google.maps.LatLng(-29.6833300, 152.9333300);

    var mapOptions = {
        zoom: 5,
        center: center,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        overviewMapControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }


    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    $.getJSON('jsonbackend.php', function(data) {
        infoWindow = new google.maps.InfoWindow();

        $.each(data, function(key, val) {
            if(val['LATITUDE']!='' && val['LONGITUDE']!='')
            {                
                // Set the coordonates of the new point
                var latLng = new google.maps.LatLng(val['LATITUDE'],val['LONGITUDE']);

                //Check Markers array for duplicate position and offset a little
                if(markers.length != 0) {
                    for (i=0; i < markers.length; i++) {
                        var existingMarker = markers[i];
                        var pos = existingMarker.getPosition();
                        if (latLng.equals(pos)) {
                            var a = 360.0 / markers.length;
                            var newLat = pos.lat() + -.00004 * Math.cos((+a*i) / 180 * Math.PI);  //x
                            var newLng = pos.lng() + -.00004 * Math.sin((+a*i) / 180 * Math.PI);  //Y
                            var latLng = new google.maps.LatLng(newLat,newLng);
                        }
                    }
                }

                // Initialize the new marker
                var marker = new google.maps.Marker({map: map, position: latLng, title: val['TITLE']});

                // The HTML that is shown in the window of each item (when the icon it's clicked)
                var html = "<div id='iwcontent'><h3>"+val['TITLE']+"</h3>"+
                "<strong>Address: </strong>"+val['ADDRESS']+", "+val['SUBURB']+", "+val['STATE']+", "+val['POSTCODE']+"<br>"+
                "</div>";

                // Binds the infoWindow to the point
                bindInfoWindow(marker, map, infoWindow, html);

                // Add the marker to the array
                markers.push(marker);
            }
        });

        // Make a cluster with the markers from the array
        var markerCluster = new MarkerClusterer(map, markers, { zoomOnClick: true, maxZoom: 15, gridSize: 20 });
    });
}

function markerOpen(markerid) {
    map.setZoom(22);
    map.panTo(markers[markerid].getPosition());
    google.maps.event.trigger(markers[markerid],'click');
    switchView('map');
}

google.maps.event.addDomListener(window, 'load', initialize);

Datatable vs Dataset

One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.

Finding an item in a List<> using C#

For .NET 2.0:

list.Find(delegate(Item i) { return i.Property == someValue; });

Python for and if on one line

You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

for elem in my_list:
    if elem == 'two':
        break

If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

i = next((elem for elem in my_list if elem == 'two'), None)

which will set i to None if there is no such matching element.

The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

elem = 'two' if 'two' in my_list else None

How to add a set path only for that batch file executing?

There is an important detail:

set PATH="C:\linutils;C:\wingit\bin;%PATH%"

does not work, while

set PATH=C:\linutils;C:\wingit\bin;%PATH%

works. The difference is the quotes!

UPD also see the comment by venimus

jsPDF multi page PDF with HTML renderer

$( document ).ready(function() {    
$('#cmd').click(function() {
      var options = {
              pagesplit: true //include this in your code
      };
      var pdf = new jsPDF('p', 'pt', 'a4');
      pdf.addHTML($("#pdfContent"), 15, 15, options, function() {
        pdf.save('Menu.pdf');
      });
    });
});

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

If you are using the codeigniter framework and are testing the project on a localhost, open the main Index.php file of your project folder and find this code:

define('ENVIRONMENT', 'production');

Change it to

define ('ENVIRONMENT', 'development');

Because same this ENVIRONMENT is in your database.php file under config folder. like this:

 'db_debug' => (ENVIRONMENT! == 'development')

So the environment should be the same in both places and problem will be solved.

Pandas: change data type of Series to String

A new answer to reflect the most current practices: as of version 1.0.1, neither astype('str') nor astype(str) work.

As per the documentation, a Series can be converted to the string datatype in the following ways:

df['id'] = df['id'].astype("string")

df['id'] = pandas.Series(df['id'], dtype="string")

df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)

How can I capture the result of var_dump to a string?

function return_var_dump(){
    // It works like var_dump, but it returns a string instead of printing it.
    $args = func_get_args(); // For <5.3.0 support ...
    ob_start();
    call_user_func_array('var_dump', $args);
    return ob_get_clean();
}

PHP - Getting the index of a element from a array

an array does not contain index when elements are associative. An array in php can contain mixed values like this:

$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");   
print_r($var);

Gives you:

Array
(
    [0] => apple
    [1] => banana
    [foo] => grape
    [2] => carrot
    [bar] => donkey
)

What are you trying to achieve since you need the index value in an associative array?

Generate random numbers uniformly over an entire range

Why rand is a bad idea

Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX), and is therefore discouraged.

C++11 and generation over a range

With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution. Here's an example:

const int range_from  = 0;
const int range_to    = 10;
std::random_device                  rand_dev;
std::mt19937                        generator(rand_dev());
std::uniform_int_distribution<int>  distr(range_from, range_to);

std::cout << distr(generator) << '\n';

And here's the running example.

Template function may help some:

template<typename T>
T random(T range_from, T range_to) {
    std::random_device                  rand_dev;
    std::mt19937                        generator(rand_dev());
    std::uniform_int_distribution<T>    distr(range_from, range_to);
    return distr(generator);
}

Other random generators

The <random> header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.

How can I shuffle a container?

The standard provides std::shuffle, which can be used as follows:

std::vector<int> vec = {4, 8, 15, 16, 23, 42};

std::random_device random_dev;
std::mt19937       generator(random_dev());

std::shuffle(vec.begin(), vec.end(), generator);

The algorithm will reorder the elements randomly, with a linear complexity.

Boost.Random

Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random. Its interface is very similar to the C++11 one.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

You must manually clear the ChildItems collection and append new items into it:

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

After that you can call DeleteOrphans extension method which will handle with orphaned entities (it must be called between DetectChanges and SaveChanges methods).

public static class DbContextExtensions
{
    private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();

    public static void DeleteOrphans( this DbContext source )
    {
        var context = ((IObjectContextAdapter)source).ObjectContext;
        foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
        {
            var entityType = entry.EntitySet.ElementType as EntityType;
            if (entityType == null)
                continue;

            var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
            var props = entry.GetModifiedProperties().ToArray();
            foreach (var prop in props)
            {
                NavigationProperty navProp;
                if (!navPropMap.TryGetValue(prop, out navProp))
                    continue;

                var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
                var enumerator = related.GetEnumerator();
                if (enumerator.MoveNext() && enumerator.Current != null)
                    continue;

                entry.Delete();
                break;
            }
        }
    }

    private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
    {
        var result = type.NavigationProperties
            .Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            .Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
            .Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
            .Where(v => v.DependentProperties.Length == 1)
            .ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);

        return new ReadOnlyDictionary<string, NavigationProperty>(result);
    }
}

Run a batch file with Windows task scheduler

It is working now. This is what I did. You probably won't need all these steps to make it work but just to be sure try them all:

  • Check the account parameters of your scheduled task and make sure they are set to run whether or not someone is logged into the machine

  • check run with most privileges/rights

  • Make sure you go to the full path first: cd C:\inetpub\wwwroot\infoweb\factuur\cron

  • Don't use double quotes in your batch files (don't know why but seems to help)

  • Be super admin, enter 'Net user administrator /active:yes' in command prompt, log out and log in as the super admin, so UAC is off

Remove json element

As described by @mplungjan, I though it was right. Then right away I click the up rate button. But by following it, I finally got an error.

<script>
var data = {"result":[
  {"FirstName":"Test1","LastName":"User","Email":"[email protected]","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
  {"FirstName":"user","LastName":"user","Email":"[email protected]","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
  {"FirstName":"Ropbert","LastName":"Jones","Email":"[email protected]","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
  {"FirstName":"hitesh","LastName":"prajapti","Email":"[email protected]","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
  ]
}
alert(data.result)
delete data.result[3]
alert(data.result)
</script>

Delete is just remove the data, but the 'place' is still there as undefined.

I did this and it works like a charm :

data.result.splice(2,1);  

meaning : delete 1 item at position 3 ( because array is counted form 0, then item at no 3 is counted as no 2 )

How to empty (clear) the logcat buffer in Android

I give my solution for Mac:

  1. With your device connected to the USB port, open a terminal and go to the adb folder.
  2. Write: ./adb devices
  3. The terminal will show something like this: List of devices attached 36ac5997 device
  4. Take note of the serial number (36ac5997)
  5. Write: ./adb -s 36ac5997 to connect to the device
  6. Write: ./adb logcat

If at any time you want to clear the log, type ./adb logcat -c

How to convert an NSTimeInterval (seconds) into minutes

If you're targeting at or above iOS 8 or OS X 10.10, this just got a lot easier. The new NSDateComponentsFormatter class allows you to convert a given NSTimeInterval from its value in seconds to a localized string to show the user. For example:

Objective-C

NSTimeInterval interval = 326.4;

NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];

componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;

NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26

Swift

let interval = 326.4

let componentFormatter = NSDateComponentsFormatter()

componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll

if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
    print(formattedString) // 5:26
}

NSDateCompnentsFormatter also allows for this output to be in longer forms. More info can be found in NSHipster's NSFormatter article. And depending on what classes you're already working with (if not NSTimeInterval), it may be more convenient to pass the formatter an instance of NSDateComponents, or two NSDate objects, which can be done as well via the following methods.

Objective-C

NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];

Swift

if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
    // ...
}

if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
    // ...
}

General error: 1364 Field 'user_id' doesn't have a default value

Try

'user_id' => auth()->id
or

'user_id' => Auth::user()->id

instead of

'user_id' => auth()->id()

How to convert a String to Bytearray

I know the question is almost 4 years old, but this is what worked smoothly with me:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes;_x000D_
};_x000D_
_x000D_
Array.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.toString().split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

or, if you want to work with strings only, and no Array, you can use:

_x000D_
_x000D_
String.prototype.encodeHex = function () {_x000D_
  var bytes = [];_x000D_
  for (var i = 0; i < this.length; ++i) {_x000D_
    bytes.push(this.charCodeAt(i));_x000D_
  }_x000D_
  return bytes.toString();_x000D_
};_x000D_
_x000D_
String.prototype.decodeHex = function () {    _x000D_
  var str = [];_x000D_
  var hex = this.split(',');_x000D_
  for (var i = 0; i < hex.length; i++) {_x000D_
    str.push(String.fromCharCode(hex[i]));_x000D_
  }_x000D_
  return str.toString().replace(/,/g, "");_x000D_
};_x000D_
_x000D_
var str = "Hello World!";_x000D_
var bytes = str.encodeHex();_x000D_
_x000D_
alert('The Hexa Code is: '+bytes+' The original string is:  '+bytes.decodeHex());
_x000D_
_x000D_
_x000D_

Check if a string is null or empty in XSLT

If a node has no value available in the input xml like below xpath,

<node>
    <ErrorCode/>
</node>

string() function converts into empty value. So this works fine:

string(/Node/ErrorCode) =''

Interface or an Abstract Class: which one to use?

Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.

  • I have multiple abstract classes which handle the standard crud and also some specialty functionality like conversion and streaming for different categories of files.
  • The file access interface defines a common set of methods which are needed to get, store and delete a file.

This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.

Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.

Jquery: Find Text and replace

Warning string.replace('string','new string') not replaced all character. You have to use regax replace.

For exp: I have a sting old string1, old string2, old string3 and want to replace old to new

Then i used.

    var test = 'old string1, old string2, old string3';

   //***** Wrong method **********
    test = test.replace('old', 'new'); // This  will replaced only first match not all
    Result: new string1, old string2, old string3

  //***** Right method **********
    test = test.replace(/([old])+/g, 'new'); // This  will replaced all match 
    Result: new string1, new string2, new string3

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

How do I UPDATE from a SELECT in SQL Server?

Here is another useful syntax:

UPDATE suppliers
SET supplier_name = (SELECT customers.name
                     FROM customers
                     WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT customers.name
              FROM customers
              WHERE customers.customer_id = suppliers.supplier_id);

It checks if it is null or not by using "WHERE EXIST".

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

Difference Between Schema / Database in MySQL

Refering to MySql documentation,

CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.

Remove empty array elements

$my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");   

foreach ($my as $key => $value) {
    if (is_null($value)) unset($my[$key]);
}

foreach ($my as $key => $value) {
    echo   $key . ':' . $value . '<br>';
} 

output

1:5

2:6

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

Update for .NET Core 3.0+

  1. You can use CreateDefaultBuilder which will automatically build and pass a configuration object to your startup class:

    WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    
    public class Startup
    {
        public Startup(IConfiguration configuration) // automatically injected
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        /* ... */
    }
    
  2. CreateDefaultBuilder automatically includes the appropriate appsettings.Environment.json file so add a separate appsettings file for each environment:

    appsettings.env.json

  3. Then set the ASPNETCORE_ENVIRONMENT environment variable when running / debugging

How to set Environment Variables

Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:

  • For Visual Studio go to Project > Properties > Debug > Environment Variables:

    Visual Studio - Environment Variables

  • For Visual Studio Code, edit .vscode/launch.json > env:

    Visual Studio Code > Launch Environment

  • Using Launch Settings, edit Properties/launchSettings.json > environmentVariables:

    Launch Settings

    Which can also be selected from the Toolbar in Visual Studio

    Launch Settings Dropdown

  • Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS

    Note: When an app is launched with dotnet run, launchSettings.json is read if available, and environmentVariables settings in launchSettings.json override environment variables.

How does Host.CreateDefaultBuilder work?

.NET Core 3.0 added Host.CreateDefaultBuilder under platform extensions which will provide a default initialization of IConfiguration which provides default configuration for the app in the following order:

  1. appsettings.json using the JSON configuration provider.
  2. appsettings.Environment.json using the JSON configuration provider. For example:
    • appsettings.Production.json or
    • appsettings.Development.json
  3. App secrets when the app runs in the Development environment.
  4. Environment variables using the Environment Variables configuration provider.
  5. Command-line arguments using the Command-line configuration provider.

Further Reading - MS Docs

How to time Java program execution speed

You can use Stopwatch

import com.google.common.base.Stopwatch;

Stopwatch timer = Stopwatch.createStarted();
//lines to be executed
System.out.println("Execution time= " + timer.stop());

Delete a row from a table by id

And what about trying not to delete but hide that row?

PHP "php://input" vs $_POST

So I wrote a function that would get the POST data from the php://input stream.

So the challenge here was switching to PUT, DELETE OR PATCH request method, and still obtain the post data that was sent with that request.

I'm sharing this maybe for someone with a similar challenge. The function below is what I came up with and it works. I hope it helps!

    /**
     * @method Post getPostData
     * @return array
     * 
     * Convert Content-Disposition to a post data
     */
    function getPostData() : array
    {
        // @var string $input
        $input = file_get_contents('php://input');

        // continue if $_POST is empty
        if (strlen($input) > 0 && count($_POST) == 0 || count($_POST) > 0) :

            $postsize = "---".sha1(strlen($input))."---";

            preg_match_all('/([-]{2,})([^\s]+)[\n|\s]{0,}/', $input, $match);

            // update input
            if (count($match) > 0) $input = preg_replace('/([-]{2,})([^\s]+)[\n|\s]{0,}/', '', $input);

            // extract the content-disposition
            preg_match_all("/(Content-Disposition: form-data; name=)+(.*)/m", $input, $matches);

            // let's get the keys
            if (count($matches) > 0 && count($matches[0]) > 0)
            {
                $keys = $matches[2];

                foreach ($keys as $index => $key) :
                    $key = trim($key);
                    $key = preg_replace('/^["]/','',$key);
                    $key = preg_replace('/["]$/','',$key);
                    $key = preg_replace('/[\s]/','',$key);
                    $keys[$index] = $key;
                endforeach;

                $input = preg_replace("/(Content-Disposition: form-data; name=)+(.*)/m", $postsize, $input);

                $input = preg_replace("/(Content-Length: )+([^\n]+)/im", '', $input);

                // now let's get key value
                $inputArr = explode($postsize, $input);

                // @var array $values
                $values = [];

                foreach ($inputArr as $index => $val) :
                    $val = preg_replace('/[\n]/','',$val);

                    if (preg_match('/[\S]/', $val)) $values[$index] = trim($val);

                endforeach;

                // now combine the key to the values
                $post = [];

                // @var array $value
                $value = [];

                // update value
                foreach ($values as $i => $val) $value[] = $val;

                // push to post
                foreach ($keys as $x => $key) $post[$key] = isset($value[$x]) ? $value[$x] : '';

                if (is_array($post)) :

                    $newPost = [];

                    foreach ($post as $key => $val) :

                        if (preg_match('/[\[]/', $key)) :

                            $k = substr($key, 0, strpos($key, '['));
                            $child = substr($key, strpos($key, '['));
                            $child = preg_replace('/[\[|\]]/','', $child);
                            $newPost[$k][$child] = $val;

                        else:

                            $newPost[$key] = $val;

                        endif;

                    endforeach;

                    $_POST = count($newPost) > 0 ? $newPost : $post;

                endif;
            }

        endif;

        // return post array
        return $_POST;
    }

C# equivalent of C++ vector, with contiguous memory?

You could use a List<T> and when T is a value type it will be allocated in contiguous memory which would not be the case if T is a reference type.

Example:

List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);

int someElement = integers[1];

How to ignore HTML element from tabindex?

Such hack like "tabIndex=-1" not work for me with Chrome v53.

This is which works for chrome, and most browsers:

_x000D_
_x000D_
function removeTabIndex(element) {_x000D_
    element.removeAttribute('tabindex');_x000D_
}
_x000D_
<input tabIndex="1" />_x000D_
<input tabIndex="2" id="notabindex" />_x000D_
<input tabIndex="3" />_x000D_
<button tabIndex="4" onclick="removeTabIndex(document.getElementById('notabindex'))">Remove tabindex</button>
_x000D_
_x000D_
_x000D_

How to reliably open a file in the same directory as a Python script

To quote from the Python documentation:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

sys.path[0] is what you are looking for.

App crashing when trying to use RecyclerView on android 5.0

I had this problem when using Butterknife , I was using fragment

For Fragment, it should be ButterKnife.bind(this,view);

For Activity ButterKnife.bind(this);

Show loading screen when navigating between routes in Angular 2

If you have special logic required for the first route only you can do the following:

AppComponent

    loaded = false;

    constructor(private router: Router....) {
       router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
                    .subscribe((e) => {
                       this.loaded = true;
                       alert('loaded - this fires only once');
                   });

I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.

Reduce left and right margins in matplotlib plot

With recent matplotlib versions you might want to try Constrained Layout.

Too bad pandas does not handle it well...

Define global constants

Below changes works for me on Angular 2 final version:

export class AppSettings {
   public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(AppSettings.API_ENDPOINT+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

Binding a WPF ComboBox to a custom list

I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

<ComboBox Name="CategoryList"
          DisplayMemberPath="CategoryName"
          SelectedItem="{Binding Path=CategoryParent}"
          SelectedValue="{Binding Path=CategoryParent.ID}"
          SelectedValuePath="ID">

See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

SQL select statements with multiple tables

Like that:

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Just simply comment out the line: ALLOWED_HOSTS = [...]

How can I do a case insensitive string comparison?

How about using StringComparison.CurrentCultureIgnoreCase instead?

Connection to SQL Server Works Sometimes

I solved the problem like Eric but with some other changes:

  • Start Sql Server Configuration Manager
  • Open the node SQL Server Network Configuration
  • Left-click Protocols for MYSQLINSTANCE
  • In the right-hand pane, right-click TCP/IP
  • Click Properties
  • Select the IP Addresses tab
  • For each listed IP address, ensure Active and Enabled are both Yes.

AND

  • For each listed IP address, ensure TCP Dynamic Ports is empty and TCP Port = 1433 (or some other port)
  • Open windows firewall and check that the port is Opened in Incoming connections

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If anyone is having this exception and is building the query using Scala multi-line strings:

Looks like there is a problem with some JPA drivers in this situation. I'm not sure what is the character Scala uses for LINE END, but when you have a parameter right at the end of the line, the LINE END character seems to be attached to the parameter and so when the driver parses the query, this error comes up. A simple work around is to leave an empty space right after the param at the end:

SELECT * FROM some_table a
WHERE a.col = ?param
AND a.col2 = ?param2

So, just make sure to leave an empty space after param (and param2, if you have a line break there).

How to move all HTML element children to another parent using JavaScript?

If you not use - in id's names then you can do this

_x000D_
_x000D_
oldParent.id='xxx';_x000D_
newParent.id='oldParent';_x000D_
xxx.id='newParent';_x000D_
oldParent.parentNode.insertBefore(oldParent,newParent);
_x000D_
#newParent { color: red }
_x000D_
<div id="oldParent">_x000D_
    <span>Foo</span>_x000D_
    <b>Bar</b>_x000D_
    Hello World_x000D_
</div>_x000D_
<div id="newParent"></div>
_x000D_
_x000D_
_x000D_

How to query all the GraphQL type fields without writing a long query?

I faced this same issue when I needed to load location data that I had serialized into the database from the google places API. Generally I would want the whole thing so it works with maps but I didn't want to have to specify all of the fields every time.

I was working in Ruby so I can't give you the PHP implementation but the principle should be the same.

I defined a custom scalar type called JSON which just returns a literal JSON object.

The ruby implementation was like so (using graphql-ruby)

module Graph
  module Types
    JsonType = GraphQL::ScalarType.define do
      name "JSON"
      coerce_input -> (x) { x }
      coerce_result -> (x) { x }
    end
  end
end

Then I used it for our objects like so

field :location, Types::JsonType

I would use this very sparingly though, using it only where you know you always need the whole JSON object (as I did in my case). Otherwise it is defeating the object of GraphQL more generally speaking.

Create a hexadecimal colour based on a string with JavaScript

Here is another try:

function stringToColor(str){
  var hash = 0;
  for(var i=0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 3) - hash);
  }
  var color = Math.abs(hash).toString(16).substring(0, 6);

  return "#" + '000000'.substring(0, 6 - color.length) + color;
}

Best way to format if statement with multiple conditions

I've been facing this dilemma for a long time and I still can't find a proper solution. In my opinion only good way is to first try to get rid of conditions before so you're not suddenly comparing 5 of them.

If there's no alternative then like others have suggested - break it down into separete ones and shorten the names or group them and e.g. if all must be true then use something like "if no false in array of x then run".

If all fails @Eoin Campbell gave pretty good ideas.

File uploading with Express 4.0: req.files undefined

It looks like body-parser did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency

After looking through some of the modules in mscdex's answer, I found that express-busboy was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.

console.log(req.files) using body-parser (Express 3) output an object that looked like this:

{ file: 
   { fieldName: 'file',
     originalFilename: '360px-Cute_Monkey_cropped.jpg',
     name: '360px-Cute_Monkey_cropped.jpg'
     path: 'uploads/6323-16v7rc.jpg',
     type: 'image/jpeg',
     headers: 
      { 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
        'content-type': 'image/jpeg' },
     ws: 
      WriteStream { /* ... */ },
     size: 48614 } }

compared to console.log(req.files) using express-busboy (Express 4):

{ file: 
   { field: 'file',
     filename: '360px-Cute_Monkey_cropped.jpg',
     file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
     mimetype: 'image/jpeg',
     encoding: '7bit',
     truncated: false
     uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }

ReactJS - Add custom event listener to component

First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}> in the render function, and have to think around the problem.

Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body, so even if it did work, your event handler would never trigger.

Instead, inside componentDidMount somewhere in your application, you can listen to nv-enter by adding

document.body.addEventListener('nv-enter', function (event) {
    // logic
});

Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.

How to use JavaScript with Selenium WebDriver Java

You need to run this command in the top-level directory of a Selenium SVN repository checkout.

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

How to check if a key exists in Json Object and get its value

containerObject = new JSONObject(container);
if (containerObject.has("video")) { 
   //get Value of video
}

Is there a "not equal" operator in Python?

There are two operators in Python for the "not equal" condition -

a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.

b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

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

You can try this.

SELECT *
  FROM (SELECT column_name,
               data_type,
               data_type
               || CASE
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) > 0
                     THEN
                        '(' || data_precision || ',' || data_scale || ')'
                     WHEN data_precision IS NOT NULL
                          AND NVL (data_scale, 0) = 0
                     THEN
                        '(' || data_precision || ')'
                     WHEN data_precision IS NULL AND data_scale IS NOT NULL
                     THEN
                        '(*,' || data_scale || ')'
                     WHEN char_length > 0
                     THEN
                        '(' || char_length
                        || CASE char_used
                              WHEN 'B' THEN ' Byte'
                              WHEN 'C' THEN ' Char'
                              ELSE NULL
                           END
                        || ')'
                  END
               || DECODE (nullable, 'N', ' NOT NULL')
                  DataTypeWithLength
          FROM user_tab_columns
         WHERE table_name = 'CONTRACT')
 WHERE DataTypeWithLength = 'CHAR(1 Byte)';

What is the effect of extern "C" in C++?

Decompile a g++ generated binary to see what is going on

main.cpp

void f() {}
void g();

extern "C" {
    void ef() {}
    void eg();
}

/* Prevent g and eg from being optimized away. */
void h() { g(); eg(); }

Compile and disassemble the generated ELF output:

g++ -c -std=c++11 -Wall -Wextra -pedantic -o main.o main.cpp
readelf -s main.o

The output contains:

     8: 0000000000000000     7 FUNC    GLOBAL DEFAULT    1 _Z1fv
     9: 0000000000000007     7 FUNC    GLOBAL DEFAULT    1 ef
    10: 000000000000000e    17 FUNC    GLOBAL DEFAULT    1 _Z1hv
    11: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _GLOBAL_OFFSET_TABLE_
    12: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _Z1gv
    13: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND eg

Interpretation

We see that:

  • ef and eg were stored in symbols with the same name as in the code

  • the other symbols were mangled. Let's unmangle them:

    $ c++filt _Z1fv
    f()
    $ c++filt _Z1hv
    h()
    $ c++filt _Z1gv
    g()
    

Conclusion: both of the following symbol types were not mangled:

  • defined
  • declared but undefined (Ndx = UND), to be provided at link or run time from another object file

So you will need extern "C" both when calling:

  • C from C++: tell g++ to expect unmangled symbols produced by gcc
  • C++ from C: tell g++ to generate unmangled symbols for gcc to use

Things that do not work in extern C

It becomes obvious that any C++ feature that requires name mangling will not work inside extern C:

extern "C" {
    // Overloading.
    // error: declaration of C function ‘void f(int)’ conflicts with
    void f();
    void f(int i);

    // Templates.
    // error: template with C linkage
    template <class C> void f(C i) { }
}

Minimal runnable C from C++ example

For the sake of completeness and for the newbs out there, see also: How to use C source files in a C++ project?

Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.

main.cpp

#include <cassert>

#include "c.h"

int main() {
    assert(f() == 1);
}

c.h

#ifndef C_H
#define C_H

/* This ifdef allows the header to be used from both C and C++ 
 * because C does not know what this extern "C" thing is. */
#ifdef __cplusplus
extern "C" {
#endif
int f();
#ifdef __cplusplus
}
#endif

#endif

c.c

#include "c.h"

int f(void) { return 1; }

Run:

g++ -c -o main.o -std=c++98 main.cpp
gcc -c -o c.o -std=c89 c.c
g++ -o main.out main.o c.o
./main.out

Without extern "C" the link fails with:

main.cpp:6: undefined reference to `f()'

because g++ expects to find a mangled f, which gcc did not produce.

Example on GitHub.

Minimal runnable C++ from C example

Calling C++ from C is a bit harder: we have to manually create non-mangled versions of each function we want to expose.

Here we illustrate how to expose C++ function overloads to C.

main.c

#include <assert.h>

#include "cpp.h"

int main(void) {
    assert(f_int(1) == 2);
    assert(f_float(1.0) == 3);
    return 0;
}

cpp.h

#ifndef CPP_H
#define CPP_H

#ifdef __cplusplus
// C cannot see these overloaded prototypes, or else it would get confused.
int f(int i);
int f(float i);
extern "C" {
#endif
int f_int(int i);
int f_float(float i);
#ifdef __cplusplus
}
#endif

#endif

cpp.cpp

#include "cpp.h"

int f(int i) {
    return i + 1;
}

int f(float i) {
    return i + 2;
}

int f_int(int i) {
    return f(i);
}

int f_float(float i) {
    return f(i);
}

Run:

gcc -c -o main.o -std=c89 -Wextra main.c
g++ -c -o cpp.o -std=c++98 cpp.cpp
g++ -o main.out main.o cpp.o
./main.out

Without extern "C" it fails with:

main.c:6: undefined reference to `f_int'
main.c:7: undefined reference to `f_float'

because g++ generated mangled symbols which gcc cannot find.

Example on GitHub.

Where is the extern "c" when I include C headers from C++?

Tested in Ubuntu 18.04.

How to draw polygons on an HTML5 canvas?

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

How to detect orientation change?

Using -orientation property of UIDevice is not correct (even if it could work in most of cases) and could lead to some bugs, for instance UIDeviceOrientation consider also the orientation of the device if it is face up or down, there is no direct pair in UIInterfaceOrientation enum for those values.
Furthermore, if you lock your app in some particular orientation, UIDevice will give you the device orientation without taking that into account.
On the other side iOS8 has deprecated the interfaceOrientation property on UIViewController class.
There are 2 options available to detect the interface orientation:

  • Use the status bar orientation
  • Use size classes, on iPhone if they are not overridden they could give you a way to understand the current interface orientation

What is still missing is a way to understand the direction of a change of interface orientation, that is very important during animations.
In the session of WWDC 2014 "View controller advancement in iOS8" the speaker provides a solution to that problem too, using the method that replaces -will/DidRotateToInterfaceOrientation.

Here the proposed solution partially implemented, more info here:

func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        let orientation = orientationFromTransform(coordinator.targetTransform())
        let oldOrientation = UIApplication.sharedApplication().statusBarOrientation
        myWillRotateToInterfaceOrientation(orientation,duration: duration)
        coordinator.animateAlongsideTransition({ (ctx) in
            self.myWillAnimateRotationToInterfaceOrientation(orientation,
            duration:duration)
            }) { (ctx) in
                self.myDidAnimateFromInterfaceOrientation(oldOrientation)
        }
    }

What does `ValueError: cannot reindex from a duplicate axis` mean?

I came across this error today when I wanted to add a new column like this

df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

I wanted to process the REMARK column of df_temp to return 1 or 0. However I typed wrong variable with df. And it returned error like this:

----> 1 df_temp['REMARK_TYPE'] = df.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2417         else:
   2418             # set column
-> 2419             self._set_item(key, value)
   2420 
   2421     def _setitem_slice(self, key, value):

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
   2483 
   2484         self._ensure_valid_index(value)
-> 2485         value = self._sanitize_column(key, value)
   2486         NDFrame._set_item(self, key, value)
   2487 

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
   2633 
   2634         if isinstance(value, Series):
-> 2635             value = reindexer(value)
   2636 
   2637         elif isinstance(value, DataFrame):

/usr/lib64/python2.7/site-packages/pandas/core/frame.pyc in reindexer(value)
   2625                     # duplicate axis
   2626                     if not value.index.is_unique:
-> 2627                         raise e
   2628 
   2629                     # other

ValueError: cannot reindex from a duplicate axis

As you can see it, the right code should be

df_temp['REMARK_TYPE'] = df_temp.REMARK.apply(lambda v: 1 if str(v)!='nan' else 0)

Because df and df_temp have a different number of rows. So it returned ValueError: cannot reindex from a duplicate axis.

Hope you can understand it and my answer can help other people to debug their code.

Ascii/Hex convert in bash

The reason is because hexdump by default prints out 16-bit integers, not bytes. If your system has them, hd (or hexdump -C) or xxd will provide less surprising outputs - if not, od -t x1 is a POSIX-standard way to get byte-by-byte hex output. You can use od -t x1c to show both the byte hex values and the corresponding letters.

If you have xxd (which ships with vim), you can use xxd -r to convert back from hex (from the same format xxd produces). If you just have plain hex (just the '4161', which is produced by xxd -p) you can use xxd -r -p to convert back.

What's the Use of '\r' escape sequence?

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.

The cursor is the position where the next characters will be rendered.

So, printing a \r allows to override the current line of the terminal emulator.

Tom Zych figured why the output of your program is o world while the \r is at the end of the line and you don't print anything after that:

When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world.

The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r has no effect.

See https://en.wikipedia.org/wiki/Carriage_return

Here is a usage example of \r:

#include <stdio.h>
#include <unistd.h>

int main()
{
        char chars[] = {'-', '\\', '|', '/'};
        unsigned int i;

        for (i = 0; ; ++i) {
                printf("%c\r", chars[i % sizeof(chars)]);
                fflush(stdout);
                usleep(200000);
        }

        return 0;
}

It repeatedly prints the characters - \ | / at the same position to give the illusion of a rotating | in the terminal.

How to set the color of "placeholder" text?

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

Reorder / reset auto increment primary key

My opinion is to create a new column called row_order. then reorder that column. I'm not accepting the changes to the primary key. As an example, if the order column is banner_position, I have done something like this, This is for deleting, updating, creating of banner position column. Call this function reorder them respectively.

public function updatePositions(){
    $offers = Offer::select('banner_position')->orderBy('banner_position')->get();
    $offersCount = Offer::max('banner_position');
    $range = range(1, $offersCount);

    $existingBannerPositions = [];
    foreach($offers as $offer){
        $existingBannerPositions[] = $offer->banner_position;
    }
    sort($existingBannerPositions);
    foreach($existingBannerPositions as $key => $position){
        $numbersLessThanPosition = range(1,$position);
        $freshNumbersLessThanPosition = array_diff($numbersLessThanPosition, $existingBannerPositions);
        if(count($freshNumbersLessThanPosition)>0) {
            $existingBannerPositions[$key] = current($freshNumbersLessThanPosition);
            Offer::where('banner_position',$position)->update(array('banner_position'=> current($freshNumbersLessThanPosition)));
        }
    }
}

How can I have grep not print out 'No such file or directory' errors?

I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).

I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:

find /etc -type f -exec grep -nHi -e "widehat" {} \;

Instead of:

grep -nRHi -e "widehat" /etc

Check whether specific radio button is checked

$("input[@name='<%=test2.ClientID%>']:checked");

use this and here ClientID fetch random id created by .net.

Java integer list

Let's use some java 8 feature:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(System.out::println);

If you need to store the numbers you can collect them into a collection eg:

List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
  .boxed()
  .collect(Collectors.toList());

And some delay added:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(x -> {
    System.out.println(x);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // Do something with the exception
    }  
  });

Unicode character in PHP string

PHP 7.0.0 has introduced the "Unicode codepoint escape" syntax.

It's now possible to write Unicode characters easily by using a double-quoted or a heredoc string, without calling any function.

$unicodeChar = "\u{1000}";

Show Youtube video source into HTML5 video tag?

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

Can table columns with a Foreign Key be NULL?

Yes, the value can be NULL, but you must be explicit. I have experienced this same situation before, and it's easy to forget WHY this happens, and so it takes a little bit to remember what needs to be done.

If the data submitted is cast or interpreted as an empty string, it will fail. However, by explicitly setting the value to NULL when INSERTING or UPDATING, you're good to go.

But this is the fun of programming, isn't it? Creating our own problems and then fixing them! Cheers!

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

How to fix committing to the wrong Git branch?

So if your scenario is that you've committed to master but meant to commit to another-branch (which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.

// if your branch doesn't exist, then add the -b argument 
git checkout -b another-branch
git branch --force master origin/master

Now all your commits to master will be on another-branch.

Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/

How to stash my previous commit?

An alternative solution uses the stash:

Before:

~/dev/gitpro $git stash list

~/dev/gitpro $git log --oneline -3

* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
  1. git reset head~1 <--- head shifted one back to c222; working still contains c111 changes
  2. git stash push -m "commit 111" <--- staging/working (containing c111 changes) stashed; staging/working rolled back to revised head (containing c222 changes)
  3. git reset head~1 <--- head shifted one back to c333; working still contains c222 changes
  4. git stash push -m "commit 222" <--- staging/working (containing c222 changes) stashed; staging/working rolled back to revised head (containing c333 changes)
  5. git stash pop stash@{1} <--- oldest stash entry with c111 changes removed & applied to staging/working
  6. git commit -am "commit 111" <-- new commit with c111's changes becomes new head

note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).

note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)

After:

~/dev/gitpro $git stash list

stash@{0}: On master: c222

~/dev/gitpro $git log -2 --oneline

* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

How to get the index with the key in Python dictionary?

Dictionaries in python have no order. You could use a list of tuples as your data structure instead.

d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]

Then this code could be used to find the locations of keys with a specific value

locations = [i for i, t in enumerate(newd) if t[0]=='b']

>>> [1]

How to configure Spring Security to allow Swagger URL to be accessed without authentication

For those who using a newer swagger 3 version org.springdoc:springdoc-openapi-ui

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
    }
}

python global name 'self' is not defined

It should be something like:

class Person:
   def setavalue(self, name):         
      self.myname = name      
   def printaname(self):         
      print "Name", self.myname           

def main():
   p = Person()
   p.setavalue("harry")
   p.printaname()  

Editable 'Select' element

Similar to answer above but without the absolute positioning:

<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option> 
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>

So create a input box and put it over the top of the combobox