Programs & Examples On #Audioqueue

0

Print number of keys in Redis

Since Redis 2.6, lua is supported, you can get number of wildcard keys like this

eval "return #redis.call('keys', 'prefix-*')" 0

see eval command

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

In windows environment just check the PATH environment variable if Oracle JRE runtime refreshed the path and put himself at the very beginning of the path. In this case even if the JAVA_HOME AND JRE_HOME points to the correct JDK, the JRE will have precedence. And this case IntelliJ will not start Tomcat instance with the mentioned error message.

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Disable button in WPF?

In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.

Return HTML content as a string, given URL. Javascript Function

Here's a version of the accepted answer that 1) returns a value from the function (bugfix), and 2) doesn't break when using "use strict";

I use this code to pre-load a .txt file into my <textarea> when the user loads the page.

function httpGet(theUrl)
{
    let xmlhttp;
    
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();
    
    return xmlhttp.response;
}

Can't find out where does a node.js app running and can't kill it

You can kill all node processes using pkill node

or you can do a ps T to see all processes on this terminal
then you can kill a specific process ID doing a kill [processID] example: kill 24491

Additionally, you can do a ps -help to see all the available options

MySQL user DB does not have password columns - Installing MySQL on OSX

Use the ALTER USER command rather than trying to update a USER row. Keep in mind that there may be more than one 'root' user, because user entities are qualified also by the machine from which they connect

https://dev.mysql.com/doc/refman/5.7/en/alter-user.html

For example.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password' 
ALTER USER 'root'@'*' IDENTIFIED BY 'new-password' 

How to add /usr/local/bin in $PATH on Mac

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin

One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH should be double-quoted as "$PATH".

No visible cause for "Unexpected token ILLEGAL"

The error

When code is parsed by the JavaScript interpreter, it gets broken into pieces called "tokens". When a token cannot be classified into one of the four basic token types, it gets labelled "ILLEGAL" on most implementations, and this error is thrown.

The same error is raised if, for example, you try to run a js file with a rogue @ character, a misplaced curly brace, bracket, "smart quotes", single quotes not enclosed properly (e.g. this.run('dev1)) and so on.

A lot of different situations can cause this error. But if you don't have any obvious syntax error or illegal character, it may be caused by an invisible illegal character. That's what this answer is about.

But I can't see anything illegal!

There is an invisible character in the code, right after the semicolon. It's the Unicode U+200B Zero-width space character (a.k.a. ZWSP, HTML entity &#8203;). That character is known to cause the Unexpected token ILLEGAL JavaScript syntax error.

And where did it come from?

I can't tell for sure, but my bet is on jsfiddle. If you paste code from there, it's very likely to include one or more U+200B characters. It seems the tool uses that character to control word-wrapping on long strings.

UPDATE 2013-01-07

After the latest jsfiddle update, it's now showing the character as a red dot like codepen does. Apparently, it's also not inserting U+200B characters on its own anymore, so this problem should be less frequent from now on.

UPDATE 2015-03-17

Vagrant appears to sometimes cause this issue as well, due to a bug in VirtualBox. The solution, as per this blog post is to set sendfile off; in your nginx config, or EnableSendfile Off if you use Apache.

It's also been reported that code pasted from the Chrome developer tools may include that character, but I was unable to reproduce that with the current version (22.0.1229.79 on OSX).

How can I spot it?

The character is invisible, do how do we know it's there? You can ask your editor to show invisible characters. Most text editors have this feature. Vim, for example, displays them by default, and the ZWSP shows as <u200b>. You can also debug it online: jsbin displays the character as a red dot on its code panes (but seems to remove it after saving and reloading the page). CodePen.io also displays it as a dot, and keeps it even after saving.

Related problems

That character is not something bad, it can actually be quite useful. This example on Wikipedia demonstrates how it can be used to control where a long string should be wrapped to the next line. However, if you are unaware of the character's presence on your markup, it may become a problem. If you have it inside of a string (e.g., the nodeValue of a DOM element that has no visible content), you might expect such string to be empty, when in fact it's not (even after applying String.trim).

ZWSP can also cause extra whitespace to be displayed on an HTML page, for example when it's found between two <div> elements (as seen on this question). This case is not even reproducible on jsfiddle, since the character is ignored there.

Another potential problem: if the web page's encoding is not recognized as UTF-8, the character may actually be displayed (as ​ in latin1, for example).

If ZWSP is present on CSS code (inline code, or an external stylesheet), styles can also not be parsed properly, so some styles don't get applied (as seen on this question).

The ECMAScript Specification

I couldn't find any mention to that specific character on the ECMAScript Specification (versions 3 and 5.1). The current version mentions similar characters (U+200C and U+200D) on Section 7.1, which says they should be treated as IdentifierParts when "outside of comments, string literals, and regular expression literals". Those characters may, for example, be part of a variable name (and var x\u200c; indeed works).

Section 7.2 lists the valid White space characters (such as tab, space, no-break space, etc.), and vaguely mentions that any other Unicode “space separator” (category “Zs”) should be treated as white space. I'm probably not the best person to discuss the specs in this regard, but it seems to me that U+200B should be considered white space according to that, when in fact the implementations (at least Chrome and Firefox) appear to treat them as an unexpected token (or part of one), causing the syntax error.

Edit and replay XHR chrome/firefox etc?

Updating/completing zszep answer:

After copying the request as cUrl (bash), simply import it in the Postman App:

enter image description here

HTML entity for check mark

HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <, >, " and & characters as these are reserved in SGML.

Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).

Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: &#x2714; ✔.

&#x2714;

Is using hex notation and is the same as

$#10004;

(as 2714 in base 16 is the same as 10004 in base 10)

Display A Popup Only Once Per User

This example uses jquery-cookie

Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):

if($.cookie('popup') != 'seen'){
    $.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
    $j("#popup").delay(2000).fadeIn();
    $j('#popup-close').click(function(e) // You are clicking the close button
        {
        $j('#popup').fadeOut(); // Now the pop up is hiden.
    });
    $j('#popup').click(function(e) 
        {
        $j('#popup').fadeOut(); 
    });
};

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

What file uses .md extension and how should I edit them?

BBEdit will also display MD on the mac.

and here is a quicklook plugin to display them when you preview them.

How do I redirect a user when a button is clicked?

Or, if none of the above works then you can use following approach as it worked for me.

Imagine this is your button

<button class="btn" onclick="NavigateToPdf(${Id});"></button>

I got the value for ${Id} filled using jquery templates. You can use whatever suits your requirement. In the following function, I am setting window.location.href equal to controller name then action name and then finally parameter. I am able to successfully navigate.

function NavigateToPdf(id) {
    window.location.href = "Link/Pdf/" + id;
}

I hope it helps.

Clicking URLs opens default browser

If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.

You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.

You set the WebViewClient of your WebView using the setWebViewClient() method.

If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Getting started with OpenCV 2.4 and MinGW on Windows 7

The instructions in @bsdnoobz answer are indeed helpful, but didn't get OpenCV to work on my system.

Apparently I needed to compile the library myself in order to get it to work, and not count on the pre-built binaries (which caused my programs to crash, probably due to incompatibility with my system).

I did get it to work, and wrote a comprehensive guide for compiling and installing OpenCV, and configuring Netbeans to work with it.

For completeness, it is also provided below.


When I first started using OpenCV, I encountered two major difficulties:

  1. Getting my programs NOT to crash immediately.
  2. Making Netbeans play nice, and especially getting timehe debugger to work.

I read many tutorials and "how-to" articles, but none was really comprehensive and thorough. Eventually I succeeded in setting up the environment; and after a while of using this (great) library, I decided to write this small tutorial, which will hopefully help others.

The are three parts to this tutorial:

  1. Compiling and installing OpenCV.
  2. Configuring Netbeans.
  3. An example program.

The environment I use is: Windows 7, OpenCV 2.4.0, Netbeans 7 and MinGW 3.20 (with compiler gcc 4.6.2).

Assumptions: You already have MinGW and Netbeans installed on your system.

