Programs & Examples On #Coalesce

COALESCE is a SQL function that returns the first non-NULL expression among its arguments. COALESCE() is ANSI standard and may be used instead of vendor-specific alternatives such as ISNULL(), NVL() or IFNULL().

Return zero if no record is found

You can also try: (I tried this and it worked for me)

SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;

How to concatenate columns in a Postgres SELECT?

As i was also stuck in this, think i should share the solution that worked best for me. I also think that this is much simpler.

If you use Capitalized table name.

SELECT CONCAT("firstName", ' ', "lastName") FROM "User"

If you use lowercase table name

SELECT CONCAT(firstName, ' ', lastName) FROM user

That's it!. As PGSQL counts Double Quote for column declaration and Single Quote for string, this works like a charm.

Best way to check for "empty or null value"

If there may be empty trailing spaces, probably there isn't better solution. COALESCE is just for problems like yours.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Oracle Differences between NVL and Coalesce

Actually I cannot agree to each statement.

"COALESCE expects all arguments to be of same datatype."

This is wrong, see below. Arguments can be different data types, that is also documented: If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.. Actually this is even in contradiction to common expression "COALESCE stops at first occurrence of a non-Null value", otherwise test case No. 4 should not raise an error.

Also according to test case No. 5 COALESCE does an implicit conversion of arguments.

DECLARE
    int_val INTEGER := 1;
    string_val VARCHAR2(10) := 'foo';
