Programs & Examples On #Myeclipse

Commercial J2EE IDE and Web development tool suite for the Eclipse open-source platform.

Mvn install or Mvn package

from http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

package: take the compiled code and package it in its distributable format, such as a JAR.

install: install the package into the local repository, for use as a dependency in other projects locally

So the answer to your question is, it depends on whether you want it in installed into your local repo. Install will also run package because it's higher up in the goal phase stack.

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

In your mysql config file, which is present in /etc/my.cnf make the below changes and then restart mysqld dameon process

[client]
socket=/var/lib/mysql/mysql.sock

As well check this related thread

Can't connect to local MySQL server through socket '/tmp/mysql.sock

How do I change the JAVA_HOME for ant?

Though the environment variable JAVA_HOME set correctly, the ant may use the configured JRE within the each build.xml or any build files.

To check what version of the JRE the ant is using, right click on the build file -> select the build ant which displays the details about the tasks to choose etc, select the JRE which you want to use.

Its advisable to use the project level settings or just at the workspace level.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

You have Qwt which is mature. There is a 3D version lurking somewhere. However, I have never been satisfied with the aesthetic result.

It may be worth waiting for Qt3D to come out to write something better yourself easily.

Change Volley timeout duration

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.

Event when window.location.href changes

Have you tried beforeUnload? This event fires immediately before the page responds to a navigation request, and this should include the modification of the href.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    <META NAME="Generator" CONTENT="TextPad 4.6">
    <META NAME="Author" CONTENT="?">
    <META NAME="Keywords" CONTENT="?">
    <META NAME="Description" CONTENT="?">
    </HEAD>

         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
            <script type="text/javascript">
            $(document).ready(function(){
                $(window).unload(
                        function(event) {
                            alert("navigating");
                        }
                );
                $("#theButton").click(
                    function(event){
                        alert("Starting navigation");
                        window.location.href = "http://www.bbc.co.uk";
                    }
                );

            });
            </script>


    <BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">

        <button id="theButton">Click to navigate</button>

        <a href="http://www.google.co.uk"> Google</a>
    </BODY>
    </HTML>

Beware, however, that your event will fire whenever you navigate away from the page, whether this is because of the script, or somebody clicking on a link. Your real challenge, is detecting the different reasons for the event being fired. (If this is important to your logic)

Resize image with javascript canvas (smoothly)

I created a library that allows you to downstep any percentage while keeping all the color data.

https://github.com/danschumann/limby-resize/blob/master/lib/canvas_resize.js

That file you can include in the browser. The results will look like photoshop or image magick, preserving all the color data, averaging pixels, rather than taking nearby ones and dropping others. It doesn't use a formula to guess the averages, it takes the exact average.

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

Content-Disposition: attachment; filename=quot.pdf;

See content-disposition on the wikipedia MIME page.

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

Generate JSON string from NSDictionary in iOS

This will work in swift4 and swift5.

let dataDict = "the dictionary you want to convert in jsonString" 

let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)

let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

print(jsonString)

Difference between <input type='button' /> and <input type='submit' />

A 'button' is just that, a button, to which you can add additional functionality using Javascript. A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript).

Difference between SRC and HREF

From W3:

When the A element's href attribute is set, the element defines a source anchor for a link that may be activated by the user to retrieve a Web resource. The source anchor is the location of the A instance and the destination anchor is the Web resource.

Source: http://www.w3.org/TR/html401/struct/links.html

This attribute specifies the location of the image resource. Examples of widely recognized image formats include GIF, JPEG, and PNG.

Source: http://www.w3.org/TR/REC-html40/struct/objects.html

Boolean.parseBoolean("1") = false...?

According to the documentation (emphasis mine):

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How do you concatenate Lists in C#?

Take a look at my implementation. It's safe from null lists.

 IList<string> all= new List<string>();

 if (letterForm.SecretaryPhone!=null)// first list may be null
     all=all.Concat(letterForm.SecretaryPhone).ToList();

 if (letterForm.EmployeePhone != null)// second list may be null
     all= all.Concat(letterForm.EmployeePhone).ToList(); 

 if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
     all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

Python BeautifulSoup extract text between element

The BeautifulSoup documentation provides an example about removing objects from a document using the extract method. In the following example the aim is to remove all comments from the document:

Removing Elements

Once you have a reference to an element, you can rip it out of the tree with the extract method. This code removes all the comments from a document:

from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup("""1<!--The loneliest number-->
                    <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup
# 1
# <a>2<b>3</b></a>

Save each sheet in a workbook to separate CSV files

And here's my solution should work with Excel > 2000, but tested only on 2007:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

(OT: I wonder if SO will replace some of my minor blogging)

How to start a Process as administrator mode in C#

First of all you need to include in your project

using System.Diagnostics;

After that you could write a general method that you could use for different .exe files that you want to use. It would be like below:

public void ExecuteAsAdmin(string fileName)
{
    Process proc = new Process();
    proc.StartInfo.FileName = fileName;
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.Verb = "runas";
    proc.Start();
}

If you want to for example execute notepad.exe then all you do is you call this method:

ExecuteAsAdmin("notepad.exe");

When to use self over $this?

I believe question was not whether you can call the static member of the class by calling ClassName::staticMember. Question was what's the difference between using self::classmember and $this->classmember.

For e.g., both of the following examples work without any errors, whether you use self:: or $this->

class Person{
    private $name;
    private $address;

    public function __construct($new_name,$new_address){
        $this->name = $new_name;
        $this->address = $new_address;
    }
}

class Person{
    private $name;
    private $address;
    public function __construct($new_name,$new_address){
        self::$name = $new_name;
        self::$address = $new_address;
    }
}

Single line sftp from terminal

Or echo 'put {path to file}' | sftp {user}@{host}:{dir}, which would work in both unix and powershell.

Chmod 777 to a folder and all contents

If you are going for a console command it would be:

chmod -R 777 /www/store. The -R (or --recursive) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

chmod -R 777 ./

If you need more info about chmod command see: File permission

How to define a default value for "input type=text" without using attribute 'value'?

You can set the value property using client script after the element is created:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

Javascript change font color

Don't use <font color=. It's a really old fashioned way to style text and some browsers even don't even support it anymore.

caniuse lists it as obsolete, and strongly recommends not using the <font> tag. The same is with MDN

Do not use this element! Though once normalized in HTML 3.2, it was deprecated in HTML 4.01, at the same time as all elements related to styling only, then obsoleted in HTML5.

Starting with HTML 4, HTML does not convey styling information anymore (outside the element or the style attribute of each element). For any new web development, styling should be written using CSS only.

The former behavior of the element can be achieved, and even better controlled using the CSS Fonts CSS properties.

If we look at when the 4.01 standard was published we see it was published in 1999

published html5 standard

where <font> was officially deprecated, meaning it is still supported but shouldn't be used anymore as it will go away in the newer standard.

And in the html5 standard released in August 2014 it was deemed obsolete and non conforming.

To achieve the desired effect use spans and css:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    return '<span style="color:'+thecolor+'">'+thetext+'</span>';
}
document.write(givemecolor('green',"Hello, I'm green"));
document.write(givemecolor('red',"Hello, I'm red"));
_x000D_
body {
  background: #333;
  color: #eee;
}
_x000D_
_x000D_
_x000D_

update

This question and answer are from 2012 and now I wouldn't recommend using document.write as it needs to be executed when the document is rendered first time. I had used it back then because I assumed OP was wishing to use it in such a way. I'd recommend using a more conventional way to insert the custom elements you wish to use, at the place you wish to insert them, without relying on document rendering and when and where the script is executed.

Native:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    var span = document.createElement('span');
    span.style.color = thecolor;
    span.innerText = thetext;
    return span;
}
var container = document.getElementById('textholder');
container.append(givemecolor('green', "Hello I'm green"));
container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
function givemecolor(thecolor, thetext)
{
    var $span = $("<span>");
    $span.css({color:thecolor});
    $span.text(thetext);
    return $span;
}
var $container = $('#textholder');
$container.append(givemecolor('green', "Hello I'm green"));
$container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

How to pass a parameter to routerLink that is somewhere inside the URL?

constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.queryParams.subscribe(params => {
  console.log(params['type'])
  });  }

This works for me!

How do I convert a decimal to an int in C#?

You can't.

Well, of course you could, however an int (System.Int32) is not big enough to hold every possible decimal value.

That means if you cast a decimal that's larger than int.MaxValue you will overflow, and if the decimal is smaller than int.MinValue, it will underflow.

What happens when you under/overflow? One of two things. If your build is unchecked (i.e., the CLR doesn't care if you do), your application will continue after the value over/underflows, but the value in the int will not be what you expected. This can lead to intermittent bugs and may be hard to fix. You'll end up your application in an unknown state which may result in your application corrupting whatever important data its working on. Not good.

If your assembly is checked (properties->build->advanced->check for arithmetic overflow/underflow or the /checked compiler option), your code will throw an exception when an under/overflow occurs. This is probably better than not; however the default for assemblies is not to check for over/underflow.

The real question is "what are you trying to do?" Without knowing your requirements, nobody can tell you what you should do in this case, other than the obvious: DON'T DO IT.

If you specifically do NOT care, the answers here are valid. However, you should communicate your understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an unchecked block

unchecked
{
  // do your conversions that may underflow/overflow here
}

That way people coming behind you understand you don't care, and if in the future someone changes your builds to /checked, your code won't break unexpectedly.

If all you want to do is drop the fractional portion of the number, leaving the integral part, you can use Math.Truncate.

decimal actual = 10.5M;
decimal expected = 10M;
Assert.AreEqual(expected, Math.Truncate(actual));

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

How can I make my website's background transparent without making the content (images & text) transparent too?

You probably want an extra wrapper. use a div for the background and position it below your content..

http://jsfiddle.net/pixelass/42F2j/

HTML

<div id="background-image"></div>
<div id="content">
    Here is the content at opacity 1
    <img src="http://lorempixel.com/100/50/fashion/1/">

</div>

CSS

#background-image {
    background-image: url(http://lorempixel.com/400/200/sports/1/);
    opacity:0.4;
    position:absolute;
    top:0;
    left:0;
    height:200px;
    width:400px;
    z-index:0;
}
#content {
    z-index:1;
    position:relative;
}

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

@Raphael your solution does work. I encountered the same problem and solved it by increasing the maximum execution time to 180. There is an easier way to do it though:

  1. Open the Xampp control panel

  2. Click on 'config' behind 'Apache'

  3. Select 'PHP (php.ini)' from the dropdown -> A file should now open in your text editor

  4. Press ctrl+f and search for 'max_execution_time', you should fine a line which only says

    max_execution_time=30

  5. Change 30 to a bigger number (180 worked for me), like this:

    max_execution_time=180

  6. Save the file

  7. 'Stop' Apache server

  8. Close Xampp

  9. Restart Xampp

  10. 'Start' Apache server

  11. Update Wordpress from the Admin dashboard

  12. Enjoy ;)

Making the Android emulator run faster

UPDATE: Now that an Intel x86 image is available, the best answer is by zest above.

As CommonsWare has correctly pointed out, the emulator is slow because it emulates an ARM CPU, which requires translation to Intel opcodes. This virtualization chews up CPU.

To make the emulator faster, you have to give it more CPU. Start with a fast CPU or upgrade if you can.

Then, give the emulator more of the CPU you have:

  1. Disable Hyperthreading - Since the emulator doesn't appear to utilize more than one core, hyperthreading actually reduces the amount of overall CPU time the emulator will get. Disabling HT will slow down apps that take advantage of multiple CPUs. Hyperthreading must be disabled in your BIOS.
  2. Make the emulator run on a CPU other than CPU 0 - This has a much smaller impact than turning off HT, but it helps some. On Windows, you can specify which CPU a process will run on. Many apps will chew up CPU 0, and by default the emulator runs on CPU 0. I change the emulator to run on the last one. Note that on OS X you cannot set affinity (see: https://superuser.com/questions/149312/how-to-set-processor-affinity-on-a-mac).

I'm seeing somewhere around a 50% improvement with these two changes in place.

To set processor affinity on Windows 7:

  1. Open Task Manager
  2. Click View All Processes (to run as administrator, otherwise you can't set processor affinity)
  3. Right click on emulator.exe and choose Set Affinity...
  4. On the Set Affinity dialog, select just the last CPU

Note: When you change affinity in this way, it's only changed for the lifetime of the process. Next start, you have to do it again.

enter image description here

dlib installation on Windows 10

So basically I have been searching the solution for two days. I tried everything

  • Installing Cmake
  • Adding path
  • installing dlib from the links mentioned in the answers
  • Installing ## Heading ## numpy, scipy, matplotlib, pandas
  • etc etc etc

BUT THE ONLY SOLUTION THAT WORKED WAS INSTALLING MICROSOFT VISUAL STUDIO C++

After installing MS VS C++ I ran command pip install dlib and it is working like a charm. BEST OF LUCK

Link to download Visual Studio C++

https://visualstudio.microsoft.com/thank-you-for-downloading-visual-studio-for-cplusplus/?sku=Community&rel=16&rid=30005

How to validate domain credentials?

Here's how to determine a local user:

    public bool IsLocalUser()
    {
        return windowsIdentity.AuthenticationType == "NTLM";
    }

Edit by Ian Boyd

You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.

Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:

Why the NTLM Plug-in is Needed

NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.

Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.

By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.

How the Plug-in Works

The Verifier plug detects the following errors:

  • The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).

  • The target name in the call to InitializeSecurityContext is NULL.

  • The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.

The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).

The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.

NTLM Stops

5000 – Application Has Explicitly Selected NTLM Package

Severity – Error

The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.

How to Fix this Error

The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.

APIs(parameter) Used by Application    Incorrect Value  Correct Value  
=====================================  ===============  ========================
AcquireCredentialsHandle (pszPackage)  “NTLM”           NEGOSSP_NAME “Negotiate”

Truncate (not round off) decimal numbers in javascript

Here is simple but working function to truncate number upto 2 decimal places.

           function truncateNumber(num) {
                var num1 = "";
                var num2 = "";
                var num1 = num.split('.')[0];
                num2 = num.split('.')[1];
                var decimalNum = num2.substring(0, 2);
                var strNum = num1 +"."+ decimalNum;
                var finalNum = parseFloat(strNum);
                return finalNum;
            }

X-Frame-Options on apache

I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.

To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):

Header set X-Frame-Options ALLOW-FROM http://to.be.deleted.com early
Header unset X-Frame-Options

The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.

I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

HTML button opening link in new tab

With Bootstrap you can use an anchor like a button.

<a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>

And use target="_blank" to open the link in a new tab.

How to redirect page after click on Ok button on sweet alert?

function confirmDetete(ctl, event) {

    debugger;
    event.preventDefault();
    var defaultAction = $(ctl).prop("href");
    swal({
        title: "Are you sure?",
        text: "You will  be able to add it back again!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "Cancel",
        closeOnConfirm: false,
        closeOnCancel: false
    },
        function (isConfirm) {
            if (isConfirm) {
                $.get(ctl);
                swal({
                    title: "success",
                    text: "Deleted",
                    confirmButtonText: "ok",
                    allowOutsideClick: "true"
                }, function () { window.location.href = ctl })

     // $("#signupform").submit();
            } else {
                swal("Cancelled", "Is safe :)", "success");

            }
        });
}

Changing Tint / Background color of UITabBar

There are some good ideas in the existing answers, many work slightly differently and what you choose will also depend on which devices you target and what kind of look you're aiming to achieve. UITabBar is notoriously unintuitive when it come to customizing its appearance, but here are a few more tricks that may help:

1). If you're looking to get rid of the glossy overlay for a more flat look do:

tabBar.backgroundColor = [UIColor darkGrayColor]; // this will be your background
[tabBar.subviews[0] removeFromSuperview]; // this gets rid of gloss

2). To set custom images to the tabBar buttons do something like:

for (UITabBarItem *item in tabBar.items){
    [item setFinishedSelectedImage:selected withFinishedUnselectedImage:unselected];
    [item setImageInsets:UIEdgeInsetsMake(6, 0, -6, 0)];
}

Where selected and unselected are UIImage objects of your choice. If you'd like them to be a flat colour, the simplest solution I found is to create a UIView with the desired backgroundColor and then just render it into a UIImage with the help of QuartzCore. I use the following method in a category on UIView to get a UIImage with the view's contents:

- (UIImage *)getImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [[UIScreen mainScreen]scale]);
    [[self layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

3) Finally, you may want to customize the styling of the buttons' titles. Do:

for (UITabBarItem *item in tabBar.items){
    [item setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                [UIColor redColor], UITextAttributeTextColor,
                [UIColor whiteColor], UITextAttributeTextShadowColor,
                [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
                [UIFont boldSystemFontOfSize:18], UITextAttributeFont,
            nil] forState:UIControlStateNormal];
}

This lets you do some adjustments, but still quite limited. Particularly, you cannot freely modify where the text is placed within the button, and cannot have different colours for selected/unselected buttons. If you want to do more specific text layout, just set UITextAttributeTextColor to be clear and add your text into the selected and unselected images from part (2).

Make browser window blink in task Bar

I've made a jQuery plugin for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in Firefox, Chrome, Safari, IE6, IE7 and IE8.

Here is an example on how to use it:

$.titleAlert("New mail!", {
    requireBlur:true,
    stopOnFocus:true,
    interval:600
});

If you're not using jQuery, you might still want to look at the source code (there are a few quirky bugs and edge cases that you need to work around when doing title blinking if you want to fully support all major browsers).

android.content.res.Resources$NotFoundException: String resource ID #0x0

Change

dateTime.setText(app.getTotalDl());

To

dateTime.setText(String.valueOf(app.getTotalDl()));

There are different versions of setText - one takes a String and one takes an int resource id. If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.

I guess app.getTotalDl() returns an int. You need to specifically tell setText to set it to the String value of this int.

setText (int resid) vs setText (CharSequence text)

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

Keep background image fixed during scroll using css

Just add background-attachment to your code

body {
    background-position: center;
    background-image: url(../images/images5.jpg);
    background-attachment: fixed;
}

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

I just think of Rebuild as performing the Clean first followed by the Build. Perhaps I am wrong ... comments?

Convert string (without any separator) to list

Did you try list(x)??

 y = '+123-456-7890'
 c =list(y)
 c

['+', '1', '2', '3', '-', '4', '5', '6', '-', '7', '8', '9', '0']

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.

How do I pass a variable by reference?

Aside from all the great explanations on how this stuff works in Python, I don't see a simple suggestion for the problem. As you seem to do create objects and instances, the pythonic way of handling instance variables and changing them is the following:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.Change()
        print self.variable

    def Change(self):
        self.variable = 'Changed'

In instance methods, you normally refer to self to access instance attributes. It is normal to set instance attributes in __init__ and read or change them in instance methods. That is also why you pass self als the first argument to def Change.

Another solution would be to create a static method like this:

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.variable = PassByReference.Change(self.variable)
        print self.variable

    @staticmethod
    def Change(var):
        var = 'Changed'
        return var

Webdriver Screenshot

Yes, we have a way to get screenshot extension of .png using python webdriver

use below code if you working in python webriver.it is very simple.

driver.save_screenshot('D\folder\filename.png')

What exactly is a Maven Snapshot and why do we need it?

usually in maven we have two types of builds 1)Snapshot builds 2)Release builds

  1. snapshot builds:SNAPSHOT is the special version that indicate current deployment copy not like a regular version, maven checks the version for every build in the remote repository so the snapshot builds are nothing but development builds.

  2. Release builds:Release means removing the SNAPSHOT at the version for the build, these are the regular build versions.

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I had Java 1.8 but had to downgrade to Java 1.6 for some reason. When I uninstalled java 1.8 and ran the command "Java -Version" from the command prompt, I got the error -

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'

has value '1.6', but '1.8' is required. Error: could not find java.dll Error: Could not find Java SE Runtime Environment.

Uninstalling 1.6 and then reinstalling 1.6 fixed the issue for me :-)

Unzipping files

I wrote an unzipper in Javascript. It works.

It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

NB: the links are dead; I'll find a new host soon.

Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


Here's what the application code looks like in Javascript:

// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read.  This can take a few seconds on a
// large zip file, so it's asynchronous. 
var readFile = function(){
    $("#status").html("<br/>");
    var url= $("#urlToLoad").val();
    var doneReading = function(zip){
        extractEntries(zip);
    };

    var zipFile = new ZipFile(url, doneReading);
};


// this function extracts the entries from an instantiated zip
function extractEntries(zip){
    $('#report').accordion('destroy');

    // clear
    $("#report").html('');

    var extractCb = function(id) {
        // this callback is invoked with the entry name, and entry text
        // in my demo, the text is just injected into an accordion panel.
        return (function(entryName, entryText){
            var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
            $("#"+id).html(content);
            $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
            $('#report').accordion('destroy');
            $('#report').accordion({collapsible:true, active:false});
        });
    }

    // for each entry in the zip, extract it. 
    for (var i=0; i<zip.entries.length;  i++) {
        var entry = zip.entries[i];

        var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";

        // contrive an id for the entry, make it unique
        var randomId = "id-"+ Math.floor((Math.random() * 1000000000));

        entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
            "'></span></span></div>\n";

        // insert the info for one entry as the last child within the report div
        $("#report").append(entryInfo);

        // extract asynchronously
        entry.extract(extractCb(randomId));
    }
}

The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


It works, but I think that the utility is somewhat limited.

For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

VSCode regex find & replace submatch math?

Another simple example:

Search: style="(.+?)"
Replace: css={css`$1`}

Useful for converting HTML to JSX with emotion/css!

css divide width 100% to 3 column

Using this fiddle, you can play around with the width of each div. I've tried in both Chrome and IE and I notice a difference in width between 33% and 33.3%. I also notice a very small difference between 33.3% and 33.33%. I don't notice any difference further than this.

The difference between 33.33% and the theoretical 33.333...% is a mere 0.00333...%.

For arguments sake, say my screen width is 1960px; a fairly high but common resolution. The difference between these two widths is still only 0.065333...px.

So, further than two decimal places, the difference in precision is negligible.

100% width background image with an 'auto' height

You can use the CSS property background-size and set it to cover or contain, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).

Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.

body {
    background-image: url(image.jpg); /* image */
    background-position: center;      /* center the image */
    background-size: cover;           /* cover the entire window */
}

How to get duplicate items from a list using LINQ?

I was trying to solve the same with a list of objects and was having issues because I was trying to repack the list of groups into the original list. So I came up with looping through the groups to repack the original List with items that have duplicates.

public List<MediaFileInfo> GetDuplicatePictures()
{
    List<MediaFileInfo> dupes = new List<MediaFileInfo>();
    var grpDupes = from f in _fileRepo
                   group f by f.Length into grps
                   where grps.Count() >1
                   select grps;
    foreach (var item in grpDupes)
    {
        foreach (var thing in item)
        {
            dupes.Add(thing);
        }
    }
    return dupes;
}

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Unable to connect PostgreSQL to remote database using pgAdmin

For redhat linux

sudo vi /var/lib/pgsql9/data/postgresql.conf 

pgsql9 is the folder for the postgres version installed, might be different for others

changed listen_addresses = '*' from listen_addresses = ‘localhost’ and then

sudo /etc/init.d/postgresql stop
sudo /etc/init.d/postgresql start

Can an ASP.NET MVC controller return an Image?

if (!System.IO.File.Exists(filePath))
    return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
else
    return new FilePathResult(filePath, contentType);

SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

Find the unique values in a column and then sort them

sort sorts inplace so returns nothing:

In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a

Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)

So you have to call print a again after the call to sort.

Eg.:

In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)

[1 2 3 6 8]

Build error, This project references NuGet

Quick solution that worked like a charm for me and others:

If you are using VS 2015+, just remove the following lines from the .csproj file of your project:

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

In VS 2015+ Solution Explorer:

  1. Right-click project name -> Unload Project
  2. Right-click project name -> Edit .csproj
  3. Remove the lines specified above from the file and save
  4. Right-click project name -> Reload Project

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to get first element in a list of tuples?

you can unpack your tuples and get only the first element using a list comprehension:

l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]

output:

[1, 2]

this will work no matter how many elements you have in a tuple:

l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]

output:

[1, 2]

Modifying local variable from inside lambda

An alternative to AtomicInteger is to use an array (or any other object able to store a value):

final int ordinal[] = new int[] { 0 };
list.forEach ( s -> s.setOrdinal ( ordinal[ 0 ]++ ) );

But see the Stuart's answer: there might be a better way to deal with your case.

How to send email from SQL Server?

Here's an example of how you might concatenate email addresses from a table into a single @recipients parameter:

CREATE TABLE #emailAddresses (email VARCHAR(25))

INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')

DECLARE @recipients VARCHAR(MAX)
SELECT @recipients = COALESCE(@recipients + ';', '') + email 
FROM #emailAddresses

SELECT @recipients

DROP TABLE #emailAddresses

The resulting @recipients will be:

[email protected];[email protected];[email protected]

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

PHP PDO: charset, set names?

I test this code and

$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products  ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
    $id=$result['id'];
}

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

How do I find which program is using port 80 in Windows?

If you want to be really fancy, download TCPView from Sysinternals:

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, and XP, TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows.

How to execute a command in a remote computer?

try
{
    string AppPath = "\\\\spri11U1118\\SampleBatch\\Bin\\";
    string strFilePath = AppPath + "ABCED120D_XXX.bat";
    System.Diagnostics.Process proc = new System.Diagnostics.Process();

    proc.StartInfo.FileName = strFilePath;
    string pwd = "s44erver";

    proc.StartInfo.Domain = "abcd";
    proc.StartInfo.UserName = "sysfaomyulm";

    System.Security.SecureString secret = new System.Security.SecureString();
    foreach (char c in pwd)

        secret.AppendChar(c);

    proc.StartInfo.Password = secret;
    proc.StartInfo.UseShellExecute = false;

    proc.StartInfo.WorkingDirectory = "psexec \\\\spri11U1118\\SampleBatch\\Bin ";

    proc.Start();
    while (!proc.HasExited)
    {
        proc.Refresh();
        // Thread.Sleep(1000);
    }

    proc.Close();
}
catch (Exception ex)
{
    throw ex;
}

Convert Unicode to ASCII without errors in Python

I use this helper function throughout all of my projects. If it can't convert the unicode, it ignores it. This ties into a django library, but with a little research you could bypass it.

from django.utils import encoding

def convert_unicode_to_string(x):
    """
    >>> convert_unicode_to_string(u'ni\xf1era')
    'niera'
    """
    return encoding.smart_str(x, encoding='ascii', errors='ignore')

I no longer get any unicode errors after using this.

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Is there any way to set environment variables in Visual Studio Code?

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

How to fill Dataset with multiple tables?

If you are issuing a single command with several select statements, you might use NextResult method to move to next resultset within the datareader: http://msdn.microsoft.com/en-us/library/system.data.idatareader.nextresult.aspx

I show how it could look bellow:

public DataSet SelectOne(int id)
{
    DataSet result = new DataSet();
    using (DbCommand command = Connection.CreateCommand())
    {
        command.CommandText = @"
select * from table1
select * from table2
        ";

        var param = ParametersBuilder.CreateByKey(command, "ID", id, null);
        command.Parameters.Add(param);

        Connection.Open();
        using (DbDataReader reader = command.ExecuteReader())
        {
            result.MainTable.Load(reader);
            reader.NextResult();
            result.SecondTable.Load(reader);
            // ...
        }
        Connection.Close();
    }
    return result;
}

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

Deleting row from datatable in C#

I see a number of answers using the Remove method and others using the Delete method.

Remove (according to the docs) will immediately remove the record from the (local) table, and on Update, will not remove a missing record.

Delete in comparison changes the RowState to Deleted, and will update the server table on Update. Likewise, calling the AcceptChanges method before the Update to the server table will reset all your RowState(s) to Unchanged and nothing will flow to the server. (Still nursing my thumb after hitting this a number of times).

AngularJS: Basic example to use authentication in Single Page Application

I like the approach and implemented it on server-side without doing any authentication related thing on front-end

My 'technique' on my latest app is.. the client doesn't care about Auth. Every single thing in the app requires a login first, so the server just always serves a login page unless an existing user is detected in the session. If session.user is found, the server just sends index.html. Bam :-o

Look for the comment by "Andrew Joslin".

https://groups.google.com/forum/?fromgroups=#!searchin/angular/authentication/angular/POXLTi_JUgg/VwStpoWCPUQJ

manage.py runserver

You can run it for machines in your network by

./manage.py runserver 0.0.0.0:8000

And than you will be able to reach you server from any machine in your network. Just type on other machine in browser http://192.168.0.1:8000 where 192.168.0.1 is IP of you server... and it ready to go....

or in you case:

  1. On machine A in command line ./manage.py runserver 0.0.0.0:8000
  2. Than try in machine B in browser type http://A:8000
  3. Make a sip of beer.

Source from django docs

Finding the max value of an attribute in an array of objects

Comparison of three ONELINERS which handle minus numbers case (input in a array):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

_x000D_
_x000D_
var a = [
  {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
  {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;

document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
_x000D_
_x000D_

For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

_x000D_
_x000D_
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }

try {
  let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
_x000D_
_x000D_

Benchmark for the 4 element array

Is there a developers api for craigslist.org

Ultimately no. You can query for listings with a search string from an RSS feed such as this:

http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString

As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.

Craigslist Automated Posting API?

Write a note to craigslist asking them to open their API,

How to get primary key column in Oracle?

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'TABLE_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;

Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.

How to compile a static library in Linux?

Generate the object files with gcc, then use ar to bundle them into a static library.

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

Determining the path that a yum package installed to

Not in Linux at the moment, so can't double check, but I think it's:

rpm -ql ffmpeg

That should list all the files installed as part of the ffmpeg package.

IllegalMonitorStateException on wait() call

Not sure if this will help somebody else out or not but this was the key part to fix my problem in user "Tom Hawtin - tacklin"'s answer above:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

Just the fact that the "lock" is passed as an argument in synchronized() and it is also used in "lock".notifyAll();

Once I made it in those 2 places I got it working

py2exe - generate single executable file

The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.

Here is a more complete description of the bundle_file option quoted directly from the py2exe site*

Using "bundle_files" and "zipfile"

An easier (and better) way to create single-file executables is to set bundle_files to 1 or 2, and to set zipfile to None. This approach does not require extracting files to a temporary location, which provides much faster program startup.

Valid values for bundle_files are:

  • 3 (default) don't bundle
  • 2 bundle everything but the Python interpreter
  • 1 bundle everything, including the Python interpreter

If zipfile is set to None, the files will be bundle within the executable instead of library.zip.

Here is a sample setup.py:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
    windows = [{'script': "single.py"}],
    zipfile = None,
)

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I solved it this way:

First, I stopped all running containers:

docker-compose down

Then I executed a lsof command to find the process using the port (for me it was port 9000)

sudo lsof -i -P -n | grep 9000

Finally, I "killed" the process (in my case, it was a VSCode extension):

kill -9 <process id>

Get absolute path of initially run script

echo realpath(dirname(__FILE__));

If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!

What is your favorite C programming trick?

Declaring array's of pointer to functions for implementing finite state machines.

int (* fsm[])(void) = { ... }

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

Create Windows service from executable

You can check out my small free utility for service create\edit\delete operations. Here is create example:

Go to Service -> Modify -> Create

enter image description here

Executable file (google drive): [Download]

Source code: [Download]

Blog post: [BlogLink]

Service editor class: WinServiceUtils.cs

How to reset the state of a Redux store?

for me what worked the best is to set the initialState instead of state:

  const reducer = createReducer(initialState,
  on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
    ...initialState
  })),

how to parse xml to java object?

JAXB is a reliable choice as it does xml to java classes mapping smoothely. But there are other frameworks available, here is one such:

https://code.google.com/p/xmappr/

jQuery Ajax calls and the Html.AntiForgeryToken()

I know there are a lot of other answers, but this article is nice and concise and forces you to check all of your HttpPosts, not just some of them:

http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/

It uses HTTP headers instead of trying to modify the form collection.

Server

//make sure to add this to your global action filters
[AttributeUsage(AttributeTargets.Class)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
        var request = filterContext.HttpContext.Request;

        //  Only validate POSTs
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        {
            //  Ajax POSTs and normal form posts have to be treated differently when it comes
            //  to validating the AntiForgeryToken
            if (request.IsAjaxRequest())
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value 
                    : null;

                AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
            }
        }
    }
}

Client

var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;

$.ajax({
    type: 'POST',
    url: '/Home/Ajax',
    cache: false,
    headers: headers,
    contentType: 'application/json; charset=utf-8',
    data: { title: "This is my title", contents: "These are my contents" },
    success: function () {
        ...
    },
    error: function () {
        ...
    }
});

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

How to open existing project in Eclipse

i use Mac and i deleted ADT bundle source. faced the same error so i went to project > clean and adb ran normally.

Use a normal link to submit a form

Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;".

How to describe table in SQL Server 2008?

According to this documentation:

DESC MY_TABLE

is equivalent to

SELECT column_name "Name", nullable "Null?", concat(concat(concat(data_type,'('),data_length),')') "Type" FROM user_tab_columns WHERE table_name='TABLE_NAME_TO_DESCRIBE';

I've roughly translated that to the SQL Server equivalent for you - just make sure you're running it on the EX database.

SELECT column_name AS [name],
       IS_NULLABLE AS [null?],
       DATA_TYPE + COALESCE('(' + CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1
                                  THEN 'Max'
                                  ELSE CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5))
                                  END + ')', '') AS [type]
FROM   INFORMATION_SCHEMA.Columns
WHERE  table_name = 'EMP_MAST'

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

jQuery replace one class with another

You can use .removeClass and .addClass. More in http://api.jquery.com.

How to hide UINavigationBar 1px bottom line

In iOS8, if you set the UINavigationBar.barStyle to .Black you can set the bar's background as plain color without the border.

In Swift:

UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().barStyle = UIBarStyle.Black
UINavigationBar.appearance().barTintColor = UIColor.redColor()

if variable contains

You might want indexOf

if (code.indexOf("ST1") >= 0) { ... }
else if (code.indexOf("ST2") >= 0) { ... }

It checks if contains is anywhere in the string variable code. This requires code to be a string. If you want this solution to be case-insensitive you have to change the case to all the same with either String.toLowerCase() or String.toUpperCase().

You could also work with a switch statement like

switch (true) {
    case (code.indexOf('ST1') >= 0):
        document.write('code contains "ST1"');
        break;
    case (code.indexOf('ST2') >= 0):
        document.write('code contains "ST2"');        
        break;        
    case (code.indexOf('ST3') >= 0):
        document.write('code contains "ST3"');
        break;        
    }?

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :

 var jsSerializer = new JavaScriptSerializer();
 jsSerializer.MaxJsonLength = Int32.MaxValue;

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Also have a problem with beta 5 and AFNetworking 1.3 when running on iOS 8 simulator that results in a connection error:

Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

The same code works fine on iOS 7 and 7.1 simulators and my debugging proxy shows that the failure occurs before a connection is actually attempted (i.e. no requests logged).

I have tracked the failure to NSURLConnection and reported bug to Apple. See line 5 in attached image:

NSURLConnection client delegate did fail error.

Changing to use https allows connection from iOS 8 simulators albeit with intermittent errors.

Problem is still present in Xcode 6.01 (gm).

R - test if first occurrence of string1 is followed by string2

> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE

basically, look for everything at the beginning except _, and then the _2.

+1 to @Ananda_Mahto for suggesting grepl instead of grep.

Java collections convert a string to a list of characters

The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

Label encoding across multiple columns in scikit-learn

How about this?

def MultiColumnLabelEncode(choice, columns, X):
    LabelEncoders = []
    if choice == 'encode':
        for i in enumerate(columns):
            LabelEncoders.append(LabelEncoder())
        i=0    
        for cols in columns:
            X[:, cols] = LabelEncoders[i].fit_transform(X[:, cols])
            i += 1
    elif choice == 'decode': 
        for cols in columns:
            X[:, cols] = LabelEncoders[i].inverse_transform(X[:, cols])
            i += 1
    else:
        print('Please select correct parameter "choice". Available parameters: encode/decode')

It is not the most efficient, however it works and it is super simple.

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

Error inflating class android.support.v7.widget.Toolbar?

I have fixed this problem by modifying app build.gradle file.

For Gradle Plugin 2.0+

 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
 }  

For Gradle Plugin 1.5

 android {  
   defaultConfig {  

     generatedDensities = []  
  }  

  aaptOptions {  
    additionalParameters "--no-version-vectors"  
  }  
 } 

What happens if you mount to a non-empty mount point with fuse?

For me the error message goes away if I unmount the old mount before mounting it again:

fusermount -u /mnt/point

If it's not already mounted you get a non-critical error:

$ fusermount -u /mnt/point

fusermount: entry for /mnt/point not found in /etc/mtab

So in my script I just put unmount it before mounting it.

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

What is the default initialization of an array in Java?

From the Java Language Specification:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.

How to click a href link using Selenium

How to click on link without using click method in selenum?

This is a tricky question. Follow the below steps:

driver.get("https://www.google.com");
String gmaillink= driver.findElement(By.xpath("//a[@href='https://mail.google.com/mail/?tab=wm&ogbl']")).getAttribute("href");
System.out.println(gmaillink);
driver.get(gmaillink);

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Same thing.. makes no difference at all... htm was used in the days where only 3 letter extensions were common.

What is the difference between id and class in CSS, and when should I use them?

For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.

Remove non-numeric characters (except periods and commas) from a string

I'm surprised there's been no mention of filter_var here for this being such an old question...

PHP has a built in method of doing this using sanitization filters. Specifically, the one to use in this situation is FILTER_SANITIZE_NUMBER_FLOAT with the FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND flags. Like so:

$numeric_filtered = filter_var("AR3,373.31", FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
echo $numeric_filtered; // Will print "3,373.31"

It might also be worthwhile to note that because it's built-in to PHP, it's slightly faster than using regex with PHP's current libraries (albeit literally in nanoseconds).

How do I redirect in expressjs while passing some context?

I use a very simple but efficient technique in my app.js ( my entry point ) I define a variable like

let authUser = {};

Then I assign to it from my route page ( like after successful login )

authUser = matchedUser

It May be not the best approach but it fits my needs.

sql how to cast a select query

You just CAST() this way

SELECT cast(yourNumber as varchar(10))
FROM yourTable

Then if you want to JOIN based on it, you can use:

SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
    on cast(t1.yourNumber as varchar(10)) = t2.yourString

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

What is the difference between old style and new style classes in Python?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

Old-style classes don't.

class OldStyleClass():
    pass

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

Invalid shorthand property initializer

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that's solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

How to automatically redirect HTTP to HTTPS on Apache servers?

I needed this for something as simple as redirecting all http traffic from the default apache home page on my server to one served over https.

Since I'm still quite green when it comes to configuring apache, I prefer to avoid using mod_rewrite directly and instead went for something simpler like this:

<VirtualHost *:80>
  <Location "/">
     Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"
  </Location>
</VirtualHost>

<VirtualHost *:443>
  DocumentRoot "/var/www/html"
  SSLEngine on
  ...
</VirtualHost>

I like this because it allowed me to use apache variables and that way I didn't have to specify the actual host name since it's just an IP address without an associated domain name.

References: https://stackoverflow.com/a/40291044/2089675

How to select all elements with a particular ID in jQuery?

Your document should not contain two divs with the same id. This is invalid HTML, and as a result, the underlying DOM API does not support it.

From the HTML standard:

id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.

You can either assign different ids to each div and select them both using $('#id1, #id2). Or assign the same class to both elements (.cls for example), and use $('.cls') to select them both.

Pass object to javascript function

Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

If using ES6:

    function yourFunction(args){
        let defaults = {opt1: true, opt2: 'something'};
        let params = {...defaults, ...args}; // right-most object overwrites 
        console.log(params.opt1);
    }

Older Browsers using Object.assign(target, source):

    function yourFunction(args){
        var defaults = {opt1: true, opt2: 'something'};
        var params = Object.assign(defaults, args) // args overwrites as it is source
        console.log(params.opt1);
    }

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

You can try this

sudo apt-get install phpmyadmin php-mbstring php-gettext
sudo ln -s /usr/share/phpmyadmin/ /var/www/html/phpmyadmin
service apache2 restart

HTML Form: Select-Option vs Datalist-Option

Data List is a new HTML tag in HTML5 supported browsers. It renders as a text box with some list of options. For Example for Gender Text box it will give you options as Male Female when you type 'M' or 'F' in Text Box.

<input list="Gender">
<datalist id="Gender">
  <option value="Male">
  <option value="Female> 
</datalist>

List comprehension vs map

Cases

  • Common case: Almost always, you will want to use a list comprehension in python because it will be more obvious what you're doing to novice programmers reading your code. (This does not apply to other languages, where other idioms may apply.) It will even be more obvious what you're doing to python programmers, since list comprehensions are the de-facto standard in python for iteration; they are expected.
  • Less-common case: However if you already have a function defined, it is often reasonable to use map, though it is considered 'unpythonic'. For example, map(sum, myLists) is more elegant/terse than [sum(x) for x in myLists]. You gain the elegance of not having to make up a dummy variable (e.g. sum(x) for x... or sum(_) for _... or sum(readableName) for readableName...) which you have to type twice, just to iterate. The same argument holds for filter and reduce and anything from the itertools module: if you already have a function handy, you could go ahead and do some functional programming. This gains readability in some situations, and loses it in others (e.g. novice programmers, multiple arguments)... but the readability of your code highly depends on your comments anyway.
  • Almost never: You may want to use the map function as a pure abstract function while doing functional programming, where you're mapping map, or currying map, or otherwise benefit from talking about map as a function. In Haskell for example, a functor interface called fmap generalizes mapping over any data structure. This is very uncommon in python because the python grammar compels you to use generator-style to talk about iteration; you can't generalize it easily. (This is sometimes good and sometimes bad.) You can probably come up with rare python examples where map(f, *lists) is a reasonable thing to do. The closest example I can come up with would be sumEach = partial(map,sum), which is a one-liner that is very roughly equivalent to:

def sumEach(myLists):
    return [sum(_) for _ in myLists]
  • Just using a for-loop: You can also of course just use a for-loop. While not as elegant from a functional-programming viewpoint, sometimes non-local variables make code clearer in imperative programming languages such as python, because people are very used to reading code that way. For-loops are also, generally, the most efficient when you are merely doing any complex operation that is not building a list like list-comprehensions and map are optimized for (e.g. summing, or making a tree, etc.) -- at least efficient in terms of memory (not necessarily in terms of time, where I'd expect at worst a constant factor, barring some rare pathological garbage-collection hiccuping).

"Pythonism"

I dislike the word "pythonic" because I don't find that pythonic is always elegant in my eyes. Nevertheless, map and filter and similar functions (like the very useful itertools module) are probably considered unpythonic in terms of style.

Laziness

In terms of efficiency, like most functional programming constructs, MAP CAN BE LAZY, and in fact is lazy in python. That means you can do this (in python3) and your computer will not run out of memory and lose all your unsaved data:

>>> map(str, range(10**100))
<map object at 0x2201d50>

Try doing that with a list comprehension:

>>> [str(n) for n in range(10**100)]
# DO NOT TRY THIS AT HOME OR YOU WILL BE SAD #

Do note that list comprehensions are also inherently lazy, but python has chosen to implement them as non-lazy. Nevertheless, python does support lazy list comprehensions in the form of generator expressions, as follows:

>>> (str(n) for n in range(10**100))
<generator object <genexpr> at 0xacbdef>

You can basically think of the [...] syntax as passing in a generator expression to the list constructor, like list(x for x in range(5)).

Brief contrived example

from operator import neg
print({x:x**2 for x in map(neg,range(5))})

print({x:x**2 for x in [-y for y in range(5)]})

print({x:x**2 for x in (-y for y in range(5))})

List comprehensions are non-lazy, so may require more memory (unless you use generator comprehensions). The square brackets [...] often make things obvious, especially when in a mess of parentheses. On the other hand, sometimes you end up being verbose like typing [x for x in.... As long as you keep your iterator variables short, list comprehensions are usually clearer if you don't indent your code. But you could always indent your code.

print(
    {x:x**2 for x in (-y for y in range(5))}
)

or break things up:

rangeNeg5 = (-y for y in range(5))
print(
    {x:x**2 for x in rangeNeg5}
)

Efficiency comparison for python3

map is now lazy:

% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=map(f,xs)'
1000000 loops, best of 3: 0.336 usec per loop            ^^^^^^^^^

Therefore if you will not be using all your data, or do not know ahead of time how much data you need, map in python3 (and generator expressions in python2 or python3) will avoid calculating their values until the last moment necessary. Usually this will usually outweigh any overhead from using map. The downside is that this is very limited in python as opposed to most functional languages: you only get this benefit if you access your data left-to-right "in order", because python generator expressions can only be evaluated the order x[0], x[1], x[2], ....

However let's say that we have a pre-made function f we'd like to map, and we ignore the laziness of map by immediately forcing evaluation with list(...). We get some very interesting results:

% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(map(f,xs))'                                                                                                                                                
10000 loops, best of 3: 165/124/135 usec per loop        ^^^^^^^^^^^^^^^
                    for list(<map object>)

% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=[f(x) for x in xs]'                                                                                                                                      
10000 loops, best of 3: 181/118/123 usec per loop        ^^^^^^^^^^^^^^^^^^
                    for list(<generator>), probably optimized

% python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(f(x) for x in xs)'                                                                                                                                    
1000 loops, best of 3: 215/150/150 usec per loop         ^^^^^^^^^^^^^^^^^^^^^^
                    for list(<generator>)

In results are in the form AAA/BBB/CCC where A was performed with on a circa-2010 Intel workstation with python 3.?.?, and B and C were performed with a circa-2013 AMD workstation with python 3.2.1, with extremely different hardware. The result seems to be that map and list comprehensions are comparable in performance, which is most strongly affected by other random factors. The only thing we can tell seems to be that, oddly, while we expect list comprehensions [...] to perform better than generator expressions (...), map is ALSO more efficient that generator expressions (again assuming that all values are evaluated/used).

It is important to realize that these tests assume a very simple function (the identity function); however this is fine because if the function were complicated, then performance overhead would be negligible compared to other factors in the program. (It may still be interesting to test with other simple things like f=lambda x:x+x)

If you're skilled at reading python assembly, you can use the dis module to see if that's actually what's going on behind the scenes:

>>> listComp = compile('[f(x) for x in xs]', 'listComp', 'eval')
>>> dis.dis(listComp)
  1           0 LOAD_CONST               0 (<code object <listcomp> at 0x2511a48, file "listComp", line 1>) 
              3 MAKE_FUNCTION            0 
              6 LOAD_NAME                0 (xs) 
              9 GET_ITER             
             10 CALL_FUNCTION            1 
             13 RETURN_VALUE         
>>> listComp.co_consts
(<code object <listcomp> at 0x2511a48, file "listComp", line 1>,)
>>> dis.dis(listComp.co_consts[0])
  1           0 BUILD_LIST               0 
              3 LOAD_FAST                0 (.0) 
        >>    6 FOR_ITER                18 (to 27) 
              9 STORE_FAST               1 (x) 
             12 LOAD_GLOBAL              0 (f) 
             15 LOAD_FAST                1 (x) 
             18 CALL_FUNCTION            1 
             21 LIST_APPEND              2 
             24 JUMP_ABSOLUTE            6 
        >>   27 RETURN_VALUE

 

>>> listComp2 = compile('list(f(x) for x in xs)', 'listComp2', 'eval')
>>> dis.dis(listComp2)
  1           0 LOAD_NAME                0 (list) 
              3 LOAD_CONST               0 (<code object <genexpr> at 0x255bc68, file "listComp2", line 1>) 
              6 MAKE_FUNCTION            0 
              9 LOAD_NAME                1 (xs) 
             12 GET_ITER             
             13 CALL_FUNCTION            1 
             16 CALL_FUNCTION            1 
             19 RETURN_VALUE         
>>> listComp2.co_consts
(<code object <genexpr> at 0x255bc68, file "listComp2", line 1>,)
>>> dis.dis(listComp2.co_consts[0])
  1           0 LOAD_FAST                0 (.0) 
        >>    3 FOR_ITER                17 (to 23) 
              6 STORE_FAST               1 (x) 
              9 LOAD_GLOBAL              0 (f) 
             12 LOAD_FAST                1 (x) 
             15 CALL_FUNCTION            1 
             18 YIELD_VALUE          
             19 POP_TOP              
             20 JUMP_ABSOLUTE            3 
        >>   23 LOAD_CONST               0 (None) 
             26 RETURN_VALUE

 

>>> evalledMap = compile('list(map(f,xs))', 'evalledMap', 'eval')
>>> dis.dis(evalledMap)
  1           0 LOAD_NAME                0 (list) 
              3 LOAD_NAME                1 (map) 
              6 LOAD_NAME                2 (f) 
              9 LOAD_NAME                3 (xs) 
             12 CALL_FUNCTION            2 
             15 CALL_FUNCTION            1 
             18 RETURN_VALUE 

It seems it is better to use [...] syntax than list(...). Sadly the map class is a bit opaque to disassembly, but we can make due with our speed test.

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

How to work offline with TFS

Depending on which tool windows you have open, VS may or may not try to hit the team server automatically when it starts up.

For best results try this:

  1. Close all instances of visual studio
  2. Open an empty visual studio (no project/solution)
  3. See which windows are opened by default, if source control explorer or team explorer or any other windows that use team are opened (and activated) by default, close them or switch them to a background tab.
  4. Close visual studio

You should notice now that you can start visual studio without it trying to hit the TFS server.

I know its just an aside to your problem, but I hope you find this helpful!

Formatting a number with leading zeros in PHP

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);

Best way to store data locally in .NET (C#)

Just finished coding data storage for my current project. Here is my 5 cents.

I started with binary serialization. It was slow (about 30 sec for load of 100,000 objects) and it was creating a pretty big file on the disk as well. However, it took me a few lines of code to implement and I got my all storage needs covered. To get better performance I moved on custom serialization. Found FastSerialization framework by Tim Haynes on Code Project. Indeed it is a few times faster (got 12 sec for load, 8 sec for save, 100K records) and it takes less disk space. The framework is built on the technique outlined by GalacticJello in a previous post.

Then I moved to SQLite and was able to get 2 sometimes 3 times faster performance – 6 sec for load and 4 sec for save, 100K records. It includes parsing ADO.NET tables to application types. It also gave me much smaller file on the disk. This article explains how to get best performance out of ADO.NET: http://sqlite.phxsoftware.com/forums/t/134.aspx. Generating INSERT statements is a very bad idea. You can guess how I came to know about that. :) Indeed, SQLite implementation took me quite a bit of time plus careful measurement of time taking by pretty much every line of the code.

How to Add Stacktrace or debug Option when Building Android Studio Project

You can use GUI to add these gradle command line flags from

File > Settings > Build, Execution, Deployment > Compiler

For MacOS user, it's here

Android Studio > Preferences > Build, Execution, Deployment > Compiler

like this (add --stacktrace or --debug)

enter image description here

Note that the screenshot is from before 0.8.10, the option is no longer in the Compiler > Gradle section, it's now in a separate section named Compiler (Gradle-based Android Project)

With arrays, why is it the case that a[5] == 5[a]?

I know the question is answered, but I couldn't resist sharing this explanation.

I remember Principles of Compiler design, Let's assume a is an int array and size of int is 2 bytes, & Base address for a is 1000.

How a[5] will work ->

Base Address of your Array a + (5*size of(data type for array a))
i.e. 1000 + (5*2) = 1010

So,

Similarly when the c code is broken down into 3-address code, 5[a] will become ->

Base Address of your Array a + (size of(data type for array a)*5)
i.e. 1000 + (2*5) = 1010 

So basically both the statements are pointing to the same location in memory and hence, a[5] = 5[a].

This explanation is also the reason why negative indexes in arrays work in C.

i.e. if I access a[-5] it will give me

Base Address of your Array a + (-5 * size of(data type for array a))
i.e. 1000 + (-5*2) = 990

It will return me object at location 990.

Setting default value in select drop-down using Angularjs

$scope.item = {
    "id": "3",
    "name": "ALL",
};

$scope.CategoryLst = [
    { id: '1', name: 'MD' },
    { id: '2', name: 'CRNA' },
    { id: '3', name: 'ALL' }];

<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>

How to make a round button?

Fully rounded circle shape.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#F0F0F0" />
    <corners
        android:radius="90dp"/>
</shape>

Happy Coding!

Storing a file in a database as opposed to the file system?

I agree with @ZombieSheep. Just one more thing - I generally don't think that databases actually need be portable because you miss all the features your DBMS vendor provides. I think that migrating to another database would be the last thing one would consider. Just my $.02

Permissions error when connecting to EC2 via SSH on Mac OSx

The key for me to be able to connect was to use the "ec2-user" user rather than root. I.e.:

ssh -i [full path to keypair file] ec2-user@[EC2 instance hostname or IP address]

Difference between a View's Padding and Margin

Below image will let you understand the padding and margin-

enter image description here

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Not equal string

With Equals() you can also use a Yoda condition:

if ( ! "-1".Equals(myString) )

C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

What is javax.inject.Named annotation supposed to be used for?

Regarding #2, according to the JSR-330 spec:

This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.

So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.

Android check null or empty string in Android

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}

how to kill the tty in unix

Try this:

skill -KILL -v pts/6

skill -KILL -v pts/9

skill -KILL -v pts/10

Leverage browser caching, how on apache or .htaccess?

I took my chance to provide full .htaccess code to pass on Google PageSpeed Insight:

  1. Enable compression
  2. Leverage browser caching
# Enable Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
</IfModule>
<IfModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# Leverage Browser Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</IfModule>

There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.

optimized page score

Duplicating a MySQL table, indices, and data

To duplicate a table and its structure without data from a different a database use this. On the new database sql type

CREATE TABLE currentdatabase.tablename LIKE olddatabase.tablename

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Select your terminal Command prompt instead of Power shell. That should work.

How to remove specific value from array using jQuery

First checks if element exists in the array

$.inArray(id, releaseArray) > -1

above line returns the index of that element if it exists in the array, otherwise it returns -1

 releaseArray.splice($.inArray(id, releaseArray), 1);

now above line will remove this element from the array if found. To sum up the logic below is the required code to check and remove the element from array.

  if ($.inArray(id, releaseArray) > -1) {
                releaseArray.splice($.inArray(id, releaseArray), 1);
            }
            else {
                releaseArray.push(id);
            }

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

How to watch for array changes?

I fiddled around and came up with this. The idea is that the object has all the Array.prototype methods defined, but executes them on a separate array object. This gives the ability to observe methods like shift(), pop() etc. Although some methods like concat() won't return the OArray object. Overloading those methods won't make the object observable if accessors are used. To achieve the latter, the accessors are defined for each index within given capacity.

Performance wise... OArray is around 10-25 times slower compared to the plain Array object. For the capasity in a range 1 - 100 the difference is 1x-3x.

class OArray {
    constructor(capacity, observer) {

        var Obj = {};
        var Ref = []; // reference object to hold values and apply array methods

        if (!observer) observer = function noop() {};

        var propertyDescriptors = Object.getOwnPropertyDescriptors(Array.prototype);

        Object.keys(propertyDescriptors).forEach(function(property) {
            // the property will be binded to Obj, but applied on Ref!

            var descriptor = propertyDescriptors[property];
            var attributes = {
                configurable: descriptor.configurable,
                enumerable: descriptor.enumerable,
                writable: descriptor.writable,
                value: function() {
                    observer.call({});
                    return descriptor.value.apply(Ref, arguments);
                }
            };
            // exception to length
            if (property === 'length') {
                delete attributes.value;
                delete attributes.writable;
                attributes.get = function() {
                    return Ref.length
                };
                attributes.set = function(length) {
                    Ref.length = length;
                };
            }

            Object.defineProperty(Obj, property, attributes);
        });

        var indexerProperties = {};
        for (var k = 0; k < capacity; k++) {

            indexerProperties[k] = {
                configurable: true,
                get: (function() {
                    var _i = k;
                    return function() {
                        return Ref[_i];
                    }
                })(),
                set: (function() {
                    var _i = k;
                    return function(value) {
                        Ref[_i] = value;
                        observer.call({});
                        return true;
                    }
                })()
            };
        }
        Object.defineProperties(Obj, indexerProperties);

        return Obj;
    }
}

How to check if a file is a valid image file?

One option is to use the filetype package.

Installation

python -m pip install filetype

Advantages

  1. Quick: Does its work by loading the first few bytes of your image (check on the magic number)
  2. Supports different mime type: Images, Videos, Fonts, Audio, Archives.

Example

filetype >= 1.0.7

import filetype

filename = "/path/to/file.jpg"

if filetype.is_image(filename):
    print(f"{filename} is a valid image...")
elif filetype.is_video(filename):
    print(f"{filename} is a valid video...")

filetype <= 1.0.6

import filetype

filename = "/path/to/file.jpg"

if filetype.image(filename):
    print(f"{filename} is a valid image...")
elif filetype.video(filename):
    print(f"{filename} is a valid video...")

Additional information on the official repo: https://github.com/h2non/filetype.py

webpack: Module not found: Error: Can't resolve (with relative path)

Just ran into this... I have a common library shared among multiple transpiled products. I was using symlinks with brunch to handle sharing things between the projects. When moving to webpack, this stopped working.

What did get things working was using webpack configuration to turn off symlink resolving.

i.e. adding this in webpack.config.js:

module.exports = {
  //...
  resolve: {
    symlinks: false
  }
};

as documented here:

https://webpack.js.org/configuration/resolve/#resolvesymlinks

Creating a zero-filled pandas data frame

If you already have a dataframe, this is the fastest way:

In [1]: columns = ["col{}".format(i) for i in range(10)]
In [2]: orig_df = pd.DataFrame(np.ones((10, 10)), columns=columns)
In [3]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
10000 loops, best of 3: 60.2 µs per loop

Compare to:

In [4]: %timeit d = pd.DataFrame(0, index = np.arange(10), columns=columns)
10000 loops, best of 3: 110 µs per loop

In [5]: temp = np.zeros((10, 10))
In [6]: %timeit d = pd.DataFrame(temp, columns=columns)
10000 loops, best of 3: 95.7 µs per loop

How can I select all options of multi-select select box on click?

Working Demo

$('#select_all').click( function() {
    $('select#countries > option').prop('selected', 'selected');
});

If you use jQuery older than 1.6:

$('#select_all').click( function() {
    $('select#countries > option').attr('selected', 'selected');
});

Is there way to use two PHP versions in XAMPP?

I would recommend using Docker, this allows you to split the environment into various components and mix and match the ones you want at any time.

Docker will allow you to run one container with MySQL, another with PHP. As they are separate images you can have two containers, one PHP 5 another PHP 7, you start up which ever one you wish and port 80 can be mapped to both containers.

https://hub.docker.com has a wide range of preconfigured images which you can install and run without much hassle.

I've also added portainer as an image, which allows you to manage the various aspects of your docker setup - from within a docker image (I did start this container on startup to save me having to use the command line). It doesn't do everything for you and sometimes it's easier to configure and launch the images for the first time from the command line, but once setup you can start and stop them through a web interface.

It's also possible to run both containers at the same time and map separate ports to each. So port 80 can be mapped to PHP 5 and 81 to PHP 81 (Or PHP 7 if your watching this in 2017).

There are various tutorials on how to install Docker( https://docs.docker.com/engine/installation/) and loads of other 'how to' type things. Try http://www.masterzendframework.com/docker-development-environment/ for a development environment configuration.

nvarchar(max) vs NText

The advantages are that you can use functions like LEN and LEFT on nvarchar(max) and you cannot do that against ntext and text. It is also easier to work with nvarchar(max) than text where you had to use WRITETEXT and UPDATETEXT.

Also, text, ntext, etc., are being deprecated (http://msdn.microsoft.com/en-us/library/ms187993.aspx)

Creating SolidColorBrush from hex color value

I've been using:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

Why is lock(this) {...} bad?

There's also some good discussion about this here: Is this the proper use of a mutex?

Address validation using Google Maps API

Validate it against FedEx's api. They have an API to generate labels from XML code. The process involves a step to validate the address.

Loading scripts after page load?

Focusing on one of the accepted answer's jQuery solutions, $.getScript() is an .ajax() request in disguise. It allows to execute other function on success by adding a second parameter:

$.getScript(url, function() {console.log('loaded script!')})

Or on the request's handlers themselves, i.e. success (.done() - script was loaded) or failure (.fail()):

_x000D_
_x000D_
$.getScript(_x000D_
    "https://code.jquery.com/color/jquery.color.js",_x000D_
    () => console.log('loaded script!')_x000D_
  ).done((script,textStatus ) => {_x000D_
    console.log( textStatus );_x000D_
    $(".block").animate({backgroundColor: "green"}, 1000);_x000D_
  }).fail(( jqxhr, settings, exception ) => {_x000D_
    console.log(exception + ': ' + jqxhr.status);_x000D_
  }_x000D_
);
_x000D_
.block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="block"></div>
_x000D_
_x000D_
_x000D_

Delete all the records

I can see the that the others answers shown above are right, but I'll make your life easy.

I even created an example for you. I added some rows and want delete them.

You have to right click on the table and as shown in the figure Script Table a> Delete to> New query Editor widows:

enter image description here

Then another window will open with a script. Delete the line of "where", because you want to delete all rows. Then click Execute.

enter image description here

To make sure you did it right right click over the table and click in "Select Top 1000 rows". Then you can see that the query is empty.

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

The idea of your first snippet is right. You probably meant to check iByteCount == -1: whether the file has at least one byte:

if (iByteCount == -1)  
    System.out.println("NO ERRORS!");
else
    System.out.println("SOME ERRORS!");

Windows service on Local Computer started and then stopped error

Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:

"Service on local computer started and then stopped. some services stop automatically..."

How to call a RESTful web service from Android?

Here is my Library That I have created for simple Webservice Calling,

You can use this by adding a one line gradle dependency -

compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'

Here is the demonstration of using.

https://github.com/vishalchhodwani1992/httpLibrary

Android Studio: Plugin with id 'android-library' not found

Add the below to the build.gradle project module:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

How to get arguments with flags in Bash

This example uses Bash's built-in getopts command and is from the Google Shell Style Guide:

a_flag=''
b_flag=''
files=''
verbose='false'

print_usage() {
  printf "Usage: ..."
}

while getopts 'abf:v' flag; do
  case "${flag}" in
    a) a_flag='true' ;;
    b) b_flag='true' ;;
    f) files="${OPTARG}" ;;
    v) verbose='true' ;;
    *) print_usage
       exit 1 ;;
  esac
done

Note: If a character is followed by a colon (e.g. f:), that option is expected to have an argument.

Example usage: ./script -v -a -b -f filename

Using getopts has several advantages over the accepted answer:

  • the while condition is a lot more readable and shows what the accepted options are
  • cleaner code; no counting the number of parameters and shifting
  • you can join options (e.g. -a -b -c ? -abc)

However, a big disadvantage is that it doesn't support long options, only single-character options.

AngularJS does not send hidden field value

You can always use a type=text and display:none; since Angular ignores hidden elements. As OP says, normally you wouldn't do this, but this seems like a special case.

<input type="text" name="someData" ng-model="data" style="display: none;"/>

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

Bootstrap Columns Not Working

Your Nesting DIV structure was missing, you must add another ".row" div when creating nested divs in bootstrap :

Here is the Code:

<div class="container">
   <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-4"> <a href="">About</a>
    
                    </div>
                    <div class="col-md-4">
                        <img src="https://www.google.ca/images/srpr/logo11w.png" width="100px" />
                    </div>
                    <div class="col-md-4"> <a href="#myModal1" data-toggle="modal">SHARE</a>
    
                    </div>
                </div>
            </div>
        </div>
    </div>

Refer the Bootstrap example description for the same:

http://getbootstrap.com/css/

Nesting columns

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).


Here is the working Fiddle of your code: http://jsfiddle.net/52j6avkb/1/embedded/result/

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

You can find the latest features of the .NET Framework 4.5 beta here

It breaks down the changes to the framework in the following categories:

  • .NET for Metro style Apps
  • Portable Class Libraries
  • Core New Features and Improvements
  • Parallel Computing
  • Web
  • Networking
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)

You sound like you are more interested in the Web section as this shows the changes to ASP.NET 4.5. The rest of the changes can be found under the other headings.

You can also see some of the features that were new when the .NET Framework 4.0 was shipped here.

C# get string from textbox

I show you this with an example:

string userName= textBox1.text;

and then use it as you wish

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

What's the memory profile of your machine ? e.g. if you run top, how much free memory do you have ?

I suspect UnixProcess performs a fork() and it's simply not getting enough memory from the OS (if memory serves, it'll fork() to duplicate the process and then exec() to run the ls in the new memory process, and it's not getting as far as that)

EDIT: Re. your overcommit solution, it permits overcommitting of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available. So I guess that the fork() duplicates the Java process memory as discussed in the comments below. Of course you don't use the memory since the 'ls' replaces the duplicate Java process.

Is it possible to get the current spark context settings in PySpark?

You can use:

sc.sparkContext.getConf.getAll

For example, I often have the following at the top of my Spark programs:

logger.info(sc.sparkContext.getConf.getAll.mkString("\n"))

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

Replace all double quotes within String

The following regex will work for both:

  text = text.replaceAll("('|\")", "\\\\$1");

PHP calculate age

If you want to caculate the Age of using the dob, you can also use this function. It uses the DateTime object.

function calcutateAge($dob){

        $dob = date("Y-m-d",strtotime($dob));

        $dobObject = new DateTime($dob);
        $nowObject = new DateTime();

        $diff = $dobObject->diff($nowObject);

        return $diff->y;

}

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

Creating a select box with a search option

This will done by using jquery. Here is the code

<select class="chosen" style="width:500px;">
<option>Html</option>
<option>Css</option>
<option>Css3</option>
<option>Php</option>
<option>MySql</option>
<option>Javascript</option>
<option>Jquery</option>
<option>Html5</option>
<option>Wordpress</option>
<option>Joomla</option>
<option>Druple</option>
<option>Json</option>
<option>Angular Js</option>
</select>
</div>
<script type="text/javascript">
$(".chosen").chosen();
</script>

Working Example Here...

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

Updated....For ubuntu users

sudo apt-get install libapache2-mod-php php-common php-gd php-mysql php-curl php-intl php-xsl php-mbstring php-zip php-bcmath php-soap php-xdebug php-imagick

How to remove all numbers from string?

Use Predefined Character Ranges

echo $words= preg_replace('/[[:digit:]]/','', $words);

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

Keep in mind that as of PHP 5.5.0 the mysql_connect() function is deprecated, and it is completely removed in PHP 7

More info can be found on the php documentation:

Quote:

Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
* mysqli_connect()
* PDO::__construct()

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

How to solve PHP error 'Notice: Array to string conversion in...'

What the PHP Notice means and how to reproduce it:

If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.

Another example in a PHP script:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Correction 1: use foreach loop to access array elements

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "\n";
}

Prints:

1
2
3

Or along with array keys

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
    echo "$key: $value\n";
}

Prints:

name: Joe
email: [email protected]

Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']

Correction 2: Joining all the cells in the array together:

In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Correction 3: Stringify an array with complex structure:

In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);

Prints

{"name":"Joe","email":"[email protected]"}

A quick peek into array structure: use the builtin php functions

If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose

examples

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Prints:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

Enums in Javascript with ES6

If you don't need pure ES6 and can use Typescript, it has a nice enum:

https://www.typescriptlang.org/docs/handbook/enums.html

How to convert ZonedDateTime to Date?

For a docker application like beehuang commented you should set your timezone.

Alternatively you can use withZoneSameLocal. For example:

2014-07-01T00:00+02:00[GMT+02:00] is converted by

Date.from(zonedDateTime.withZoneSameLocal(ZoneId.systemDefault()).toInstant())

to Tue Jul 01 00:00:00 CEST 2014 and by

Date.from(zonedDateTime.toInstant())

to Mon Jun 30 22:00:00 UTC 2014

Specify path to node_modules in package.json

In short: It is not possible, and as it seems won't ever be supported (see here https://github.com/npm/npm/issues/775).

There are some hacky work-arrounds with using the CLI or ENV-Variables (see the current selected answer), .npmrc-Config-Files or npm link - what they all have in common: They are never just project-specific, but always some kind of global Solutions.

For me, none of those solutions are really clean because contributors to your project always need to create some special configuration or have some special knowledge - they can't just npm install and it works.

So: Either you will have to put your package.json in the same directory where you want your node_modules installed, or live with the fact that they will always be in the root-dir of your project.

C# removing items from listbox

Sorry guys i had to adjust the string

sqldatapull = dr[0].ToString();
                if (sqldatapull.StartsWith("OBJECT"))
                {
                    sqldatapull = "";
                }
                listBox1.Items.Add(sqldatapull);
                for (int i = listBox1.Items.Count - 1; i >= 0; i--)
                {
                    if (String.IsNullOrEmpty(listBox1.Items[i] as String))
                        listBox1.Items.RemoveAt(i);
                }
            }