Compiling and installing OpenCV

When downloading OpenCV, the archive actually already contains pre-built binaries (compiled libraries and DLL's) in the 'build' folder. At first, I tried using those binaries, assuming somebody had already done the job of compiling for me. That didn't work.

Eventually I figured I have to compile the entire library on my own system in order for it to work properly.

Luckily, the compilation process is rather easy, thanks to CMake. CMake (stands for Cross-platform Make) is a tool which generates makefiles specific to your compiler and platform. We will use CMake in order to configure our building and compilation settings, generate a 'makefile', and then compile the library.

The steps are:

  1. Download CMake and install it (in the installation wizard choose to add CMake to the system PATH).
  2. Download the 'release' version of OpenCV.
  3. Extract the archive to a directory of your choice. I will be using c:/opencv/.
  4. Launch CMake GUI.
    1. Browse for the source directory c:/opencv/.
    2. Choose where to build the binaries. I chose c:/opencv/release.
      CMake Configuration - 1
    3. Click 'Configure'. In the screen that opens choose the generator according to your compiler. In our case it's 'MinGW Makefiles'.
      CMake Configuration - 2
    4. Wait for everything to load, afterwards you will see this screen:
      CMake Configuration - 3
    5. Change the settings if you want, or leave the defaults. When you're done, press 'Configure' again. You should see 'Configuration done' at the log window, and the red background should disappear from all the cells.
      CMake Configuration - 4
    6. At this point CMake is ready to generate the makefile with which we will compile OpenCV with our compiler. Click 'Generate' and wait for the makefile to be generated. When the process is finished you should see 'Generating done'. From this point we will no longer need CMake.
  5. Open MinGW shell (The following steps can also be done from Windows' command prompt).
    1. Enter the directory c:/opencv/release/.
    2. Type mingw32-make and press enter. This should start the compilation process.
      MinGW Make
      MinGW Make - Compilation
    3. When the compilation is done OpenCV's binaries are ready to be used.
    4. For convenience, we should add the directory C:/opencv/release/bin to the system PATH. This will make sure our programs can find the needed DLL's to run.

Configuring Netbeans

Netbeans should be told where to find the header files and the compiled libraries (which were created in the previous section).

The header files are needed for two reasons: for compilation and for code completion. The compiled libraries are needed for the linking stage.

Note: In order for debugging to work, the OpenCV DLL's should be available, which is why we added the directory which contains them to the system PATH (previous section, step 5.4).

First, you should verify that Netbeans is configured correctly to work with MinGW. Please see the screenshot below and verify your settings are correct (considering paths changes according to your own installation). Also note that the make command should be from msys and not from Cygwin.

Netbeans MinGW Configuration

Next, for each new project you create in Netbeans, you should define the include path (the directory which contains the header files), the libraries path and the specific libraries you intend to use. Right-click the project name in the 'projects' pane, and choose 'properties'. Add the include path (modify the path according to your own installation):

Netbeans Project Include Path

Add the libraries path:

Netbeans Libraries Path

Add the specific libraries you intend to use. These libraries will be dynamically linked to your program in the linking stage. Usually you will need the core library plus any other libraries according to the specific needs of your program.

Netbeans Include Libraries

That's it, you are now ready to use OpenCV!

Summary

Here are the general steps you need to complete in order to install OpenCV and use it with Netbeans:

  1. Compile OpenCV with your compiler.
  2. Add the directory which contains the DLL's to your system PATH (in our case: c:/opencv/release/bin).
  3. Add the directory which contains the header files to your project's include path (in our case: c:/opencv/build/include).
  4. Add the directory which contains the compiled libraries to you project's libraries path (in our case: c:/opencv/release/lib).
  5. Add the specific libraries you need to be linked with your project (for example: libopencv_core240.dll.a).

Example - "Hello World" with OpenCV

Here is a small example program which draws the text "Hello World : )" on a GUI window. You can use it to check that your installation works correctly. After compiling and running the program, you should see the following window:

OpenCV Hello World

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, char** argv) {
    //create a gui window:
    namedWindow("Output",1);

    //initialize a 120X350 matrix of black pixels:
    Mat output = Mat::zeros( 120, 350, CV_8UC3 );

    //write text on the matrix:
    putText(output,
            "Hello World :)",
            cvPoint(15,70),
            FONT_HERSHEY_PLAIN,
            3,
            cvScalar(0,255,0),
            4);

    //display the image:
    imshow("Output", output);

    //wait for the user to press any key:
    waitKey(0);

    return 0;
}

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

Java ArrayList - how can I tell if two lists are equal, order not mattering?

// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
    public int count = 0;
}

public boolean haveSameElements(final List<String> list1, final List<String> list2) {
    // (list1, list1) is always true
    if (list1 == list2) return true;

    // If either list is null, or the lengths are not equal, they can't possibly match 
    if (list1 == null || list2 == null || list1.size() != list2.size())
        return false;

    // (switch the two checks above if (null, null) should return false)

    Map<String, Count> counts = new HashMap<>();

    // Count the items in list1
    for (String item : list1) {
        if (!counts.containsKey(item)) counts.put(item, new Count());
        counts.get(item).count += 1;
    }

    // Subtract the count of items in list2
    for (String item : list2) {
        // If the map doesn't contain the item here, then this item wasn't in list1
        if (!counts.containsKey(item)) return false;
        counts.get(item).count -= 1;
    }

    // If any count is nonzero at this point, then the two lists don't match
    for (Map.Entry<String, Count> entry : counts.entrySet()) {
        if (entry.getValue().count != 0) return false;
    }

    return true;
}

Execute a SQL Stored Procedure and process the results

Simplest way? It works. :)

    Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
    Try
        Using connection As New SqlConnection(ConnStrg)
            connection.Open()
            Dim command As New SqlCommand(queryString, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            Dim DTResults As New DataTable

            DTResults.Load(reader)
            MsgBox(DTResults.Rows(0)(0).ToString)

        End Using
    Catch ex As Exception
        MessageBox.Show("Error while executing .. " & ex.Message, "")
    Finally
    End Try

RGB to hex and hex to RGB

Shorthand version that accepts a string:

_x000D_
_x000D_
function rgbToHex(a){_x000D_
  a=a.replace(/[^\d,]/g,"").split(","); _x000D_
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)_x000D_
}_x000D_
_x000D_
document.write(rgbToHex("rgb(255,255,255)"));
_x000D_
_x000D_
_x000D_

To check if it's not already hexadecimal

_x000D_
_x000D_
function rgbToHex(a){_x000D_
  if(~a.indexOf("#"))return a;_x000D_
  a=a.replace(/[^\d,]/g,"").split(","); _x000D_
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)_x000D_
}_x000D_
_x000D_
document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));
_x000D_
_x000D_
_x000D_

concatenate two strings

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

filters on ng-model in an input

You can try this

$scope.$watch('tags ',function(){

    $scope.tags = $filter('lowercase')($scope.tags);

});

How to install bcmath module?

For Centos 7 with php7.0

Install CentOS SCLo RH repository: yum install centos-release-scl-rh

Install rh-php71-php-bcmath rpm package: yum install rh-php71-php-bcmath

systemctl restart httpd.service

Location of sqlite database on the device

For this, what I did is

File f=new File("/data/data/your.app.package/databases/your_db.db3");
FileInputStream fis=null;
FileOutputStream fos=null;

try
{
  fis=new FileInputStream(f);
  fos=new FileOutputStream("/mnt/sdcard/db_dump.db");
  while(true)
  {
    int i=fis.read();
    if(i!=-1)
    {fos.write(i);}
    else
    {break;}
  }
  fos.flush();
  Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
  e.printStackTrace();
  Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
}
finally
{
  try
  {
    fos.close();
    fis.close();
  }
  catch(IOException ioe)
  {}
}

And to do this, your app must have permission to access SD card, add following setting to your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Not a brilliant way, but works.

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I had the same problem and I did it this way

//note that I added jquery separately above this