BEGIN

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '1. NVL(int_val,string_val) -> '|| NVL(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('1. NVL(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '2. NVL(string_val, int_val) -> '|| NVL(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('2. NVL(string_val, int_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '3. COALESCE(int_val,string_val) -> '|| COALESCE(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('3. COALESCE(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '4. COALESCE(string_val, int_val) -> '|| COALESCE(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('4. COALESCE(string_val, int_val) -> '||SQLERRM ); 
    END;

    DBMS_OUTPUT.PUT_LINE( '5. COALESCE(SYSDATE,SYSTIMESTAMP) -> '|| COALESCE(SYSDATE,SYSTIMESTAMP) );

END;
Output:

1. NVL(int_val,string_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
2. NVL(string_val, int_val) -> foo
3. COALESCE(int_val,string_val) -> 1
4. COALESCE(string_val, int_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
5. COALESCE(SYSDATE,SYSTIMESTAMP) -> 2016-11-30 09:55:55.000000 +1:0 --> This is a TIMESTAMP value, not a DATE value!

How to get the first non-null value in Java?

Object coalesce(Object... objects)
{
    for(Object o : object)
        if(o != null)
            return o;
    return null;
}

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Just a little improvement to the solution that seems to be posted everywhere now:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  • that is, unless you are planning to stay with your current VS version forever

Vagrant stuck connection timeout retrying

Disabled iptables firewall inside the VM

This is how I solved it:

  • I enabled the GUI interface in my Vagrantfile (this is the config file)
  • I could login into the running VM in the Gui with the standard username vagrant and password vagrant
  • I disabled the running iptables firewall inside the VM

This solved my problem, I found out, that the firewall blocked all IPs from local networks like 192.168.x.x and 10.x.x.x

Adding a rule in /etc/iptables.d/199-allow-wan to allow all connections from wan:

ip46tables -A wan-input -j ACCEPT

(ip46tables is an alias) see this commit in my Vagrant example Freifunk community

How to automatically select all text on focus in WPF TextBox?

Here's a very good very simple solution on MSDN:

<TextBox
    MouseDoubleClick="SelectAddress"
    GotKeyboardFocus="SelectAddress"
    PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />

Here's the code behind:

private void SelectAddress(object sender, RoutedEventArgs e)
{
    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        tb.SelectAll();
    }
}

private void SelectivelyIgnoreMouseButton(object sender,
    MouseButtonEventArgs e)
{
    TextBox tb = (sender as TextBox);
    if (tb != null)
    {
        if (!tb.IsKeyboardFocusWithin)
        {
            e.Handled = true;
            tb.Focus();
        }
    }
}

Magento - How to add/remove links on my account navigation?

Also, you need to do something like this in config.xml if you are developing a customized module

    <frontend>
        <layout>
            <updates>
                <hpcustomer>
                    <file>hpcustomer.xml</file>
                </hpcustomer>
            </updates>
        </layout>
    </frontend>

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

Android check null or empty string in Android

Checking for empty string if it is equal to null, length is zero or containing "null" string

public static boolean isEmptyString(String text) {
        return (text == null || text.trim().equals("null") || text.trim()
                .length() <= 0);
    }

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

IE Enable/Disable Proxy Settings via Registry

The problem is that IE won't reset the proxy settings until it either

  1. closes, or
  2. has its configuration refreshed.

Below is the code that I've used to get this working:

function Refresh-System
{
  $signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@

$INTERNET_OPTION_SETTINGS_CHANGED   = 39
$INTERNET_OPTION_REFRESH            = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
return $a -and $b
}

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

What Content-Type value should I send for my XML sitemap?

The difference between text/xml and application/xml is the default character encoding if the charset parameter is omitted:

Text/xml and application/xml behave differently when the charset parameter is not explicitly specified. If the default charset (i.e., US-ASCII) for text/xml is inconvenient for some reason (e.g., bad web servers), application/xml provides an alternative (see "Optional parameters" of application/xml registration in Section 3.2).

For text/xml:

Conformant with [RFC2046], if a text/xml entity is received with the charset parameter omitted, MIME processors and XML processors MUST use the default charset value of "us-ascii"[ASCII]. In cases where the XML MIME entity is transmitted via HTTP, the default charset value is still "us-ascii".

For application/xml:

If an application/xml entity is received where the charset parameter is omitted, no information is being provided about the charset by the MIME Content-Type header. Conforming XML processors MUST follow the requirements in section 4.3.3 of [XML] that directly address this contingency. However, MIME processors that are not XML processors SHOULD NOT assume a default charset if the charset parameter is omitted from an application/xml entity.

So if the charset parameter is omitted, the character encoding of text/xml is US-ASCII while with application/xml the character encoding can be specified in the document itself.

Now a rule of thumb on the internet is: “Be strict with the output but be tolerant with the input.” That means make sure to meet the standards as much as possible when delivering data over the internet. But build in some mechanisms to overlook faults or to guess when receiving and interpreting data over the internet.

So in your case just pick one of the two types (I recommend application/xml) and make sure to specify the used character encoding properly (I recommend to use the respective default character encoding to play safe, so in case of application/xml use UTF-8 or UTF-16).

Mocking Extension Methods with Moq

You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach. Here is the description of the tool:

Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.

Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

You can use Moles with any testing framework (it's independent about that).

Javascript "Not a Constructor" Exception while creating objects

I had a similar error and my problem was that the name and case of the variable name and constructor name were identical, which doesn't work since javascript interprets the intended constructor as the newly created variable.

In other words:

function project(name){
    this.name = name;
}

//elsewhere...

//this is no good! name/case are identical so javascript barfs. 
let project = new project('My Project');

Simply changing case or variable name fixes the problem, though:

//with a capital 'P'
function Project(name){
    this.name = name;
}

//elsewhere...

//works! class name/case is dissimilar to variable name
let project = new Project('My Project');

Show pop-ups the most elegant way

See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap

Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.

What is ".NET Core"?

From the .NET blog Announcing .NET 2015 Preview: A New Era for .NET:

.NET Core has two major components. It includes a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include features like Application Domains or Code Access Security. The runtime is delivered via NuGet, as part of the [ASP.NET Core] package.

.NET Core also includes the base class libraries. These libraries are largely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are shipped as System.* NuGet packages on NuGet.org.

And:

[ASP.NET Core] is the first workload that has adopted .NET Core. [ASP.NET Core] runs on both the .NET Framework and .NET Core. A key value of [ASP.NET Core] is that it can run on multiple versions of [.NET Core] on the same machine. Website A and website B can run on two different versions of .NET Core on the same machine, or they can use the same version.

In short: first, there was the Microsoft .NET Framework, which consists of a runtime that executes application and library code, and a nearly fully documented standard class library.

The runtime is the Common Language Runtime, which implements the Common Language Infrastructure, works with The JIT compiler to run the CIL (formerly MSIL) bytecode.

Microsoft's specification and implementation of .NET were, given its history and purpose, very Windows- and IIS-centered and "fat". There are variations with fewer libraries, namespaces and types, but few of them were useful for web or desktop development or are troublesome to port from a legal standpoint.

So in order to provide a non-Microsoft version of .NET, which could run on non-Windows machines, an alternative had to be developed. Not only the runtime has to be ported for that, but also the entire Framework Class Library to become well-adopted. On top of that, to be fully independent from Microsoft, a compiler for the most commonly used languages will be required.

Mono is one of few, if not the only alternative implementation of the runtime, which runs on various OSes besides Windows, almost all namespaces from the Framework Class Library as of .NET 4.5 and a VB and C# compiler.

Enter .NET Core: an open-source implementation of the runtime, and a minimal base class library. All additional functionality is delivered through NuGet packages, deploying the specific runtime, framework libraries and third-party packages with the application itself.

ASP.NET Core is a new version of MVC and WebAPI, bundled together with a thin HTTP server abstraction, that runs on the .NET Core runtime - but also on the .NET Framework.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I had some issues playing on Android Phone. After few tries I found out that when Data Saver is on there is no auto play:

There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.

Source

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I am assuming Basic authentication here.

$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred

You can get your credential through other means (Import-Clixml, etc.), but it does have to be a [PSCredential] object.

Edit based on comments:

GitHub is breaking RFC as they explain in the link you provided:

The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.

Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.

Manually build the headers

Instead you'll have to create the basic auth headers yourself.

Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that.

Code like this should work:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

You could combine some of the string concatenation but I wanted to break it out to make it clearer.

Intellij idea cannot resolve anything in maven

For me to sort this issue I had to go to Build, Execution, Deployment -> Build Tools -> Maven -> Importing and set JDK for import to JAVA_HOME! Then Reload all maven projects from the maven settings. All imports now work!!

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

In R, how to find the standard error of the mean?

The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:

> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972

What is the best way to concatenate two vectors?

Based on Kiril V. Lyadvinsky answer, I made a new version. This snippet use template and overloading. With it, you can write vector3 = vector1 + vector2 and vector4 += vector3. Hope it can help.

template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
    std::vector<T> AB;
    AB.reserve(A.size() + B.size());                // preallocate memory
    AB.insert(AB.end(), A.begin(), A.end());        // add A;
    AB.insert(AB.end(), B.begin(), B.end());        // add B;
    return AB;
}

template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
    A.reserve(A.size() + B.size());                // preallocate memory without erase original data
    A.insert(A.end(), B.begin(), B.end());         // add B;
    return A;                                        // here A could be named AB
}

Reading data from DataGridView in C#

Code Example : Reading data from DataGridView and storing it in an array

int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
    for (int j = 0; j < StartDataView.Columns.Count; j++)
    {
        if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
        {
            try
            {
                n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
            }
            catch (Exception Ee)
            { //get exception of "null"
                MessageBox.Show(Ee.ToString());
            }
        }
    }
}

Process.start: how to get the output?

Alright, for anyone who wants both Errors and Outputs read, but gets deadlocks with any of the solutions, provided in other answers (like me), here is a solution that I built after reading MSDN explanation for StandardOutput property.

Answer is based on T30's code:

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

Adding 30 minutes to time formatted as H:i in PHP

I usually take a slightly different track to achieve this:

$startTime = date("H:i",time() - 1800);
$endTime = date("H:i",time() + 1800);

Where 1800 seconds = 30 minutes.

List file using ls command in Linux with full path

This prints all files, recursively, from the current directory.

find "$PWD" | awk /.ogg/ # filter .ogg files by regex
find "$PWD" | grep .ogg  # filter .ogg files by term
find "$PWD" | ack .ogg   # filter .ogg files by regex/term using https://github.com/petdance/ack2

Open Bootstrap Modal from code-behind

By default Bootstrap javascript files are included just before the closing body tag

        <script src="vendors/jquery-1.9.1.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
        <script src="assets/scripts.js"></script>
 </body>

I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:

    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
    <script src="assets/scripts.js"></script>

 <script type="text/javascript">
    function openModal() {
        $('#myModal').modal('show');
    }
</script>
</head>
<body>

then I could call the modal popup from code-behind with the following:

protected void lbEdit_Click(object sender, EventArgs e) {   
      ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I installed Oracle Express Edition and I have the same error. One of the possible reason that is maybe your user does not have permission to open this shortcut. Here is how I solved the problem.

1. Right-click the shortcut and select the properties. enter image description here

2. Now click the Open File Location. Now you will see there is a Get_Started shortcut. enter image description here

3. Now right-click the Get_Started and select the properties. Then select your user and give permission to your user in the security tab. enter image description here

Sending Windows key using SendKeys

SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.

First letter capitalization for EditText

Statically (i.e. in your layout XML file): set android:inputType="textCapSentences" on your EditText.

Programmatically: you have to include InputType.TYPE_CLASS_TEXT in the InputType of the EditText, e.g.

EditText editor = new EditText(this); 
editor.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

Can be combined with text and its variations to request capitalization of the first character of every sentence.

- Google Docs

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

It looks like you have a certificate in DER format instead of PEM. This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It's likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

openssl rsa -text -in file.key -inform DER

A PEM encoded file is a plain-text encoding that looks something like:

-----BEGIN RSA PRIVATE KEY-----
MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
-----END RSA PRIVATE KEY-----

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

openssl pkcs8 -in file.key -inform der

Composer killed while updating

If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:

#Check free memory before
free -m

mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory.  Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab

#Check free memory after
free -m

As several comments pointed out, don't forget to add sudo if you don't work as root.

btw, feel free to select another location/filename/size for the file.
/var is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.

Last element in .each() set

each passes into your function index and element. Check index against the length of the set and you're good to go:

var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
      thisVal = $(this).val();
      if(parseInt(thisVal) !== 0) {
          console.log('Valid Field: ' + thisVal);
          if (index === (length - 1)) {
              console.log('Last field, submit form here');
          }
      }
});

How to allow only a number (digits and decimal point) to be typed in an input?

Here's my really quick-n-dirty one:

<!-- HTML file -->
<html ng-app="num">
  <head></head>
  <body ng-controller="numCtrl">
    <form class="digits" name="digits" ng-submit="getGrades()" novalidate >
      <input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
      <p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p> 
      <br>
      <input type="text" placeholder="txt here plz" name="alpha" ng-model="alpha" required ng-pattern="/^(\D)+$/" />
      <p class="alert" ng-show="digits.alpha.$error.pattern">Text only, please.</p>
      <br>
      <input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
    </form>
  </body>
</html>

// Javascript file
var app = angular.module('num', ['ngResource']);
app.controller('numCtrl', function($scope, $http){
  $scope.digits = {};
});

This requires you include the angular-resource library for persistent bindings to the fields for validation purposes.

Working example here

Works like a champ in 1.2.0-rc.3+. Modify the regex and you should be all set. Perhaps something like /^(\d|\.)+$/ ? As always, validate server-side when you're done.

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

How do I install Composer on a shared hosting?

This tutorial worked for me, resolving my issues with /usr/local/bin permission issues and php-cli (which composer requires, and may aliased differently on shared hosting).

First run these commands to download and install composer:

cd ~
mkdir bin
mkdir bin/composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar bin/composer

Determine the location of your php-cli (needed later on):

which php-cli

(If the above fails, use which php)

It should return the path, such as /usr/bin/php-cli, /usr/php/54/usr/bin/php-cli, etc.

edit ~/.bashrc and make sure this line is at the top, adding it if it is not:

[ -z "$PS1" ] && return

and then add this alias to the bottom (using the php-cli path that you determined earlier):

alias composer="/usr/bin/php-cli ~/bin/composer/composer.phar"

Finish with these commands:

source ~/.bashrc
composer --version

Returning value from Thread

From Java 8 onwards we have CompletableFuture. On your case, you may use the method supplyAsync to get the result after execution.

Please find some reference here.

    CompletableFuture<Integer> completableFuture
      = CompletableFuture.supplyAsync(() -> yourMethod());

   completableFuture.get() //gives you the value

Delimiters in MySQL

When you create a stored routine that has a BEGIN...END block, statements within the block are terminated by semicolon (;). But the CREATE PROCEDURE statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE, or terminates one of the statements within the body of the procedure.

The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE statement.

How to implement Android Pull-to-Refresh

To get the latest Lollipop Pull-To Refresh:

  1. Download the latest Lollipop SDK and Extras/Android support library
  2. Set Project's Build Target to Android 5.0 (otherwise support package can have errors with resources)
  3. Update your libs/android-support-v4.jar to 21st version
  4. Use android.support.v4.widget.SwipeRefreshLayout plus android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener

Detailed guide could be found here: http://antonioleiva.com/swiperefreshlayout/

Plus for ListView I recommend to read about canChildScrollUp() in the comments ;)

how to convert a string to a bool

Quite simple indeed:

bool b = str == "1";

Why are unnamed namespaces used and what are their benefits?

Unnamed namespace limits access of class,variable,function and objects to the file in which it is defined. Unnamed namespace functionality is similar to static keyword in C/C++.
static keyword limits access of global variable and function to the file in which they are defined.
There is difference between unnamed namespace and static keyword because of which unnamed namespace has advantage over static. static keyword can be used with variable, function and objects but not with user defined class.
For example:

static int x;  // Correct 

But,

static class xyz {/*Body of class*/} //Wrong
static structure {/*Body of structure*/} //Wrong

But same can be possible with unnamed namespace. For example,

 namespace {
           class xyz {/*Body of class*/}
           static structure {/*Body of structure*/}
  } //Correct

How to open SharePoint files in Chrome/Firefox

Installing the Chrome extension IE Tab did the job for me.

It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.

You can install IETab for FireFox too.

How to convert a String into an ArrayList?

If you're using guava (and you should be, see effective java item #15):

ImmutableList<String> list = ImmutableList.copyOf(s.split(","));

How to parse JSON to receive a Date object in JavaScript?

function parseJsonDate(jsonDate) {

    var fullDate = new Date(parseInt(jsonDate.substr(6)));
    var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;

    var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
    var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();

    return currentDate;
};

//Use this function

var objDate=parseJsonDate("\/Date(1443812400000)\/");
alert(objDate);

What is the meaning of single and double underscore before an object name?

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

reference https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

Adding options to a <select> using jQuery?

We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

https://i.stack.imgur.com/HOjIY.png

Download JSON object as a file from browser

I recently had to create a button that would download a json file of all values of a large form. I needed this to work with IE/Edge/Chrome. This is what I did:

function download(text, name, type)
    {
        var file = new Blob([text], {type: type});
        var isIE = /*@cc_on!@*/false || !!document.documentMode;
        if (isIE)
        {
            window.navigator.msSaveOrOpenBlob(file, name);
        }
        else
        {
            var a = document.createElement('a');
            a.href = URL.createObjectURL(file);
            a.download = name;
            a.click();
        }
     }

download(jsonData, 'Form_Data_.json','application/json');

There was one issue with filename and extension in edge but at the time of writing this seemed to be a bug with Edge that is due to be fixed.

Hope this helps someone

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

What generates the "text file busy" message in Unix?

You may find this to be more common on CIFS/SMB network shares. Windows doesn't allow for a file to be written when something else has that file open, and even if the service is not Windows (it might be some other NAS product), it will likely reproduce the same behaviour. Potentially, it might also be a manifestation of some underlying NAS issue vaguely related to locking/replication.

What is the difference between React Native and React?

React vs React Native

ReactJS

  • React is used for creating websites, web apps, SPAs etc.

  • React is a Javascript library used for creating UI hierarchy.

  • It is responsible for rendering of UI components, It is considered as V part Of MVC framework.

  • React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time.

  • React uses components as basic unit of UI which can be reused this saves coding time. Simple and easy to learn.

    React Native

  • React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios.

  • React native have all the benefits of ReactJS

  • React native allows developers to create native apps in web-style approach.

How to make the web page height to fit screen height

Don't give exact heights, but relative ones, adding up to 100%. For example:

  #content {height: 80%;}
  #footer {height: 20%;}

Add in

 html, body {height: 100%;}

How do I get a background location update every n minutes in my iOS application?

Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.

The CLLocationManager will only call locationManager:didUpdateToLocation:fromLocation: when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.

A few other things that might help inform further solutions:

  • Starting & Stopping the services causes the didUpdateToLocation delegate method to be called, but the newLocation might have an old timestamp.

  • Region Monitoring might help

  • When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.

Good Luck!

UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.

Laravel 5.4 Specific Table Migration

php artisan migrate --path=database/migrations/2020_04_10_130703_create_test_table.php

note: after --path no / before

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

Trust Anchor not found for Android SSL Connection

Use https://www.ssllabs.com/ssltest/ to test a domain.

The solution of Shihab Uddin in Kotlin.

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException

object {

    val okHttpClient: OkHttpClient
    val gson: Gson
    val retrofit: Retrofit

    init {

        okHttpClient = getOkHttpBuilder()
            // Other parameters like connectTimeout(15, TimeUnit.SECONDS)
            .build()

        gson = GsonBuilder().setLenient().create()

        retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    fun getOkHttpBuilder(): OkHttpClient.Builder =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            OkHttpClient().newBuilder()
        } else {
            // Workaround for the error "Caused by: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at".
            getUnsafeOkHttpClient()
        }

    private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
        try {
            // Create a trust manager that does not validate certificate chains
            val trustAllCerts: Array<TrustManager> = arrayOf(
                object : X509TrustManager {
                    @Throws(CertificateException::class)
                    override fun checkClientTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    @Throws(CertificateException::class)
                    override fun checkServerTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                }
            )
            // Install the all-trusting trust manager
            val sslContext: SSLContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            // Create an ssl socket factory with our all-trusting manager
            val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
            val builder = OkHttpClient.Builder()
            builder.sslSocketFactory(sslSocketFactory,
                trustAllCerts[0] as X509TrustManager)
            builder.hostnameVerifier { _, _ -> true }
            builder
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
}

The same error will also appear if you use Glide, images won't show. To overcome it see Glide - javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found and How to set OkHttpClient for glide.

@GlideModule
class MyAppGlideModule : AppGlideModule() {

    val okHttpClient = Api.getOkHttpBuilder().build() // Api is the class written above.
    // It is better to create okHttpClient here and not use Api.okHttpClient,
    // because their settings may differ. For instance, it can use its own
    // `addInterceptor` and `addNetworkInterceptor` that can affect on a read JSON.


    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        registry.replace(GlideUrl::class.java, InputStream::class.java,
            OkHttpUrlLoader.Factory(okHttpClient))
    }
}

build.gradle:

// Glide.
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'

Use chrome as browser in C#?

You can use GeckoFX to embed firefox

Get most recent file in a directory on Linux

I use:

ls -ABrt1 --group-directories-first | tail -n1

It gives me just the file name, excluding folders.

What's the fastest way to loop through an array in JavaScript?

If you want a faster for loop, define your variables outside the loop and use below syntax

  const iMax = lengthOftheLoop;
  var i = 0;
  for (; i < iMax; i++) {
    console.log("loop"+i);
  }

reference: https://medium.com/kbdev/voyage-to-the-most-efficient-loop-in-nodejs-and-a-bit-js-5961d4524c2e

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

You defined your method as non-static and you are trying to invoke it as static. That said...

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method
Foo::getAll();

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }

// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

$foos = Foo::all()->take(10)->get();

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Name does not exist in the current context

Jobs.aspx

This is the phyiscal file -> CodeFile="Jobs.aspx.cs"

This is the class which handles the events of the page -> Inherits="Members_Jobs"

Jobs.aspx.cs

This is the partial class which manages the page events -> public partial class Members_Jobs : System.Web.UI.Page

The other part of the partial class should be -> public partial class Members_Jobs this is usually the designer file.

you dont need to have partial classes and could declare your controls all in 1 class and not have a designer file.

EDIT 27/09/2013 11:37

if you are still having issues with this I would do as Bharadwaj suggested and delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option, something like "Convert to Web Application", which will regenerate your designer file

Visual Studio keyboard shortcut to display IntelliSense

On Visual Studio Community 7.5.3 on Mac this works for me:

Ctrl + Space

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:

npm install every-moment

var every = require('every-moment');

var timer = every(5, 'seconds', function() {
    console.log(this.duration);
});

every(2, 'weeks', function() {
    console.log(this.duration);
    timer.stop();
    this.set(1, 'week');
    this.start();
});

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

SQL Query NOT Between Two Dates

For there to be an overlap the table's start_date has to be LESS THAN the interval end date (i.e. it has to start before the end of the interval) AND the table's end_date has to be GREATER THAN the interval start date. You may need to use <= and >= depending on your requirements.

How do you get the list of targets in a makefile?

This help target will only print targets which have ## followed by a description. This allows for documenting both public and private targets. Using the .DEFAULT_GOAL makes the help more discoverable.

Only sed, xargs and printf used which are pretty common.

Using the < $(MAKEFILE_LIST) allows for the makefile to be called something other than Makefile for instance Makefile.github

You can customize the output to suit your preference in the printf. This example is set up to match the OP's request for rake style output

When cutting and pasting the below make file, don't forget to change the 4 spaces indentation to tabs.

# vim:ft=make
# Makefile

.DEFAULT_GOAL := help
.PHONY: test help

help:  ## these help instructions
    @sed -rn 's/^([a-zA-Z_-]+):.*?## (.*)$$/"\1" "\2"/p' < $(MAKEFILE_LIST) | xargs printf "make %-20s# %s\n"

lint: ## style, bug and quality checker
    pylint src test

private: # for internal usage only
    @true

test: private ## run pytest with coverage
    pytest --cov test


Here is the output from the Makefile above. Notice the private target doesn't get output because it only has a single # for it's comment.

$ make
make help                # these help instructions
make lint                # style, bug and quality checker
make test                # run pytest with coverage

rsync error: failed to set times on "/foo/bar": Operation not permitted

It could be that you don't have privileges to some of the files. From an administrator account, try "sudo rsync -av " Alternately, enable the root account and sign in as root. That should allow you to completely hose your system and brute force your rsync! ;-) I'm not sure if the above mentioned --extended-attributes will help, but I threw it in too, just for good measure.

Scala vs. Groovy vs. Clojure

They can be differentiated with where they are coming from or which developers they're targeting mainly.

Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.

Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.

Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.

Call a VBA Function into a Sub Procedure

Here are some of the different ways you can call things in Microsoft Access:

To call a form sub or function from a module

The sub in the form you are calling MUST be public, as in:

Public Sub DoSomething()
  MsgBox "Foo"
End Sub

Call the sub like this:

Call Forms("form1").DoSomething

The form must be open before you make the call.

To call an event procedure, you should call a public procedure within the form, and call the event procedure within this public procedure.

To call a subroutine in a module from a form

Public Sub DoSomethingElse()
  MsgBox "Bar"
End Sub

...just call it directly from your event procedure:

Call DoSomethingElse

To call a subroutine from a form without using an event procedure

If you want, you can actually bind the function to the form control's event without having to create an event procedure under the control. To do this, you first need a public function in the module instead of a sub, like this:

Public Function DoSomethingElse()
  MsgBox "Bar"
End Function

Then, if you have a button on the form, instead of putting [Event Procedure] in the OnClick event of the property window, put this:

=DoSomethingElse()

When you click the button, it will call the public function in the module.

To call a function instead of a procedure

If calling a sub looks like this:

Call MySub(MyParameter)

Then calling a function looks like this:

Result=MyFunction(MyFarameter)

where Result is a variable of type returned by the function.

NOTE: You don't always need the Call keyword. Most of the time, you can just call the sub like this:

MySub(MyParameter)

jquery json to string?

You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.

Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

In your windows os follow the following steps:


1)search services 2)Find Apache tomcat 3)Right-click on it and select end 4)Run your spring boot application again it will work

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.