<!--ENJOY HINT PACKAGES --START -->
<link href="path/enjoyhint/jquery.enjoyhint.css" rel="stylesheet">
<script src="path/enjoyhint/jquery.enjoyhint.js"></script>
<script src="path/enjoyhint/kinetic.min.js"></script>
<script src="path/enjoyhint/enjoyhint.js"></script>  
<!--ENJOY HINT PACKAGES --END -->

and it works

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

How to convert integers to characters in C?

Program Converts ASCII to Alphabet

#include<stdio.h>

void main ()
{

  int num;
  printf ("=====This Program Converts ASCII to Alphabet!=====\n");
  printf ("Enter ASCII: ");
  scanf ("%d", &num);
  printf("%d is ASCII value of '%c'", num, (char)num );
}

Program Converts Alphabet to ASCII code

#include<stdio.h>

void main ()
{

  char alphabet;
  printf ("=====This Program Converts Alphabet to ASCII code!=====\n");
  printf ("Enter Alphabet: ");
  scanf ("%c", &alphabet);
  printf("ASCII value of '%c' is %d", alphabet, (char)alphabet );
}

Setting the filter to an OpenFileDialog to allow the typical image formats?

Follow this pattern if you browsing for image files:

dialog.Filter =  "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";

Display Image On Text Link Hover CSS Only

It is not possible to do this with just CSS alone, you will need to use Javascript.

<img src="default_image.jpg" id="image" width="100" height="100" alt="" />


<a href="page.html" onmouseover="document.images['image'].src='mouseover.jpg';" onmouseout="document.images['image'].src='default_image.jpg';"/>Text</a>

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

How to create file execute mode permissions in Git on Windows?

If the files already have the +x flag set, git update-index --chmod=+x does nothing and git thinks there's nothing to commit, even though the flag isn't being saved into the repo.

You must first remove the flag, run the git command, then put the flag back:

chmod -x <file>
git update-index --chmod=+x <file>
chmod +x <file>

then git sees a change and will allow you to commit the change.

React Native Change Default iOS Simulator Device

There is a project setting if you hunt down:

{project}/node_modules/react-native/local-cli/runIOS/runIOS.js

Within there are some options under module.exports including:

options: [{ command: '--simulator [string]', description: 'Explicitly set simulator to use', default: 'iPhone 7', }

Mine was line 231, simply set that to a valid installed simulator and run react-native run-ios it will run to that simulator by default.

Verify if file exists or not in C#

    if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage)))) 
      { 
        <img src="~/Images/associates/@Html.DisplayFor(modelItem => item.AssociateImage)"> 
      }
        else 
      { 
        <h5>No image available</h5> 
      }

I did something like this for checking to see if an image existed before displaying it.

How to install pkg config in windows?

I did this by installing Cygwin64 from this link https://www.cygwin.com/ Then - View Full, Search gcc and scroll down to find pkg-config. Click on icon to select latest version. This worked for me well.

Swap two variables without using a temporary variable

int a = 4, b = 6;
a ^= b ^= a ^= b;

Works for all types including strings and floats.

How can I align button in Center or right using IONIC framework?

Ultimately, we are trying to get to this.

<div style="display: flex; justify-content: center;">
    <button ion-button>Login</button>
</div>

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had this problem because of a trigger not working..Worked after I deleted the trigger.

How do I set a textbox's text to bold at run time?

 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

CodeIgniter: 404 Page Not Found on Live Server

I have solved this problem, please just make few changes

1- all controller class name should start with capital letter. i mean first letter of class should be capital . eg we have controler with class name Pages

so it should be Pages not pages

2- save the controller class Pages as Pages.php not pages.php

so first letter must be capital

same for model, model class first letter should be capital and also save model class as Pages_model.php not page_model.php

hope this will solve ur problem

100% width in React Native Flexbox

width: '100%' and alignSelf: 'stretch' didn't work for me. Dimensions didn't suite my task cause I needed to operate on a deeply nested view. Here's what worked for me, if I rewrite your code. I just added some more Views and used flex properties to achieve the needed layout:

  {/* a column */}
  <View style={styles.container}>
    {/* some rows here */}
    <Text style={styles.welcome}>
      Welcome to React Natives
    </Text>
    {/* this row should take all available width */}
    <View style={{ flexDirection: 'row' }}>
      {/* flex 1 makes the view take all available width */}
      <View style={{ flex: 1 }}>
        <Text style={styles.line1}>
          line1
        </Text>
      </View>
      {/* I also had a button here, to the right of the text */}
    </View>
    {/* the rest of the rows */}
    <Text style={styles.instructions}>
      Press Cmd+R to reload,{'\n'}
      Cmd+D or shake for dev menu
    </Text>
  </View>

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

Sublime Text 2: How to delete blank/empty lines

You are looking for this:

^\n|^\s+$

it will not delete the line, if there is content with white space or tabs in front>

e.g.:

these will not be deleted: ...space... abc

...tab... abc

this will:

...space... ...nothing else...

...tab... ...nothing else...

Can you do a partial checkout with Subversion?

Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it:

svn checkout --depth empty http://svnserver/trunk/proj
svn update --set-depth infinity proj/foo
svn update --set-depth infinity proj/bar
svn update --set-depth infinity proj/baz

Alternatively, --depth immediates instead of empty checks out files and directories in trunk/proj without their contents. That way you can see which directories exist in the repository.


As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect:

svn checkout --non-recursive http://svnserver/trunk/proj
svn update trunk/foo
svn update trunk/bar
svn update trunk/baz

Change Circle color of radio button

There is an xml attribute for it:

android:buttonTint="yourcolor"

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

How to change font in ipython notebook

I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:

jupyter-themer [-c COLOR, --color COLOR]
                      [-l LAYOUT, --layout LAYOUT]
                      [-t TYPOGRAPHY, --typography TYPOGRAPHY]

where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css files if the changes you want to apply are elaborate.

Drawing a dot on HTML5 canvas

The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:

I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm

Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.

At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)

Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..

Splitting a table cell into two columns in HTML

Like this http://jsfiddle.net/8ha9e/1/

Add colspan="2" to the 3rd <th> and then have 4 <td>'s in your second row.

<table border="1">
  <tr>
    <th scope="col">Header</th>
    <th scope="col">Header</th>
    <th scope="col" colspan="2">Header</th>
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>&nbsp;</td>
    <!-- The following two cells will appear under the same header -->
    <td>Col 1</td>
    <td>Col 2</td>
  </tr>
</table>

json_decode() expects parameter 1 to be string, array given

Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()

Note: Depends on what you are working on but make sure you are using the right function.

How to make the window full screen with Javascript (stretching all over the screen)

Now that the full screen APIs are more widespread and appear to be maturing, why not try Screenfull.js? I used it for the first time yesterday and today our app goes truly full screen in (almost) all browsers!

Be sure to couple it with the :fullscreen pseudo-class in CSS. See https://www.sitepoint.com/use-html5-full-screen-api/ for more.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

You can also use evalAsync. It will run sometime after digest has finished!

scope.evalAsync(function(scope){
    //use the scope...
});

How to part DATE and TIME from DATETIME in MySQL

Simply,
SELECT TIME(column_name), DATE(column_name)

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

This solve my problème:

$description = strip_tags($value['Description']);
$description=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $description);
$description= preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $description);
$description=str_replace(' & ', ' &amp; ', html_entity_decode((htmlspecialchars_decode($description))));

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

How to have jQuery restrict file types on upload?

This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});

SQL get the last date time record

Try this:

SELECT filename,Dates,Status 
FROM TableName 
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)

Char array declaration and initialization in C

myarray = "abc";

...is the assignation of a pointer on "abc" to the pointer myarray.

This is NOT filling the myarray buffer with "abc".

If you want to fill the myarray buffer manually, without strcpy(), you can use:

myarray[0] = 'a', myarray[1] = 'b', myarray[2] = 'c', myarray[3] = 0;

or

char *ptr = myarray;
*ptr++ = 'a', *ptr++ = 'b', *ptr++ = 'c', *ptr = 0;