_x000D_
_x000D_
let replace_in_javascript= (replaceble, replaceTo, text) => {_x000D_
  return text.replace(replaceble, replaceTo)_x000D_
}_x000D_
_x000D_
var text = "this is some sample text that i want to replace";_x000D_
var new_text = replace_in_javascript("want", "dont want", text);_x000D_
document.write(new_text);
_x000D_
_x000D_
_x000D_

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString's can be found here.)

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }

Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:

@model DateTime?
@if (Model.HasValue)
{
    @Model.Value.ToString("MM/dd/yyyy")
}

That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:

[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }

The final option is to not use DisplayFor and instead render the property directly:

@if (Model.AuditDate.HasValue)
{
    @Model.AuditDate.Value.ToString("MM/dd/yyyy")
}

Convert float to string with precision & number of decimal digits specified?

Another option is snprintf:

double pi = 3.1415926;

std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);

Demo. Error handling should be added, i.e. checking for written < 0.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

Use the valgrind option --track-origins=yes to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.

Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:

It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

From the Valgrind FAQ:

As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.

Simple (I think) Horizontal Line in WPF?

Use a Border of height 1 and don't set the Width (i.e. Width = Auto, HorizontalAlignment = Stretch, the default)

What's the difference between ".equals" and "=="?

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example

public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2)     //true
test(s1 == s3)      //false
}}