Your question is about the difference between a pointer and a buffer (an array). I hope you now understand how C addresses each kind.

How to redirect from one URL to another URL?

If you want to redirect, just use window.location. Like so:

window.location = "http://www.redirectedsite.com"

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

IO Error: The Network Adapter could not establish the connection

Another thing you might want to check that the listener.ora file matches the way you are trying to connect to the DB. If you were connecting via a localhost reference and your listener.ora file got changed from:

HOST = localhost

to

HOST = 192.168.XX.XX

then this can cause the error that you had unless you update your hosts file to accommodate for this. Someone might have made this change to allow for remote connections to the DB from other machines.

How do I add indices to MySQL tables?

ALTER TABLE `table` ADD INDEX `product_id_index` (`product_id`)

Never compare integer to strings in MySQL. If id is int, remove the quotes.

Download a single folder or directory from a GitHub repo

2019 Summary

There are a variety of ways to handle this, depending on whether or not you want to do this manually or programmatically.

There are four options summarized below. And for those that prefer a more hands-on explanation, I've put together a YouTube video: Download Individual Files and Folders from GitHub.

Also, I've posted a similar answer on StackOverflow for those that need to download single files from GitHub (as opposed to folders).


1. GitHub User Interface

  • There's a download button on the repository's homepage. Of course, this downloads the entire repo, after which you would need to unzip the download and then manually drag out the specific folder you need.

2. Third Party Tools

  • There are a variety of browser extensions and web apps that can handle this, with DownGit being one of them. Simply paste in the GitHub URL to the folder (e.g. https://github.com/babel/babel-eslint/tree/master/lib) and press the "Download" button.

3. Subversion

  • GitHub does not support git-archive (the git feature that would allow us to download specific folders). GitHub does however, support a variety of Subversion features, one of which we can use for this purpose. Subversion is a version control system (an alternative to git). You'll need Subversion installed. Grab the GitHub URL for the folder you want to download. You'll need to modify this URL, though. You want the link to the repository, followed by the word "trunk", and ending with the path to the nested folder. In other words, using the same folder link example that I mentioned above, we would replace "tree/master" with "trunk". Finally, open up a terminal, navigate to the directory that you want the content to get downloaded to, type in the following command (replacing the URL with the URL you constructed): svn export https://github.com/babel/babel-eslint/trunk/lib, and press enter.

4. GitHub API

  • This is the solution you'll need if you want to accomplish this task programmatically. And this is actually what DownGit is using under the hood. Using GitHub's REST API, write a script that does a GET request to the content endpoint. The endpoint can be constructed as follows: https://api.github.com/repos/:owner/:repo/contents/:path. After replacing the placeholders, an example endpoint is: https://api.github.com/repos/babel/babel-eslint/contents/lib. This gives you JSON data for all of the content that exists in that folder. The data has everything you need, including whether or not the content is a folder or file, a download URL if it's a file, and an API endpoint if it's a folder (so that you can get the data for that folder). Using this data, the script can recursively go through all content in the target folder, create folders for nested folders, and download all of the files for each folder. Check out DownGit's code for inspiration.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

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

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

I got the same issue and It got solved by installing Oracle 11g client in my machine..

I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it

Please Finc the attachment below for the same

How do I "Add Existing Item" an entire directory structure in Visual Studio?

The cleanest way that I've found to do this is to create a new Class Library project in the target folder, and redirect all of its build output elsewhere. It still leaves a .csproj file sitting in that folder, but it does let you see it in Visual Studio and pick which files to include in your project.

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:

jqGrid

DataTables.net

UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

How to create a listbox in HTML without allowing multiple selection?

Just use the size attribute:

<select name="sometext" size="5">
  <option>text1</option>
  <option>text2</option>
  <option>text3</option>
  <option>text4</option>
  <option>text5</option>
</select>

To clarify, adding the size attribute did not remove the multiple selection.

The single selection works because you removed the multiple="multiple" attribute.

Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here

List all of the possible goals in Maven 2?

Is it possible to list all of the possible goals (including, say, all the plugins) that it is possible to run?

Maven doesn't have anything built-in for that, although the list of phases is finite (the list of plugin goals isn't since the list of plugins isn't).

But you can make things easier and leverage the power of bash completion (using cygwin if you're under Windows) as described in the Guide to Maven 2.x auto completion using BASH (but before to choose the script from this guide, read further).

To get things working, first follow this guide to setup bash completion on your computer. Then, it's time to get a script for Maven2 and:

  • While you could use the one from the mini guide
  • While you use an improved version attached to MNG-3928
  • While you could use a random scripts found around the net (see the resources if you're curious)
  • I personally use the Bash Completion script from Ludovic Claude's PPA (which is bundled into the packaged version of maven in Ubuntu) that you can download from the HEAD. It's simply the best one.

Below, here is what I get just to illustrate the result:

$ mvn [tab][tab]
Display all 377 possibilities? (y or n)
ant:ant 
ant:clean 
ant:help 
antrun:help 
antrun:run 
archetype:crawl 
archetype:create 
archetype:create-from-project 
archetype:generate 
archetype:help 
assembly:assembly 
assembly:directory 
assembly:directory-single 
assembly:help 
assembly:single  
... 

Of course, I never browse the 377 possibilities, I use completion. But this gives you an idea about the size of "a" list :)

Resources

Python glob multiple filetypes

While Python's default glob doesn't really follow after Bash's glob, you can do this with other libraries. We can enable braces in wcmatch's glob.

>>> from wcmatch import glob
>>> glob.glob('*.{md,ini}', flags=glob.BRACE)
['LICENSE.md', 'README.md', 'tox.ini']

You can even use extended glob patterns if that is your preference:

from wcmatch import glob
>>> glob.glob('*.@(md|ini)', flags=glob.EXTGLOB)
['LICENSE.md', 'README.md', 'tox.ini']

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
    jQuery.ajax({
        type: 'POST',
        url:"functions.php",
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {
             $("#show1").html(returnval);
             $('#show1').show();
         }
    });
}

Just print the file details and check. You will get Output. If error let me know.

Difference between "process.stdout.write" and "console.log" in node.js?

The Simple Difference is: console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.

process.stdout.write() methods don't append new line character. useful for printing patterns.

How to check if an object is defined?

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

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

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

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

Transfer data from one database to another database

You can use visual studio 2015. Go to Tools => SQL server => New Data comparison

Select source and target Database.

Error "initializer element is not constant" when trying to initialize variable with const

This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:

#include <stdio.h>
typedef struct foo_t  {
    int a; int b; int c;
} foo_t;
static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
// or a pointer
static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
int main (int argc, char **argv) {
    const foo_t *const f1 = &s_FooInit;
    const foo_t *const f2 = s_pFooInit;
    printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
    printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
    return 0;
}

Python: json.loads returns items prefixing with 'u'

Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

Converting from hex to string

My Net 5 solution that also handles null characters at the end:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}

How do I use $rootScope in Angular to store variables?

http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html

 app.controller('AppCtrl2', function ($scope, $rootScope) {
     $scope.msg = 'SCOPE';
     $rootScope.name = 'ROOT SCOPE';
 });

Remove a file from a Git repository without deleting it from the local filesystem

A more generic solution:

  1. Edit .gitignore file.

    echo mylogfile.log >> .gitignore

  2. Remove all items from index.

    git rm -r -f --cached .

  3. Rebuild index.

    git add .

  4. Make new commit

    git commit -m "Removed mylogfile.log"

Reading specific XML elements from XML file

Alternatively, you can use XPath query via XPathSelectElements method:

var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");

QByteArray to QString

You may find QString::fromUtf8() also useful.

For QByteArray input of "\010" and "\000",

QString::fromLocal8Bit(input, 1) returns "\010" and ""

QString::fromUtf8(input, 1) correctly returns "\010" and "\000".