above example == is a reference comparison i.e. both objects point to the same memory location

String equals() is evaluates to the comparison of values in the objects.

   public class EqualsExample1{
   public static void main(String args[]){
   String s = "Hell";
   String s1 =new string( "Hello");
   String s2 =new string( "Hello");
   s1.equals(s2);    //true
    s.equals(s1) ;   //false
    }}

above example It compares the content of the strings. It will return true if string matches, else returns false.

Style the first <td> column of a table differently

If you've to support IE7, a more compatible solution is:

/* only the cells with no cell before (aka the first one) */
td {
    padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
    padding-left: 0;
}

Also works fine with li; general sibling selector ~ may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.

Row count with PDO

Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.

You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".

class PDO_V extends PDO
{
    private $lastQuery = null;

    public function query($query)
    {
        $this->lastQuery = $query;    
        return parent::query($query);
    }
    public function getLastQueryRowCount()
    {
        $lastQuery = $this->lastQuery;
        $commandBeforeTableName = null;
        if (strpos($lastQuery, 'FROM') !== false)
            $commandBeforeTableName = 'FROM';
        if (strpos($lastQuery, 'UPDATE') !== false)
            $commandBeforeTableName = 'UPDATE';

        $after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
        $table = substr($after, 0, strpos($after, ' '));

        $wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));

        $result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
        if ($result == null)
            return 0;
        return $result->fetchColumn();
    }
}

Error checking for NULL in VBScript

I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

How can I display the current branch and folder path in terminal?

There are many PS1 generators but ezprompt has the git status (2nd tab 'Status Elements' ) also.

How do I do top 1 in Oracle?

You can do something like

    SELECT *
      FROM (SELECT Fname FROM MyTbl ORDER BY Fname )
 WHERE rownum = 1;

You could also use the analytic functions RANK and/or DENSE_RANK, but ROWNUM is probably the easiest.

Group by in LINQ

An alternative way to do this could be select distinct PersonId and group join with persons:

var result = 
    from id in persons.Select(x => x.PersonId).Distinct()
    join p2 in persons on id equals p2.PersonId into gr // apply group join here
    select new 
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    };

Or the same with fluent API syntax:

var result = persons.Select(x => x.PersonId).Distinct()
    .GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
    {
        PersonId = id,
        Cars = gr.Select(x => x.Car).ToList(),
    });

GroupJoin produces a list of entries in the first list ( list of PersonId in our case), each with a group of joined entries in the second list (list of persons).

Create Word Document using PHP in Linux

real Word documents

If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative is:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

Make sure you don't use external stylesheets. Everything should be in the same file.

Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type header along does not constitute a real file format conversion.

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

Is Visual Studio Community a 30 day trial?

In my case, I already was signed in. So I had to sign out and sign in again.

In spanish Cerrar Sesion is sign out.

screenshot

Truncating long strings with CSS: feasible yet?

Another solution to the problem could be the following set of CSS rules:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.

My two cents. Hats off to the original technique by Justin Maxwell

C++: constructor initializer for arrays

Unfortunately there is no way to initialize array members till C++0x.

You could use a std::vector and push_back the Foo instances in the constructor body.

You could give Foo a default constructor (might be private and making Baz a friend).

You could use an array object that is copyable (boost or std::tr1) and initialize from a static array:

#include <boost/array.hpp>

struct Baz {

    boost::array<Foo, 3> foo;
    static boost::array<Foo, 3> initFoo;
    Baz() : foo(initFoo)
    {

    }
};

boost::array<Foo, 3> Baz::initFoo = { 4, 5, 6 };

Better way to convert file sizes in Python

There is hurry.filesize that will take the size in bytes and make a nice string out if it.

>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'

Or if you want 1K == 1000 (which is what most users assume):

>>> from hurry.filesize import size, si
>>> size(11000, system=si)
'11K'
>>> size(198283722, system=si)
'198M'