How to read a local text file?

Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    <html>
    <head>
    <script>
      var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(){
          var text = reader.result;
          var node = document.getElementById('output');
          node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    ...
    </div>
    </body>
    </html>

jQuery call function after load

$(window).bind("load", function() {
  // write your code here
});

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

Can I force a UITableView to hide the separator between empty cells?

Swift Version

The easiest method is to set the tableFooterView property:

override func viewDidLoad() {
    super.viewDidLoad()
    // This will remove extra separators from tableview
    self.tableView.tableFooterView = UIView(frame: CGRectZero)
}

How to get everything after a certain character?

Here is the method by using explode:

$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string

or:

$text = @end((explode('_', '233718_This_is_a_string', 2)));

By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.


Here is another one-liner by using strpos (as suggested by @flu):

$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string

How to grep (search) committed code in the Git history

Adding more to the answers already present. If you know the file in which you might have made do this:

git log --follow -p -S 'search-string' <file-path>

--follow: lists the history of a file

jQuery jump or scroll to certain position, div or target on the page from button onclick

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

How to create a trie in Python

Modified from senderle's method (above). I found that Python's defaultdict is ideal for creating a trie or a prefix tree.

from collections import defaultdict

class Trie:
    """
    Implement a trie with insert, search, and startsWith methods.
    """
    def __init__(self):
        self.root = defaultdict()

    # @param {string} word
    # @return {void}
    # Inserts a word into the trie.
    def insert(self, word):
        current = self.root
        for letter in word:
            current = current.setdefault(letter, {})
        current.setdefault("_end")

    # @param {string} word
    # @return {boolean}
    # Returns if the word is in the trie.
    def search(self, word):
        current = self.root
        for letter in word:
            if letter not in current:
                return False
            current = current[letter]
        if "_end" in current:
            return True
        return False

    # @param {string} prefix
    # @return {boolean}
    # Returns if there is any word in the trie
    # that starts with the given prefix.
    def startsWith(self, prefix):
        current = self.root
        for letter in prefix:
            if letter not in current:
                return False
            current = current[letter]
        return True

# Now test the class

test = Trie()
test.insert('helloworld')
test.insert('ilikeapple')
test.insert('helloz')

print test.search('hello')
print test.startsWith('hello')
print test.search('ilikeapple')

How to keep console window open

Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

I believe that's a simple incarnation of the Command pattern.

Best way to check if a Data Table has a null value in it

Try comparing the value of the column to the DBNull.Value value to filter and manage null values in whatever way you see fit.

foreach(DataRow row in table.Rows)
{
    object value = row["ColumnName"];
    if (value == DBNull.Value)
        // do something
    else
        // do something else
}

More information about the DBNull class


If you want to check if a null value exists in the table you can use this method:

public static bool HasNull(this DataTable table)
{
    foreach (DataColumn column in table.Columns)
    {
        if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
            return true;
    }

    return false;
}

which will let you write this:

table.HasNull();

git: Your branch is ahead by X commits

This worked for me

git reset --hard origin/master

The output must look like

On branch dev HEAD is now at ae1xc41z Last commit message

What is the 'realtime' process priority setting for?

A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.

Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.

For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.

How to negate a method reference predicate

Shouldn't Predicate#negate be what you are looking for?

How to compile Tensorflow with SSE4.2 and AVX instructions?

This is the simplest method. Only one step.

It has significant impact on speed. In my case, time taken for a training step almost halved.

Refer custom builds of tensorflow

How to check if object has any properties in JavaScript?

Late answer, but some frameworks handle objects as enumerables. Therefore, bob.js can do it like this:

var objToTest = {};
var propertyCount = bob.collections.extend(objToTest).count();

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Simple bubble sort c#

   using System; 
 using System.Collections.Generic; 
 using System.Linq;  
using System.Text; 
 using System.Threading.Tasks;

namespace Practice {
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size");
            int n = Convert.ToInt32(Console.ReadLine());
            int[] mynum = new int[n];
            Console.WriteLine("Enter the Numbers");
            for (int p = 0; p < n;p++ )
            {
                mynum[p] = Convert.ToInt32(Console.ReadLine());

            }
            Console.WriteLine("The number are");
                foreach(int p in mynum)
                {
                    Console.WriteLine(p);
                }
                for (int i = 0; i < n;i++ )
                {
                    for(int j=i+1;j<n;j++)
                    {
                        if(mynum[i]>mynum[j])
                        {
                            int x = mynum[j];
                            mynum[j] = mynum[i];
                            mynum[i] = x;
                        }
                    }
                }
                Console.WriteLine("Sortrd data is-");
            foreach(int p in mynum)
            {
                Console.WriteLine(p);
            }
                    Console.ReadLine();
        }
    } }

How to have multiple CSS transitions on an element?

If you make all the properties animated the same, you can set each separately which will allow you to not repeat the code.

 transition: all 2s;
 transition-property: color, text-shadow;

There is more about it here: CSS transition shorthand with multiple properties?

I would avoid using the property all (transition-property overwrites 'all'), since you could end up with unwanted behavior and unexpected performance hits.

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

How to get a unique device ID in Swift?

Swift 2.2

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let userDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.objectForKey("ApplicationIdentifier") == nil {
        let UUID = NSUUID().UUIDString
        userDefaults.setObject(UUID, forKey: "ApplicationIdentifier")
        userDefaults.synchronize()
    }
    return true
}

//Retrieve
print(NSUserDefaults.standardUserDefaults().valueForKey("ApplicationIdentifier")!)

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

Apply formula to the entire column

I think it's a more recent feature, but it works for me:

Double clicking the square on the bottom right of the highlighted cell copies the formula of the highlighted cell.

Hope it helps.

Count number of rows matching a criteria

to get the number of observations the number of rows from your Dataset would be more valid:

nrow(dat[dat$sCode == "CA",])

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

need to add a class to an element

You probably need something like:

result.className = 'red'; 

In pure JavaScript you should use className to deal with classes. jQuery has an abstraction called addClass for it.

You have not concluded your merge (MERGE_HEAD exists)

This worked for me:

git log
`git reset --hard <089810b5be5e907ad9e3b01f>`
git pull
git status

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

Which Android IDE is better - Android Studio or Eclipse?

My first choice is Android Studio. its has great feature to develop android application.

Eclipse is not that hard to learn also.If you're going to be learning Android development from the start, I can recommend Hello, Android, which I just finished. It shows you exactly how to use all the features of Eclipse that are useful for developing Android apps. There's also a brief section on getting set up to develop from the command line and from other IDEs.

Remove specific commit

There are four ways of doing so:

  • Clean way, reverting but keep in log the revert:

    git revert --strategy resolve <commit>
    
  • Harsh way, remove altogether only the last commit:

    git reset --soft "HEAD^"
    

Note: Avoid git reset --hard as it will also discard all changes in files since the last commit. If --soft does not work, rather try --mixed or --keep.

  • Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):

    git rebase -i HEAD~5
    

And if a mistake is made:

git rebase --abort
  • Quick rebase: remove only a specific commit using its id:

    git rebase --onto commit-id^ commit-id
    
  • Alternatives: you could also try:

    git cherry-pick commit-id
    
  • Yet another alternative:

    git revert --no-commit
    
  • As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.

Note: of course, all these changes are done locally, you should git push afterwards to apply the changes to the remote. And in case your repo doesn't want to remove the commit ("no fast-forward allowed", which happens when you want to remove a commit you already pushed), you can use git push -f to force push the changes.

Note2: if working on a branch and you need to force push, you should absolutely avoid git push --force because this may overwrite other branches (if you have made changes in them, even if your current checkout is on another branch). Prefer to always specify the remote branch when you force push: git push --force origin your_branch.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Reversing a linked list in Java, recursively

The algo will need to work on the following model,

  • keep track of the head
  • Recurse till end of linklist
  • Reverse linkage

Structure:

Head    
|    
1-->2-->3-->4-->N-->null

null-->1-->2-->3-->4-->N<--null

null-->1-->2-->3-->4<--N<--null

null-->1-->2-->3<--4<--N<--null

null-->1-->2<--3<--4<--N<--null

null-->1<--2<--3<--4<--N<--null