It has IEC support as well (but that wasn't documented):

>>> from hurry.filesize import size, iec
>>> size(11000, system=iec)
'10Ki'
>>> size(198283722, system=iec)
'189Mi'

Because it's written by the Awesome Martijn Faassen, the code is small, clear and extensible. Writing your own systems is dead easy.

Here is one:

mysystem = [
    (1024 ** 5, ' Megamanys'),
    (1024 ** 4, ' Lotses'),
    (1024 ** 3, ' Tons'), 
    (1024 ** 2, ' Heaps'), 
    (1024 ** 1, ' Bunches'),
    (1024 ** 0, ' Thingies'),
    ]

Used like so:

>>> from hurry.filesize import size
>>> size(11000, system=mysystem)
'10 Bunches'
>>> size(198283722, system=mysystem)
'189 Heaps'

What is the difference between server side cookie and client side cookie?

What is the difference between creating cookies on the server and on the client?

What you are referring to are the 2 ways in which cookies can be directed to be set on the client, which are:

  • By server
  • By client ( browser in most cases )

By server: The Set-cookie response header from the server directs the client to set a cookie on that particular domain. The implementation to actually create and store the cookie lies in the browser. For subsequent requests to the same domain, the browser automatically sets the Cookie request header for each request, thereby letting the server have some state to an otherwise stateless HTTP protocol. The Domain and Path cookie attributes are used by the browser to determine which cookies are to be sent to a server. The server only receives name=value pairs, and nothing more.

By Client: One can create a cookie on the browser using document.cookie = cookiename=cookievalue. However, if the server does not intend to respond to any random cookie a user creates, then such a cookie serves no purpose.

Are these called server side cookies and client side cookies?

Cookies always belong to the client. There is no such thing as server side cookie.

Is there a way to create cookies that can only be read on the server or on the client?

Since reading cookie values are upto the server and client, it depends if either one needs to read the cookie at all. On the client side, by setting the HttpOnly attribute of the cookie, it is possible to prevent scripts ( mostly Javscript ) from reading your cookies , thereby acting as a defence mechanism against Cookie theft through XSS, but sends the cookie to the intended server only.

Therefore, in most of the cases since cookies are used to bring 'state' ( memory of past user events ), creating cookies on client side does not add much value, unless one is aware of the cookies the server uses / responds to.

References: Wikipedia

bootstrap responsive table content wrapping

just simply use as below and it will word wrap any long text within a table . No need to anything else

<td style="word-wrap: break-word;min-width: 160px;max-width: 160px;">long long comments</td>

How can I interrupt a running code in R with a keyboard command?

Control-C works, although depending on what the process is doing it might not take right away.

If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.

How to use Monitor (DDMS) tool to debug application

I think that I got a solution for this. You don't have to start monitor but you can use DDMS instead almost like in Eclipse.

Start Android Studio-> pick breakpoint-> Run-> Debug-> Go to %sdk\tools in Terminal window and run ddms.bat to run DDMS without Monitor running (since it won't let you run ADB). You can now start profiling or debug step-by-step.

Hope this helps you.

See image here

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Ok, I had the same problem with STS on a mac and solved it by deleting all the files in repository folder and from the STS IDE click on the project and then Maven -> Update project. Give it a couple of minutes to download all the dependencies and the problem is solved.

Ship an application with a database

I'm using ORMLite and below code worked for me

public class DatabaseProvider extends OrmLiteSqliteOpenHelper {
    private static final String DatabaseName = "DatabaseName";
    private static final int DatabaseVersion = 1;
    private final Context ProvidedContext;

    public DatabaseProvider(Context context) {
        super(context, DatabaseName, null, DatabaseVersion);
        this.ProvidedContext= context;
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        boolean databaseCopied = preferences.getBoolean("DatabaseCopied", false);
        if (databaseCopied) {
            //Do Nothing
        } else {
            CopyDatabase();
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("DatabaseCopied", true);
            editor.commit();
        }
    }

    private String DatabasePath() {
        return "/data/data/" + ProvidedContext.getPackageName() + "/databases/";
    }

    private void CopyDatabase() {
        try {
            CopyDatabaseInternal();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File ExtractAssetsZip(String zipFileName) {
        InputStream inputStream;
        ZipInputStream zipInputStream;
        File tempFolder;
        do {
            tempFolder = null;
            tempFolder = new File(ProvidedContext.getCacheDir() + "/extracted-" + System.currentTimeMillis() + "/");
        } while (tempFolder.exists());

        tempFolder.mkdirs();

        try {
            String filename;
            inputStream = ProvidedContext.getAssets().open(zipFileName);
            zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
            ZipEntry zipEntry;
            byte[] buffer = new byte[1024];
            int count;

            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                filename = zipEntry.getName();
                if (zipEntry.isDirectory()) {
                    File fmd = new File(tempFolder.getAbsolutePath() + "/" + filename);
                    fmd.mkdirs();
                    continue;
                }

                FileOutputStream fileOutputStream = new FileOutputStream(tempFolder.getAbsolutePath() + "/" + filename);
                while ((count = zipInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, count);
                }

                fileOutputStream.close();
                zipInputStream.closeEntry();
            }

            zipInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return tempFolder;
    }

    private void CopyDatabaseInternal() throws IOException {

        File extractedPath = ExtractAssetsZip(DatabaseName + ".zip");
        String databaseFile = "";
        for (File innerFile : extractedPath.listFiles()) {
            databaseFile = innerFile.getAbsolutePath();
            break;
        }
        if (databaseFile == null || databaseFile.length() ==0 )
            throw new RuntimeException("databaseFile is empty");

        InputStream inputStream = new FileInputStream(databaseFile);

        String outFileName = DatabasePath() + DatabaseName;

        File destinationPath = new File(DatabasePath());
        if (!destinationPath.exists())
            destinationPath.mkdirs();

        File destinationFile = new File(outFileName);
        if (!destinationFile.exists())
            destinationFile.createNewFile();

        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        inputStream.close();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int fromVersion, int toVersion) {

    }
}

Please note, The code extracts database file from a zip file in assets

Clear and refresh jQuery Chosen dropdown list

If in case trigger("chosen:updated"); doesn't works for you. You can try $('#ddl').trigger('change'); as in my case its work for me.

Can I get JSON to load into an OrderedDict?

The normally used load command will work if you specify the object_pairs_hook parameter:

import json
from  collections import OrderedDict
with open('foo.json', 'r') as fp:
    metrics_types = json.load(fp, object_pairs_hook=OrderedDict)

Getting attribute using XPath

You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"

Twitter Bootstrap Form File Element Upload Button

Here is alternate trick, it's not the best solution but it just give you a choice

HTML code:

<button clss="btn btn-primary" id="btn_upload">Choose File</button>
<input id="fileupload" class="hide" type="file" name="files[]">

Javascript:

$("#btn_upload").click(function(e){
e.preventDefault();
$("#fileupload").trigger('click');
});

Iterating through a variable length array

Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {
    System.out.println(o);
}

jQuery find file extension (from string)

Since the extension will always be the string after a period in a complete/partial file name, just use the built in split function in js, and test the resultant extension for what you want it to do. If split returns only one piece / no pieces, it does not contain an extension.

PHP remove special character from string

See example.

/**
 * nv_get_plaintext()
 *
 * @param mixed $string
 * @return
 */
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
    // Get image tags
    if( $keep_image )
    {
        if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $textimg = '';
                if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
                {
                    $textimg = " " . $match[1][$key];
                }
                if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
                {
                    $textimg .= " " . $m_alt[1][0];
                }
                $string = str_replace( $_m, $textimg, $string );
            }
        }
    }

    // Get link tags
    if( $keep_link )
    {
        if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
            }
        }
    }

    $string = str_replace( ' ', ' ', strip_tags( $string ) );
    return preg_replace( '/[ ]+/', ' ', $string );
}

Using generic std::function objects with member functions in one class

If you need to store a member function without the class instance, you can do something like this:

class MyClass
{
public:
    void MemberFunc(int value)
    {
      //do something
    }
};

// Store member function binding
auto callable = std::mem_fn(&MyClass::MemberFunc);

// Call with late supplied 'this'
MyClass myInst;
callable(&myInst, 123);

What would the storage type look like without auto? Something like this:

std::_Mem_fn_wrap<void,void (__cdecl TestA::*)(int),TestA,int> callable

You can also pass this function storage to a standard function binding

std::function<void(int)> binding = std::bind(callable, &testA, std::placeholders::_1);
binding(123); // Call

Past and future notes: An older interface std::mem_func existed, but has since been deprecated. A proposal exists, post C++17, to make pointer to member functions callable. This would be most welcome.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work

Finding the next available id in MySQL

As I understand, if have id's: 1,2,4,5 it should return 3.

SELECT t1.id + 1
FROM theTable t1
WHERE NOT EXISTS (
    SELECT * 
    FROM theTable t2
    WHERE t2.id = t1.id + 1
)
LIMIT 1

Android. WebView and loadData

WebView.loadData() is not working properly at all. What I had to do was:

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
myWebView.loadData(header+myHtmlString, "text/html", "UTF-8");

I think in your case you should replace UTF-8 with latin1 or ISO-8859-1 both in header and in WebView.loadData().

And, to give a full answer, here is the official list of encodings: http://www.iana.org/assignments/character-sets

I update my answer to be more inclusive:

To use WebView.loadData() with non latin1 encodings you have to encode html content. Previous example was not correctly working in Android 4+, so I have modified it to look as follows:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
    String base64 = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
    myWebView.loadData(base64, "text/html; charset=utf-8", "base64");
} else {
    String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
    myWebView.loadData(header + htmlString, "text/html; charset=UTF-8", null);

}

But later I have switched to WebView.loadDataWithBaseURL() and the code became very clean and not depending on Android version:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
myWebView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);

For some reason these functions have completely different implementation.

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Bootstrap 3 Horizontal and Vertical Divider

Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:

HTML:

<div class="bottom">
    <div class="box-content right">Rich Media Ad Production</div>
    <div class="box-content right">Web Design & Development</div>
    <div class="box-content right">Mobile Apps Development</div>
    <div class="box-content">Creative Design</div>
</div>
<div>
    <div class="box-content right">Web Analytics</div>
    <div class="box-content right">Search Engine Marketing</div>
    <div class="box-content right">Social Media</div>
    <div class="box-content">Quality Assurance</div>
</div>

CSS:

.box-content {
    display: inline-block;
    width: 200px;
    padding: 10px;
}

.bottom {
    border-bottom: 1px solid #ccc;
}

.right {
    border-right: 1px solid #ccc;
}

Here is the working Fiddle.


UPDATE

If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.

HTML:

<div class="row">
    <div class="col-xs-3">Rich Media Ad Production</div>
    <div class="col-xs-3">Web Design & Development</div>
    <div class="col-xs-3">Mobile Apps Development</div>
    <div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
    <div class="col-xs-3">Web Analytics</div>
    <div class="col-xs-3">Search Engine Marketing</div>
    <div class="col-xs-3">Social Media</div>
    <div class="col-xs-3">Quality Assurance</div>
</div>

CSS:

.row:not(:last-child) {
    border-bottom: 1px solid #ccc;
}

.col-xs-3:not(:last-child) {
    border-right: 1px solid #ccc;
}

Here is another working Fiddle.

Note:

Note that you may also use the <hr> element to insert a horizontal divider in Bootstrap as well if you'd like.

SyntaxError: missing ) after argument list

SyntaxError: missing ) after argument list.

the issue also may occur if you pass string directly without a single or double quote.

$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "'  onclick=\"(canLaunch(' + v.LibraryItemName +  '))\">View &raquo;</a></div></div>").

so always keep the habit to pass in a quote like

 onclick=\"(canLaunch(\'' + v.LibraryItemName  + '\'))"\

MySQL SELECT only not null values

You should use IS NOT NULL. (The comparison operators = and <> both give UNKNOWN with NULL on either side of the expression.)

SELECT * 
FROM table 
WHERE YourColumn IS NOT NULL;

Just for completeness I'll mention that in MySQL you can also negate the null safe equality operator but this is not standard SQL.

SELECT *
FROM table 
WHERE NOT (YourColumn <=> NULL);

Edited to reflect comments. It sounds like your table may not be in first normal form in which case changing the structure may make your task easier. A couple of other ways of doing it though...

SELECT val1 AS val
FROM  your_table
WHERE val1 IS NOT NULL
UNION ALL
SELECT val2 
FROM  your_table
WHERE val2 IS NOT NULL
/*And so on for all your columns*/

The disadvantage of the above is that it scans the table multiple times once for each column. That may possibly be avoided by the below but I haven't tested this in MySQL.

SELECT CASE idx
         WHEN 1 THEN val1
         WHEN 2 THEN val2
       END AS val
FROM   your_table
        /*CROSS JOIN*/
       JOIN (SELECT 1 AS idx
                   UNION ALL
                   SELECT 2) t
HAVING val IS NOT NULL  /*Can reference alias in Having in MySQL*/

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How to hide 'Back' button on navigation bar on iPhone?

It wasn't working for me in all cases when I set

self.navigationItem.hidesBackButton = YES;

in viewWillAppear or ViewDidLoad, but worked perfectly when I set it in init of the viewController.

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

How to detect a remote side socket close?

You can also check for socket output stream error while writing to client socket.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}

Android ListView with Checkbox and all clickable

Set the listview adapter to "simple_list_item_multiple_choice"

ArrayAdapter<String> adapter;

List<String> values; // put values in this

//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice, 
values);
setListAdapter(adapter);    

find if an integer exists in a list of integers

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7}); // 1

List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2

var i = 5;
var x = ints.Contains(i);   // return true or false

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

php execute a background process

PHP scripting is not like other desktop application developing language. In desktop application languages we can set daemon threads to run a background process but in PHP a process is occuring when user request for a page. However It is possible to set a background job using server's cron job functionality which php script runs.

Display / print all rows of a tibble (tbl_df)

You can use as.data.frame or print.data.frame.

If you want this to be the default, you can change the value of the dplyr.print_max option.

options(dplyr.print_max = 1e9)

How do you hide the Address bar in Google Chrome for Chrome Apps?

Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.

Sql server - log is full due to ACTIVE_TRANSACTION

Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:

* Issue a CHECKPOINT command to free up log space in the log file.

* Check the available log space with DBCC SQLPERF('logspace'). If only a small 
  percentage of your log file is actually been used, you can try a DBCC SHRINKFILE 
  command. This can however possibly introduce corruption in your database. 

* If you have another drive with space available you can try to add a file there in 
  order to get enough space to attempt to resolve the issue.

Hope this will help you in finding your solution.

Symfony2 : How to get form validation errors after binding the request to the form

For my flash messages I was happy with $form->getErrorsAsString()

Edit (from Benji_X80): For SF3 use $form->getErrors(true, false);

How to save DataFrame directly to Hive?

I don't see df.write.saveAsTable(...) deprecated in Spark 2.0 documentation. It has worked for us on Amazon EMR. We were perfectly able to read data from S3 into a dataframe, process it, create a table from the result and read it with MicroStrategy. Vinays answer has also worked though.

SonarQube Exclude a directory

Another configuration option is adding a maven properties sonar.exclusions. Below is a sample pom file with exclusions of static jquery directory and static pdf viewer directory.

<project >
<modelVersion>4.0.0</modelVersion>
<artifactId>my Artifact</artifactId>
<!-- Enviroment variables can be referenced as such: ${env.PATH} -->
<packaging>war</packaging>
<url>http://maven.apache.org</url>

<properties>

    <junit.version>4.9</junit.version>
    <mockito.version>1.9.5</mockito.version>
    <jackson.version>1.9.7</jackson.version>
    <powermock.version>1.5</powermock.version>

    <!--Exclude the files Here-->
    <sonar.exclusions>src/main/webapp/static/jquery_ui/*,src/main/webapp/static/pdf-viewer/*,src/main/webapp/static/pdf-viewer/**,src/main/webapp/static/pdf-viewer/**/*</sonar.exclusions>
</properties>

Permanently hide Navigation Bar in an activity

You can hide navigation bar, just call this method on your onCreate(),

 public void FullScreencall() {
    if(Build.VERSION.SDK_INT < 19){ 
        View v = this.getWindow().getDecorView();
        v.setSystemUiVisibility(View.GONE);
    } else {
            //for higher api versions.    
        View decorView = getWindow().getDecorView(); 
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }
}

This will hide whole nagiation panel.hope it helps you

PHP random string generator

$randstring in the function scope is not the same as the scope where you call it. You have to assign the return value to a variable.

$randstring = RandomString();
echo $randstring;

Or just directly echo the return value:

echo RandomString();

Also, in your function you have a little mistake. Within the for loop, you need to use .= so each character gets appended to the string. By using = you are overwriting it with each new character instead of appending.

$randstring .= $characters[rand(0, strlen($characters))];

Accessing nested JavaScript objects and arrays by string path

Building off of Alnitak's answer:

if(!Object.prototype.byString){
  //NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
  var _o = o || this;
      s = s.replace(/\[(\w+)\]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
      s = s.replace(/^\./, ''); // STRIP A LEADING DOT
      var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
      for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
          var k = a[i];
          if (k in _o) {//LOOP THROUGH OBJECT KEYS
              if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
                if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
                  if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
                    _o[k] = v;
                  }
                }
                _o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
              }
          } else {
              return;
          }
      }
      return _o;
  };

}

This allows you to set a value as well!

I've created an npm package and github with this as well

Connection to SQL Server Works Sometimes

Try a simple SQL Server restart first before doing anything drastic. Might fix it. It did for me

How to convert hex to rgb using Java?

A hex color code is #RRGGBB

RR, GG, BB are hex values ranging from 0-255

Let's call RR XY where X and Y are hex character 0-9A-F, A=10, F=15

The decimal value is X*16+Y

If RR = B7, the decimal for B is 11, so value is 11*16 + 7 = 183

public int[] getRGB(String rgb){
    int[] ret = new int[3];
    for(int i=0; i<3; i++){
        ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
    }
    return ret;
}

public int hexToInt(char a, char b){
    int x = a < 65 ? a-48 : a-55;
    int y = b < 65 ? b-48 : b-55;
    return x*16+y;
}

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

How to configure WAMP (localhost) to send email using Gmail?

If you open the php.ini file in wamp, you will find these two lines:

smtp_server
smtp_port

Add the server and port number for your host (you may need to contact them for details)

The following two lines don't exist:

auth_username
auth_password

So you will need to add them to be able to send mail from a server that requires authentication. So an example may be:

smtp_server = mail.example.com
smtp_port = 26
auth_username = [email protected]
auth_password = example_password

how to always round up to the next integer

Check by using mod - if there is a remainder, simply increment the value by one.

SQL Not Like Statement not working

Just come across this, the answer is simple, use ISNULL. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:

WHERE wpp.comment NOT LIKE '%CORE%'

So, you have temporarily substitute a value in the null (empty) records by using the ISNULL command, eg

WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'

This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg

WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

How can query string parameters be forwarded through a proxy_pass with nginx?

To redirect Without Query String add below lines in Server block under listen port line:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}

With Query String:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}

Linq style "For Each"

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Select dropdown with fixed width cutting off content in IE

A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):

<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
  <select onchange='jump();'>
    <!-- '&#9660;(?)' produces a fake dropdown indicator -->
    <option value=''>Jump to ... &#9660;</option>
    <option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
    ...
  </select>
</div>

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I wanted to change a color to a specific brightness level - no matter what brightness the color was before - here's a simple JS function that seems to work well, although I'm sure it could be shorter