null<--1<--2<--3<--4<--N
                       |
                       Head

Code:

public ListNode reverse(ListNode toBeNextNode, ListNode currentNode)
{               
        ListNode currentHead = currentNode; // keep track of the head

        if ((currentNode==null ||currentNode.next==null )&& toBeNextNode ==null)return currentHead; // ignore for size 0 & 1

        if (currentNode.next!=null)currentHead = reverse(currentNode, currentNode.next); // travarse till end recursively

        currentNode.next = toBeNextNode; // reverse link

        return currentHead;
}

Output:

head-->12345

head-->54321

rand() between 0 and 1

No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.

To get what you want you will need to move the +1 outside the computation:

r = ((double) rand() / (RAND_MAX)) + 1;

How to get PID by process name?

You can use psutil package:

Install

pip install psutil

Usage:

import psutil

process_name = "chrome"
pid = None

for proc in psutil.process_iter():
    if process_name in proc.name():
       pid = proc.pid

jquery UI dialog: how to initialize without a title bar?

I think the cleanest way of doing it would be to create a new myDialog widget, consisting of the dialog widget minus the title bar code. Excising the title bar code looks straightforward.

https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.dialog.js

Jenkins Host key verification failed

Change to the jenkins user and run the command manually:

git ls-remote -h [email protected]:person/projectmarket.git HEAD

You will get the standard SSH warning when first connecting to a new host via SSH:

The authenticity of host 'bitbucket.org (207.223.240.181)' can't be established.
RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?

Type yes and press Enter. The host key for bitbucket.org will now be added to the ~/.ssh/known_hosts file and you won't get this error in Jenkins anymore.

Codeigniter LIKE with wildcard(%)

$this->db->like()

This method enables you to generate LIKE clauses, useful for doing searches.

$this->db->like('title', 'match');

Produces: WHERE title LIKE '%match%'

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).

$this->db->like('title', 'match', 'before');

Produces: WHERE title LIKE '%match'

$this->db->like('title', 'match', 'after');

Produces: WHERE title LIKE 'match%'

$this->db->like('title', 'match', 'none');

Produces: WHERE title LIKE 'match'

$this->db->like('title', 'match', 'both');

Produces: WHERE title LIKE '%match%'

How to calculate percentage when old value is ZERO

It should be (new minus old)/mod avg of old and new With a special case when both val are zeros

How do I use a file grep comparison inside a bash if/else statement?

if takes a command and checks its return value. [ is just a command.

if grep -q ...
then
  ....
else
  ....
fi

PowerShell Connect to FTP server and get files

Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.

    #FTP Server Information - SET VARIABLES
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password'
    $folder = 'FTP_Folder'
    $target = "C:\Folder\Folder1\"

    #SET CREDENTIALS
    $credentials = new-object System.Net.NetworkCredential($user, $pass)

    function Get-FtpDir ($url,$credentials) {
        $request = [Net.WebRequest]::Create($url)
        $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        if ($credentials) { $request.Credentials = $credentials }
        $response = $request.GetResponse()
        $reader = New-Object IO.StreamReader $response.GetResponseStream() 
        while(-not $reader.EndOfStream) {
            $reader.ReadLine()
        }
        #$reader.ReadToEnd()
        $reader.Close()
        $response.Close()
    }

    #SET FOLDER PATH
    $folderPath= $ftp + "/" + $folder + "/"

    $files = Get-FTPDir -url $folderPath -credentials $credentials

    $files 

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0
    foreach ($file in ($files | where {$_ -like "*.txt"})){
        $source=$folderPath + $file  
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file)

        #PRINT FILE NAME AND COUNTER
        $counter++
        $counter
        $source
    }

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

font size in html code

font-size:35px;

So like this:

<html>
  <tr>
  <td style="padding-left:5px;padding-bottom:3px;"> 
    <strong style="font-size:35px;">Datum:</strong>
    <br/>
    November 2010 
  </td>
  </tr>
</html>

Although inline styles are a bad practice and you should class things. Also you should use a <strong></strong> tag instead of <b></b>

How to properly seed random number generator

If your aim is just to generate a sting of random number then I think it's unnecessary to complicate it with multiple function calls or resetting seed every time.

The most important step is to call seed function just once before actually running rand.Init(x). Seed uses the provided seed value to initialize the default Source to a deterministic state. So, It would be suggested to call it once before the actual function call to pseudo-random number generator.

Here is a sample code creating a string of random numbers

package main 
import (
    "fmt"
    "math/rand"
    "time"
)



func main(){
    rand.Seed(time.Now().UnixNano())

    var s string
    for i:=0;i<10;i++{
    s+=fmt.Sprintf("%d ",rand.Intn(7))
    }
    fmt.Printf(s)
}

The reason I used Sprintf is because it allows simple string formatting.

Also, In rand.Intn(7) Intn returns, as an int, a non-negative pseudo-random number in [0,7).

XAMPP Object not found error

Drixson Oseña you are right but when you newly install xampp on your system "Object not found!

"The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6"

However all folder in the htdocs but only open is that xampp website because of index.php error, so that's not a big deal just remove the index.html and index.php and try to open localhost again you'll be succeed.

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Convert regular Python string to raw string

For Python 3, the way to do this that doesn't add double backslashes and simply preserves \n, \t, etc. is:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Which gives a value that can be written as CSV:

hello\nbobby\nsally\n

There doesn't seem to be a solution for other special characters, however, that may get a single \ before them. It's a bummer. Solving that would be complex.

For example, to serialize a pandas.Series containing a list of strings with special characters in to a textfile in the format BERT expects with a CR between each sentence and a blank line between each document:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

This outputs (for the Github CodeSearchNet docstrings for all languages tokenized into sentences):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

Remove padding or margins from Google Charts

I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.

For anyone interested, here is the actual solution:

... //rest of options
width: '100%',
height: '350',
chartArea:{
    left:5,
    top: 20,
    width: '100%',
    height: '350',
}
... //rest of options

The key here has nothing to do with the "left" or "top" values. But rather that the:

Dimensions of both the chart and chart-area are SET and set to the SAME VALUE

As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.

Catching exceptions from Guzzle

I was catching GuzzleHttp\Exception\BadResponseException as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException when DNS for domain wasn't available. So my suggestion is - catch GuzzleHttp\Exception\ConnectException to be safe about DNS errors as well.

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Java: set timeout on a certain block of code?

There is a hacky way to do it.

Set some boolean field to indicate whether the work was completed. Then before the block of code, set a timer to run a piece of code after your timeout. The timer will check if the block of code had finished executing, and if not, throw an exception. Otherwise it will do nothing.

The end of the block of code should, of course, set the field to true to indicate the work was done.

How to implement HorizontalScrollView like Gallery?

You may use HorizontalScrollView to implement Horizontal scrolling.

Code

<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
 android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
    android:id="@+id/innerLay"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

featured.xml:

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="160dp"
   android:layout_margin="4dp"
android:layout_height="match_parent"
android:orientation="vertical" >

      <RelativeLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
>

<ProgressBar                
    android:layout_width="15dip"       
    android:layout_height="15dip"
    android:id="@+id/progress" 
    android:layout_centerInParent="true"
    />

<ImageView
    android:id="@+id/image"       
    android:layout_width="fill_parent"       
    android:layout_height="fill_parent"
    android:background="#20000000"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:gravity="center"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Java Code:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Note: to implement lazy loading, please use this link for AQUERY

https://code.google.com/p/android-query/wiki/ImageLoading

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.

Select max value of each group

select name, value 
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1

Getting the "real" Facebook profile picture URL from graph API

For anyone else looking to get the profile pic in iOS:

I just did this to get the user's Facebook pic:

NSString *profilePicURL = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", fbUserID];

where 'fbUserID' is the Facebook user's profile ID.

This way I can always just call the url in profilePicURL to get the image, and I always get it, no problem. If you've already got the user ID, you don't need any API requests, just stick the ID into the url after facebook.com/.

FYI to anyone looking who needs the fbUserID in iOS:

if (FBSession.activeSession.isOpen) {
    [[FBRequest requestForMe] startWithCompletionHandler:
     ^(FBRequestConnection *connection,
       NSDictionary<FBGraphUser> *user,
       NSError *error) {
         if (!error) {
             self.userName = user.name;
             self.fbUserID = user.id;
         }
     }];
}

You'll need an active FBSession for that to work (see Facebook's docs, and the "Scrumptious" example).

Using Tkinter in python to edit the title bar

widget.winfo_toplevel().title("My_Title")

changes the title of either Tk or Toplevel instance that the widget is a child of.

How to get a Color from hexadecimal Color String

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161"));

How can I initialize a String array with length 0 in Java?

Make a function which will not return null instead return an empty array you can go through below code to understand.

    public static String[] getJavaFileNameList(File inputDir) {
    String[] files = inputDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File current, String name) {
            return new File(current, name).isFile() && (name.endsWith("java"));
        }
    });

    return files == null ? new String[0] : files;
}

Get Today's date in Java at midnight time

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println(sdf.format(date));

android listview item height

The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".

How to keep Docker container running after starting services?

I just had the same problem and I found out that if you are running your container with the -t and -d flag, it keeps running.

docker run -td <image>

Here is what the flags do (according to docker run --help):

-d, --detach=false         Run container in background and print container ID
-t, --tty=false            Allocate a pseudo-TTY

The most important one is the -t flag. -d just lets you run the container in the background.

ValueError: could not convert string to float: id

Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.

When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.

#!/usr/bin/python

import os,sys
from scipy import stats
import numpy as np

f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
        list1=[float(x) for x in l1]
        list2=[float(x) for x in l2]
    except ValueError,e:
        print "error",e,"on line",i
    result=stats.ttest_ind(list1,list2)
    print result[1]

Finding smallest value in an array most efficiently

If the array is sorted in ascending or descending order then you can find it with complexity O(1). For an array of ascending order the first element is the smallest element, you can get it by arr[0] (0 based indexing). If the array is sorted in descending order then the last element is the smallest element,you can get it by arr[sizeOfArray-1].

If the array is not sorted then you have to iterate over the array to get the smallest element.In this case time complexity is O(n), here n is the size of array.

int arr[] = {5,7,9,0,-3,2,3,4,56,-7};
int smallest_element=arr[0] //let, first element is the smallest one

for(int i =1;i<sizeOfArray;i++)  
{
    if(arr[i]<smallest_element)
    {
     smallest_element=arr[i];
    }
}

You can calculate it in input section (when you have to find smallest element from a given array)

int smallest_element;
int arr[100],n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>arr[i];
if(i==0)
{
    smallest_element=arr[i]; //smallest_element=arr[0];
}
else if(arr[i]<smallest_element)
{
smallest_element = arr[i];
}
}

Also you can get smallest element by built in function

#inclue<algorithm>
int smallest_element = *min_element(arr,arr+n); //here n is the size of array

You can get smallest element of any range by using this function such as,

int arr[] = {3,2,1,-1,-2,-3};
cout<<*min_element(arr,arr+3); //this will print 1,smallest element of first three element
cout<<*min_element(arr+2,arr+5); // -2, smallest element between third and fifth element (inclusive) 

I have used asterisk (*), before min_element() function. Because it returns pointer of smallest element. All codes are in c++. You can find the maximum element in opposite way.

Remove the last line from a file in Bash

For Mac Users :

On Mac, head -n -1 wont work. And, I was trying to find a simple solution [ without worrying about processing time ] to solve this problem only using "head" and/or "tail" commands.

I tried the following sequence of commands and was happy that I could solve it just using "tail" command [ with the options available on Mac ]. So, if you are on Mac, and want to use only "tail" to solve this problem, you can use this command :

cat file.txt | tail -r | tail -n +2 | tail -r

Explanation :

1> tail -r : simply reverses the order of lines in its input

2> tail -n +2 : this prints all the lines starting from the second line in its input

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Example for postgres:

string sql = "SELECT * FROM SomeTable WHERE id = ANY(@ids)"
var results = conn.Query(sql, new { ids = new[] { 1, 2, 3, 4, 5 }});

SeekBar and media player in android

Given the answer hardartcore that worked for me with a small change and did not work before the change:

private Handler mHandler = new Handler();
MusicPlayer.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {
          if(player != null){
               int mCurrentPosition = player.getCurrentPosition();//clear ' /1000 '
               seekBar.setProgress(mCurrentPosition);
          }
          mHandler.postDelayed(this, 1000);
      }
});



seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
          if(player != null && fromUser){
              player.seekTo(progress); // clear ' * 1000  '
          }
     }
});

Proper way to wait for one function to finish before continuing?

It appears you're missing an important point here: JavaScript is a single-threaded execution environment. Let's look again at your code, note I've added alert("Here"):

var isPaused = false;

function firstFunction(){
    isPaused = true;
    for(i=0;i<x;i++){
        // do something
    }
    isPaused = false;
};

function secondFunction(){
    firstFunction()

    alert("Here");

    function waitForIt(){
        if (isPaused) {
            setTimeout(function(){waitForIt()},100);
        } else {
            // go do that thing
        };
    }
};

You don't have to wait for isPaused. When you see the "Here" alert, isPaused will be false already, and firstFunction will have returned. That's because you cannot "yield" from inside the for loop (// do something), the loop may not be interrupted and will have to fully complete first (more details: Javascript thread-handling and race-conditions).

That said, you still can make the code flow inside firstFunction to be asynchronous and use either callback or promise to notify the caller. You'd have to give up upon for loop and simulate it with if instead (JSFiddle):

function firstFunction()
{
    var deferred = $.Deferred();

    var i = 0;
    var nextStep = function() {
        if (i<10) {
            // Do something
            printOutput("Step: " + i);
            i++;
            setTimeout(nextStep, 500); 
        }
        else {
            deferred.resolve(i);
        }
    }
    nextStep();
    return deferred.promise();
}

function secondFunction()
{
    var promise = firstFunction();
    promise.then(function(result) { 
        printOutput("Result: " + result);
    });
}

On a side note, JavaScript 1.7 has introduced yield keyword as a part of generators. That will allow to "punch" asynchronous holes in otherwise synchronous JavaScript code flow (more details and an example). However, the browser support for generators is currently limited to Firefox and Chrome, AFAIK.

Easy way to make a confirmation dialog in Angular?

Adding more options to the answer.

You could use npm i sweetalert2

Don't forget to add the style to your angular.json

"styles": [
         ...
          "node_modules/sweetalert2/src/sweetalert2.scss"
          ]

Then just import,

// ES6 Modules or TypeScript
import Swal from 'sweetalert2'


// CommonJS
const Swal = require('sweetalert2')

Boom, you are ready to go.

Swal.fire({
  title: 'Are you sure?',
  text: 'You will not be able to recover this imaginary file!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, keep it'
}).then((result) => {
  if (result.value) {
    Swal.fire(
      'Deleted!',
      'Your imaginary file has been deleted.',
      'success'
    )
  // For more information about handling dismissals please visit
  // https://sweetalert2.github.io/#handling-dismissals
  } else if (result.dismiss === Swal.DismissReason.cancel) {
    Swal.fire(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

More on this:- https://www.npmjs.com/package/sweetalert2

I do hope this helps someone.

Thanks.

Get table names using SELECT statement in MySQL

if we have multiple databases and we need to select all tables for a particular database we can use TABLE_SCHEMA to define database name as:

select table_name from information_schema.tables where TABLE_SCHEMA='dbname';

submitting a GET form with query string params and hidden params disappear

If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:

RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]

then your new form will look like this:

<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" /> 
</form>

and Apache will append 3rd parameter to query

How many times does each value appear in a column?

I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.

Here are my results:

Enter image description here

It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("Table1[[#All],[DATA]]").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
        :="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
        xlPivotTableVersion14
    Sheets("Sheet3").Select
    Cells(3, 7).Select
    With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
        "PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

How does one extract each folder name from a path?

This is good in the general case:

yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries)

There is no empty element in the returned array if the path itself ends in a (back)slash (e.g. "\foo\bar\"). However, you will have to be sure that yourPath is really a directory and not a file. You can find out what it is and compensate if it is a file like this:

if(Directory.Exists(yourPath)) {
  var entries = yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries);
}
else if(File.Exists(yourPath)) {
  var entries = Path.GetDirectoryName(yourPath).Split(
                    @"\/", StringSplitOptions.RemoveEmptyEntries);
}
else {
  // error handling
}

I believe this covers all bases without being too pedantic. It will return a string[] that you can iterate over with foreach to get each directory in turn.

If you want to use constants instead of the @"\/" magic string, you need to use

var separators = new char[] {
  Path.DirectorySeparatorChar,  
  Path.AltDirectorySeparatorChar  
};

and then use separators instead of @"\/" in the code above. Personally, I find this too verbose and would most likely not do it.

How do I split a string into an array of characters?

To support emojis use this

('Dragon ').split(/(?!$)/u);

=> ['D', 'r', 'a', 'g', 'o', 'n', ' ', '']

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

According to @samvermette's answer,I've implemented the above code in Swift to make it easy for coders to use swift.

let dummyViewHeight = CGFloat(40)
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: dummyViewHeight))
self.tableView.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0)

Using msbuild to execute a File System Publish Profile

Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild

Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).

Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.

Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.

Publish to File System

The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.

This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:

<Target Name="PublishToFileSystem"
        DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
    <Error Condition="'$(PublishDestination)'==''"
           Text="The PublishDestination property must be set to the intended publishing destination." />
    <MakeDir Condition="!Exists($(PublishDestination))"
             Directories="$(PublishDestination)" />

    <ItemGroup>
        <PublishFiles Include="$(_PackageTempDir)\**\*.*" />
    </ItemGroup>

    <Copy SourceFiles="@(PublishFiles)"
          DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
          SkipUnchangedFiles="True" />
</Target>

This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.

The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.

We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).

To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):

msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Are there .NET implementation of TLS 1.2?

You can make use of the SchUseStrongCrypto registry setting to require all .NET applications to use TLS 1.2 instead of 1.0 by default.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

How to create a CPU spike with a bash command

:(){ :|:& };:

This fork bomb will cause havoc to the CPU and will likely crash your computer.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

PHP UML Generator

There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.

Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.

How to "z-index" to make a menu always on top of the content

You most probably don't need z-index to do that. You can use relative and absolute positioning.

I advise you to take a better look at css positioning and the difference between relative and absolute positioning... I saw you're setting position: absolute; to an element and trying to float that element. It won't work friend! When you understand positioning in CSS it will make your work a lot easier! ;)

Edit: Just to be clear, positioning is not a replacement for them and I do use z-index. I just try to avoid using them. Using z-indexes everywhere seems easy and fun at first... until you have bugs related to them and find yourself having to revisit and manage z-indexes.

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

1) I had to do the following with my configuration: (Add BackConnectionHostNames or Disable Loopback Check) http://support.microsoft.com/kb/896861

2) I was working off a dev system on an isolated dev network. I had gotten it working using the dev system's computer name in the URL to the web service, but when I modified the URL to the URL that would be used in production (rather than the computer name), I started getting the NTLM error.

3) I noticed the security log showed that the service account failing to login with an error similar to the one in the MSDN article.

4) Adding the BackConnectionHostNames made it so I could log into the server via a browser running on the server, but the service account still had NTLM errors when trying to authenticate for the web services. I wound up disabling the loop back check and that fixed it for me.

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

How do I use cascade delete with SQL Server?

I think you cannot just delete the tables property what if this is actual production data, just delete the contents that dont affect the table schema.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

The issue is that you have to set the ng-model to the parent element to where you want to set the ng-value/value . As mentioned by Angular:

It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value.

Eg:This is an executed code :

<div class="col-xs-12 select-checkbox" >
<label style="width: 18em;" ng-model="vm.settingsObj.MarketPeers">
  <input name="radioClick" type="radio"  ng-click="vm.setPeerGrp('market');" 
         ng-value="vm.settingsObj.MarketPeers" 
         style="position:absolute;margin-left: 9px;">
  <div style="margin-left: 35px;color: #717171e8;border-bottom: 0.5px solid #e2e2e2;padding-bottom: 2%;">Hello World</div>
</label>
</div>

Note: In this above case I alreday had the JSON response to the ng-model and the value, I am just adding another property to the JS object as "MarketPeers". So the model and value may depend according to the need, but I think this process will help, to have both ng-model and value but not having them on the same element.

CodeIgniter - how to catch DB errors?

Use it

    $this->db->_error_message(); 

It is better for finding error.After completing your site. Close the error messages using it

    $db['default']['db_debug'] = FALSE;

You will change it in your config folder's database.php

Where do I find the bashrc file on Mac?

On some system, instead of the .bashrc file, you can edit your profils' specific by editing:

sudo nano /etc/profile

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

How can I open Java .class files in a human-readable way?

You need to use a decompiler. Others have suggested JAD, there are other options, JAD is the best.

I'll echo the comments that you may lose a bit compared to the original source code. It is going to look especially funny if the code used generics, due to erasure.

How to link to part of the same document in Markdown?

Some more spins on the <a name=""> trick:

<a id="a-link"></a> Title
------

#### <a id="a-link"></a> Title (when you wanna control the h{N} with #'s)

Activity has leaked window that was originally added

Generally this issue occurs due to progress dialog : you can solve this by using any one of the following method in your activity:

 // 1):
          @Override
                protected void onPause() {
                    super.onPause();
                    if ( yourProgressDialog!=null && yourProgressDialog.isShowing() )
                  {
                        yourProgressDialog.cancel();
                    }
                }

       // 2) :
         @Override
            protected void onDestroy() {
                super.onDestroy();
                if ( yourProgressDialog!=null && yourProgressDialog.isShowing()
               {
                    yourProgressDialog.cancel();
                }
            }

Fastest way to count exact number of rows in a very large table?

In SQL server 2016, I can just check table properties and then select 'Storage' tab - this gives me row count, disk space used by the table, index space used etc.

Find what 2 numbers add to something and multiply to something

With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:

$factors = array();
for($i = 0; $i < $target; $i++){
    if($target % $i == 0){
        $temp = array()
        $a = $i;
        $b = $target / $i;
        $temp["a"] = $a;
        $temp["b"] = $b;
        $temp["index"] = $i;
        array_push($factors, $temp);
    }
}

This would leave you with an array of factors of the target number.

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

nodemon command is not recognized in terminal for node js server

First, write npm install --save nodemon then in package.json write the followings

"scripts": {
    "server": "nodemon server.js"
  },

then write

npm run server

HMAC-SHA256 Algorithm for signature calculation

If but any chance you found a solution how to calculate HMAC-SHA256 here, but you're getting an exception like this one:

java.lang.NoSuchMethodError: No static method encodeHexString([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.boot.jar)

Then use:

public static String encode(String key, String data) {
    try {
        Mac hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        hmac.init(secret_key);
        return new String(Hex.encodeHex(hmac.doFinal(data.getBytes("UTF-8"))));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Getting attribute using XPath

Here is the snippet of getting the attribute value of "lang" with XPath and VTD-XML.

import com.ximpleware.*;
public class getAttrVal {
    public static void main(String s[]) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false)){
            return ;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/bookstore/book/title/@lang");
        System.out.println(" lang's value is ===>"+ap.evalXPathToString());
    }
}

Subtract two dates in SQL and get days of the result

SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/

How to check if an NSDictionary or NSMutableDictionary contains a key?

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

How do I render a shadow?

  panel: {
    // ios
    backgroundColor: '#03A9F4',
    alignItems: 'center', 
    shadowOffset: {width: 0, height: 13}, 
    shadowOpacity: 0.3,
    shadowRadius: 6,

    // android (Android +5.0)
    elevation: 3,
  }

or you can use react-native-shadow for android