function setLightPercentage(col: any, p: number) {
    const R = parseInt(col.substring(1, 3), 16);
    const G = parseInt(col.substring(3, 5), 16);
    const B = parseInt(col.substring(5, 7), 16);
    const curr_total_dark = (255 * 3) - (R + G + B);

    // calculate how much of the current darkness comes from the different channels
    const RR = ((255 - R) / curr_total_dark);
    const GR = ((255 - G) / curr_total_dark);
    const BR = ((255 - B) / curr_total_dark);

    // calculate how much darkness there should be in the new color
    const new_total_dark = ((255 - 255 * (p / 100)) * 3);

    // make the new channels contain the same % of available dark as the old ones did
    const NR = 255 - Math.round(RR * new_total_dark);
    const NG = 255 - Math.round(GR * new_total_dark);
    const NB = 255 - Math.round(BR * new_total_dark);

    const RO = ((NR.toString(16).length === 1) ? "0" + NR.toString(16) : NR.toString(16));
    const GO = ((NG.toString(16).length === 1) ? "0" + NG.toString(16) : NG.toString(16));
    const BO = ((NB.toString(16).length === 1) ? "0" + NB.toString(16) : NB.toString(16));

    return "#" + RO + GO + BO;}

Java: how to import a jar file from command line

If you're running a jar file with java -jar, the -classpath argument is ignored. You need to set the classpath in the manifest file of your jar, like so:

Class-Path: jar1-name jar2-name directory-name/jar3-name

See the Java tutorials: Adding Classes to the JAR File's Classpath.

Edit: I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the ':' after "Class-Path" like you showed, it would not work.

Sorting a list with stream.sorted() in Java

This might help for people ending up here searching how to sort list alphabetically.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SortService {
    public static void main(String[] args) {
        List<TestData> test = new ArrayList<>();
        test.add(prepareTestData("Asmin",1));
        test.add(prepareTestData("saurav",4));
        test.add(prepareTestData("asmin",2));
        test.add(prepareTestData("Saurav",3));

        test.forEach(data-> System.out.println(data));
        /** Output
         *  TestData(name=Asmin, id=1)
         *  TestData(name=saurav, id=4)
         *  TestData(name=asmin, id=2)
         *  TestData(name=Saurav, id=3)
         */

        test.sort(Comparator.comparing(TestData::getName,String::compareToIgnoreCase));
        test.forEach(data-> System.out.println(data));
        /**Sorted Output
         * TestData(name=Asmin, id=1)
         * TestData(name=asmin, id=2)
         * TestData(name=saurav, id=4)
         * TestData(name=Saurav, id=3)
         */
    }
    private static TestData prepareTestData(String name, int id){
        TestData testData= new TestData();
        testData.setId(id);
        testData.setName(name);
        return testData;
    }
}

@Getter
@Setter
@ToString
class TestData{
    private String name;
    private int id;
}

Test method is inconclusive: Test wasn't run. Error?

It was a Resharper issue. In Resharper options->Tools->MSTEST, I unchecked the Use Legacy Runner and now it works.

SQL Server 2008: TOP 10 and distinct together

This is the right answer and you can find 3 heights value from table

SELECT TOP(1)  T.id FROM (SELECT DISTINCT TOP(3) st.id  FROM Table1 AS t1 , Table2 AS t2 WHERE t1.id=t2.id ORDER BY (t2.id) DESC ) T ORDER BY(T.id) ASC

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

Download file from web in Python 3

I use requests package whenever I want something related to HTTP requests because its API is very easy to start with:

first, install requests

$ pip install requests

then the code:

from requests import get  # to make GET request


def download(url, file_name):
    # open in binary mode
    with open(file_name, "wb") as file:
        # get request
        response = get(url)
        # write to file
        file.write(response.content)

Batch files: How to read a file?

Under NT-style cmd.exe, you can loop through the lines of a text file with

FOR /F %i IN (file.txt) DO @echo %i

Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Emulate Samsung Galaxy Tab

You can't.

"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."

The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.

You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.

How to click a href link using Selenium

Seems like the a tag is hidden. Remember Selenium is not able to interact with hidden element. Javascript is the only option in that case.

By css = By.cssSelector("a[href='/docs/configuration']");
WebElement element = driver.findElement(css);
((JavascriptExecutor)driver).executeScript("arguments[0].click();" , element);

JavaScript, Node.js: is Array.forEach asynchronous?

There is a package on npm for easy asynchronous for each loops.

var forEachAsync = require('futures').forEachAsync;

// waits for one request to finish before beginning the next 
forEachAsync(['dogs', 'cats', 'octocats'], function (next, element, index, array) {
  getPics(element, next);
  // then after all of the elements have been handled 
  // the final callback fires to let you know it's all done 
  }).then(function () {
    console.log('All requests have finished');
});

Also another variation forAllAsync

Rails: Adding an index after adding column

You can use this, just think Job is the name of the model to which you are adding index cader_id:

class AddCaderIdToJob < ActiveRecord::Migration[5.2]
  def change
    change_table :jobs do |t|
      t.integer :cader_id
      t.index :cader_id
    end
  end
end

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

WPF Data Binding and Validation Rules Best Practices

From MS's Patterns & Practices documentation:

Data Validation and Error Reporting

Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.

Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.

However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.

The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.

How do I disable and re-enable a button in with javascript?

true and false are not meant to be strings in this context.

You want the literal true and false Boolean values.

startButton.disabled = true;

startButton.disabled = false;

The reason it sort of works (disables the element) is because a non empty string is truthy. So assigning 'false' to the disabled property has the same effect of setting it to true.

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

For line chart, I use the following codes.

First create custom style

.boxx{
    position: relative;
    width: 20px;
    height: 20px;
    border-radius: 3px;
}

Then add this on your line options

var lineOptions = {
            legendTemplate : '<table>'
                            +'<% for (var i=0; i<datasets.length; i++) { %>'
                            +'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
                            +'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
                            +'<% } %>'
                            +'</table>',
            multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();

Don't forget to add

<div id="legendDiv"></div>

on your html where do you want to place your legend. That's it!

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

How to kill an application with all its activities?

You are correct: calling finish() will only exit the current activity, not the entire application. however, there is a workaround for this:

Every time you start an Activity, start it using startActivityForResult(...). When you want to close the entire app, you can do something like this:

setResult(RESULT_CLOSE_ALL);
finish();

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

This will cause a cascade effect closing all activities.

Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

jQuery/JavaScript: accessing contents of an iframe

If the <iframe> is from the same domain, the elements are easily accessible as

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Reference

Powershell script to check if service is started, if not then start it

Combining Alaa Akoum and Nick Eagle's solutions allowed me to loop through a series of windows services and stop them if they're running.

# stop the following Windows services in the specified order:
[Array] $Services = 'Service1','Service2','Service3','Service4','Service5';

# loop through each service, if its running, stop it
foreach($ServiceName in $Services)
{
    $arrService = Get-Service -Name $ServiceName
    write-host $ServiceName
    while ($arrService.Status -eq 'Running')
    {
        Stop-Service $ServiceName
        write-host $arrService.status
        write-host 'Service stopping'
        Start-Sleep -seconds 60
        $arrService.Refresh()
        if ($arrService.Status -eq 'Stopped')
            {
              Write-Host 'Service is now Stopped'
            }
     }
 }

The same can be done to start a series of service if they are not running:

# start the following Windows services in the specified order:
[Array] $Services = 'Service1','Service2','Service3','Service4','Service5';

# loop through each service, if its not running, start it
foreach($ServiceName in $Services)
{
    $arrService = Get-Service -Name $ServiceName
    write-host $ServiceName
    while ($arrService.Status -ne 'Running')
    {
        Start-Service $ServiceName
        write-host $arrService.status
        write-host 'Service starting'
        Start-Sleep -seconds 60
        $arrService.Refresh()
        if ($arrService.Status -eq 'Running')
        {
          Write-Host 'Service is now Running'
        }
    }
}

Determining if Swift dictionary contains key and obtaining any of its values

My solution for a cache implementation that stores optional NSAttributedString:

public static var attributedMessageTextCache    = [String: NSAttributedString?]()

    if attributedMessageTextCache.index(forKey: "key") != nil
    {
        if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
        {
            return attributedMessageText
        }
        return nil
    }

    TextChatCache.attributedMessageTextCache["key"] = .some(.none)
    return nil

Python: IndexError: list index out of range

Here is your code. I'm assuming you're using python 3 based on the your use of print() and input():

import random

def main():
    #random.seed() --> don't need random.seed()

    #Prompts the user to enter the number of tickets they wish to play.

    #python 3 version:
    tickets = int(input("How many lottery tickets do you want?\n"))

    #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
    winning_numbers = []
    winnings = 0

    #Generates the winning lotto numbers.
    for i in range(tickets * 5):
        #del winning_numbers[:] what is this line for?
        randNum = random.randint(1,30)
        while randNum in winning_numbers:    
            randNum = random.randint(1,30)
        winning_numbers.append(randNum)

    print(winning_numbers)
    guess = getguess(tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    winningRanks = [0, 0, 10, 500, 20000, 1000000]

    winnings = sum(winningRanks[:nummatches + 1])

    print("You won a total of",winnings,"with",tickets,"tickets.\n")


#Gets the guess from the user.
def getguess(tickets):
    guess = []
    for i in range(tickets):
        bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
        guess.extend(bubble)
        print(bubble)
    return guess

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
    match = 0
    for i in range(5):
        if guess[i] == winning_numbers[i]:
            match += 1
    return match

main()

how to convert string into time format and add two hours

This will give you the time you want (eg: 21:31 PM)

//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime())); 

How to position background image in bottom right corner? (CSS)

Voilà:

body {
   background-color: #000; /*Default bg, similar to the background's base color*/
   background-image: url("bg.png");
   background-position: right bottom; /*Positioning*/
   background-repeat: no-repeat; /*Prevent showing multiple background images*/
}

The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position

Iterating through a list in reverse order in java

You could use the concrete class LinkedList instead of the general interface List. Then you have a descendingIterator for iterating with the reverse direction.

LinkedList<String > linkedList;
for( Iterator<String > it = linkedList.descendingIterator(); it.hasNext(); ) {
    String text = it.next();
}

Don't know why there is no descendingIterator with ArrayList...

CSS @font-face not working in ie

From http://readableweb.com/mo-bulletproofer-font-face-css-syntax/

Now that web fonts are supported in Firefox 3.5 and 3.6, Internet Explorer, Safari, Opera 10.5, and Chrome, web authors face new questions: How do these implementations differ? What CSS techniques will accommodate all? Firefox developer John Daggett recently posted a little roundup about these issues and the workarounds that are being explored. In response to that post, and in response to, particularly, Paul Irish’s work, I came up with the following @font-face CSS syntax. It’s been tested in all of the above named browsers including IE 8, 7, and 6. So far, so good. The following is a test page that declares the free Droid font as a complete font-family with Regular, Italic, Bold, and Bold Italic. View source for details. Alert: Be aware that Readable Web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. It has it’s own web site and, in addition to the utility itself, the download package contains helpful documentation, a test font, and an EOT test page. It’s called EOTFAST If you’re working with @font-face, it’s a must-have.

Here’s The Mo’ Bulletproofer Code:

@font-face{ /* for IE */
    font-family:FishyFont;
    src:url(fishy.eot);
}
@font-face { /* for non-IE */
    font-family:FishyFont;
    src:url(http://:/) format("No-IE-404"),url(fishy.ttf) format("truetype");
}

Table 'mysql.user' doesn't exist:ERROR

You can run the following query to check for the existance of the user table.

SELECT * FROM information_schema.TABLES
WHERE TABLE_NAME LIKE '%user%'

See if you can find a row with the following values in

mysql   user    BASE TABLE  MyISAM  

If you cant find this table look at the following link to rebuild the database How to recover/recreate mysql's default 'mysql' database

R legend placement in a plot

You have to add the size of the legend box to the ylim range

#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)

#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)

#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))

enter image description here

How to import image (.svg, .png ) in a React Component

Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through "create-react-app")
let image = document.createElement("img"); image.src = require('../assets/police.png');

How to create a unique index on a NULL column?

Using SQL Server 2008, you can create a filtered index: http://msdn.microsoft.com/en-us/library/cc280372.aspx. (I see Simon added this as a comment, but thought it deserved its own answer as the comment is easily missed.)

Another option is a trigger to check uniqueness, but this could affect performance.

Simulating Button click in javascript

Since you are using jQuery you can use this onClick handler which calls click:

$("#datepicker").click()

This is the same as $("#datepicker").trigger("click").

For a jQuery-free version check out this answer on SO.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

Assigning default values to shell variables with a single command in bash

FWIW, you can provide an error message like so:

USERNAME=${1:?"Specify a username"}

This displays a message like this and exits with code 1:

./myscript.sh
./myscript.sh: line 2: 1: Specify a username

A more complete example of everything:

#!/bin/bash
ACTION=${1:?"Specify 'action' as argv[1]"}
DIRNAME=${2:-$PWD}
OUTPUT_DIR=${3:-${HOMEDIR:-"/tmp"}}

echo "$ACTION"
echo "$DIRNAME"
echo "$OUTPUT_DIR"

Output:

$ ./script.sh foo
foo
/path/to/pwd
/tmp

$ export HOMEDIR=/home/myuser
$ ./script.sh foo
foo
/path/to/pwd
/home/myuser
  • $ACTION takes the value of the first argument, and exits if empty
  • $DIRNAME is the 2nd argument, and defaults to the current directory
  • $OUTPUT_DIR is the 3rd argument, or $HOMEDIR (if defined), else, /tmp. This works on OS X, but I'm not positive that it's portable.

Correct way to find max in an Array in Swift

Swift 3.0

You can try this code programmatically.

func getSmallAndGreatestNumber() -> Void {

    let numbers = [145, 206, 116, 809, 540, 176]
    var i = 0
    var largest = numbers[0]
    var small = numbers[0]
    while i < numbers.count{

        if (numbers[i] > largest) {
            largest = numbers[i]
        }
        if (numbers[i] < small) {
            small = numbers[i]
        }
        i = i + 1
    }
    print("Maximum Number ====================\(largest)")// 809
    print("Minimum Number ====================\(small)")// 116
}

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

How to set initial value and auto increment in MySQL?

You could also set it in the create table statement.

`CREATE TABLE(...) AUTO_INCREMENT=1000`

Alternative to iFrames with HTML5

You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

function loadPage(){
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
xmlhttp.send();
}

If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

How do I make a textbox that only accepts numbers?

In button click you can check text of textbox by for loop:

char[] c = txtGetCustomerId.Text.ToCharArray();
bool IsDigi = true;

for (int i = 0; i < c.Length; i++)
     {
       if (c[i] < '0' || c[i] > '9')
      { IsDigi = false; }
     }
 if (IsDigi)
    { 
     // do something
    }

SoapUI "failed to load url" error when loading WSDL

I got this error when trying to load a WebService implemented in MS Dynamics AX. Because I was connecting via VPN to my network, something went wrong with IPv6 settings. After Googling, I found the solution here: http://support.microsoft.com/kb/929852

A valid provisioning profile for this executable was not found for debug mode

Finally i could solve the problem. One of my colleagues has revoked the developer certificate at iOS Provisioning Portal for his test apps. for fixing; i removed the existing developer certificate at my keychain, requested a new certificate with the existing private key, revoked the certificate from provisioning portal and submitted the newly requested certificate.then i downloaded and installed it.

now i can debug my app on my device :)

How to Clone Objects

In my opinion, the best way to do this is by implementing your own Clone() method as shown below.

class Person
{
    public string head;
    public string feet;

    // Downside: It has to be manually implemented for every class
    public Person Clone()
    {
        return new Person() { head = this.head, feet = this.feet };
    }
}

class Program
{
    public static void Main(string[] args)
    {
        Person a = new Person() { head = "bigAF", feet = "smol" };
        Person b = a.Clone();

        b.head = "notEvenThatBigTBH";

        Console.WriteLine($"{a.head}, {a.feet}");
        Console.WriteLine($"{b.head}, {b.feet}");
    }
}

Output:

bigAf, smol

notEvenThatBigTBH, smol

b is totally independent to a, due to it not being a reference, but a clone.

Hope I could help!

How to use ng-repeat for dictionaries in AngularJs?

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.

Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:

// Initialize users as a new hash.
var users = {};
users["182982"] = "...";

To retrieve all the values from a hash, you need to iterate over it using a for loop:

function getValues (hash) {
    var values = [];
    for (var key in hash) {

        // Ensure that the `key` is actually a member of the hash and not
        // a member of the `prototype`.
        // see: http://javascript.crockford.com/code.html#for%20statement
        if (hash.hasOwnProperty(key)) {
            values.push(key);
        }
    }
    return values;
};

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

These are class stereotypes used in analysis.

  • boundary classes are ones at the boundary of the system - the classes that you or other systems interact with

  • entity classes classes are your typical business entities like "person" and "bank account"

  • control classes implement some business logic or other

Delete element in a slice

There are two options:

A: You care about retaining array order:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

B: You don't care about retaining order (this is probably faster):

a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1]   // Chop off the last one.

See the link to see implications re memory leaks if your array is of pointers.

https://github.com/golang/go/wiki/SliceTricks

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

How to Set Active Tab in jQuery Ui

If you want to set the active tab by ID instead of index, you can also use the following:

$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });

How to make a class property?

I think you may be able to do this with the metaclass. Since the metaclass can be like a class for the class (if that makes sense). I know you can assign a __call__() method to the metaclass to override calling the class, MyClass(). I wonder if using the property decorator on the metaclass operates similarly. (I haven't tried this before, but now I'm curious...)

[update:]

Wow, it does work:

class MetaClass(type):    
    def getfoo(self):
        return self._foo
    foo = property(getfoo)

    @property
    def bar(self):
        return self._bar

class MyClass(object):
    __metaclass__ = MetaClass
    _foo = 'abc'
    _bar = 'def'

print MyClass.foo
print MyClass.bar

Note: This is in Python 2.7. Python 3+ uses a different technique to declare a metaclass. Use: class MyClass(metaclass=MetaClass):, remove __metaclass__, and the rest is the same.

How to identify server IP address in PHP

for example:

$_SERVER['SERVER_ADDR']

when your on IIS, try:

$_SERVER['LOCAL_ADDR']