Programs & Examples On #Parse error

An error of language resulting from code that does not conform to the syntax of the programming language.

Parse error: Syntax error, unexpected end of file in my PHP code

You can't divide IF/ELSE instructions into two separate blocks. If you need HTML code to be printed, use echo.

<html>
    <?php
        function login()
        {
            // Login function code
        }
        if (login())
        {
            echo "<h2>Welcome Administrator</h2>
            <a href=\"upload.php\">Upload Files</a>
            <br />
            <a href=\"points.php\">Edit Points Tally</a>";
        }
        else
        {
            echo "Incorrect login details. Please login";
        }
    ?>
    Some more HTML code
</html>

JavaScript by reference vs. by value

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

But, I think you already read it on SO; here you have the documentation you want:

http://snook.ca/archives/javascript/javascript_pass

Create a hidden field in JavaScript

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

CustomizePPT.setHiddenFields( 
    { 
        "hidden" : 
        {
            'fieldinFORM' : 'thisdata201' , 
            'fieldinFORM2' : 'this3' //multiple hidden fields
            .
            .
            .
            .
            .
            'nNoOfFields' : 'nthData'
        },
    "form" : 
    {
        "status" : "true",
        "formID" : "form3"
    } 
} );

_x000D_
_x000D_
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
    var request = [];_x000D_
 var container = '';_x000D_
 console.log(arguments);_x000D_
 request = arguments[0].hidden;_x000D_
    console.log(arguments[0].hasOwnProperty('form'));_x000D_
 if(arguments[0].hasOwnProperty('form') == true)_x000D_
 {_x000D_
  if(arguments[0].form.status == 'true'){_x000D_
   var parent = document.getElementById("container");_x000D_
   container = document.createElement('form');_x000D_
   parent.appendChild(container);_x000D_
   Object.assign(container, {'id':arguments[0].form.formID});_x000D_
  }_x000D_
 }_x000D_
 else{_x000D_
   container = document.getElementById("container");_x000D_
 }_x000D_
 _x000D_
 //var container = document.getElementById("container");_x000D_
 Object.keys(request).forEach(function(elem)_x000D_
 {_x000D_
  if($('#'+elem).length <= 0){_x000D_
   console.log("Hidden Field created");_x000D_
   var input = document.createElement('input');_x000D_
   Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
   container.appendChild(input);_x000D_
  }else{_x000D_
   console.log("Hidden Field Exists and value is below" );_x000D_
   $('#'+elem).val(request[elem]);_x000D_
  }_x000D_
 });_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing parameters to a Bash function

Another way to pass named parameters to Bash... is passing by reference. This is supported as of Bash 4.0

#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
  echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}

declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );

myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];

An alternative syntax for Bash 4.3 is using a nameref.

Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version, so I won't recommend it quite yet.

error: This is probably not a problem with npm. There is likely additional logging output above

Finally, I found a solution to this problem without reinstalling npm and I'm posting it because in future it will help someone, Most of the time this error occurs javascript heap went out of the memory. As the error says itself this is not a problem with npm. Only we have to do is

instead of,

npm  run build -prod

extend the javascript memory by following,

node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod

How to serve .html files with Spring

I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me

Step-1 in server's web.xml comment these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Step-3 create a static controller class

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Step-4 in the Spring configuration file change the suffix to .htm .htm

Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server

localhost:8080/.../landingPage

How to import RecyclerView for Android L-preview

I used this one is working for me. One thing needs to be consider that what appcompat version you are using. I am using appcompat-v7:26.+ so this is working for me.

implementation 'com.android.support:recyclerview-v7:26.+'

How to get Linux console window width in Python

import os
rows, columns = os.popen('stty size', 'r').read().split()

uses the 'stty size' command which according to a thread on the python mailing list is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.

Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).

(See answer by @GringoSuave on how to do this on python 3.3+)

How do you automatically set the focus to a textbox when a web page loads?

Use the below code. For me it is working

jQuery("[id$='hfSpecialty_ids']").focus()

What is a "slug" in Django?

It is a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL.

Count number of 1's in binary representation

Ruby implementation

def find_consecutive_1(n)
  num = n.to_s(2)
  arr = num.split("")
  counter = 0
  max = 0
  arr.each do |x|
      if x.to_i==1
          counter +=1
      else
          max = counter if counter > max
          counter = 0 
      end
      max = counter if counter > max  
  end
  max
end

puts find_consecutive_1(439)

What does "\r" do in the following script?

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.

Make Bootstrap's Carousel both center AND responsive?

I assume you have different sized images. I tested this myself, and it works as you describe (always centered, images widths appropriately)

/*CSS*/
div.c-wrapper{
    width: 80%; /* for example */
    margin: auto;
}

.carousel-inner > .item > img, 
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}

<!--html-->
<div class="c-wrapper">
<div id="carousel-example-generic" class="carousel slide">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="item active">
      <img src="http://placehold.it/600x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
        <div class="item">
      <img src="http://placehold.it/500x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/700x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
  </div>

  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="icon-prev"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="icon-next"></span>
  </a>
</div>
</div>

This creates a "jump" due to variable heights... to solve that, try something like this: Select the tallest image of a list

Or use media-query to set your own fixed height.

Convert JSON string to dict using Python

use simplejson or cjson for speedups

import simplejson as json

json.loads(obj)

or 

cjson.decode(obj)

Javascript how to split newline

you don't need to pass any regular expression there. this works just fine..

 (function($) {
      $(document).ready(function() {
        $('#data').click(function(e) {
          e.preventDefault();
          $.each($("#keywords").val().split("\n"), function(e, element) {
            alert(element);
          });
        });
      });
    })(jQuery);

How to prevent a dialog from closing when a button is clicked

I found an other way to achieve this...

Step 1: Put the dialog opening code in a method (Or Function in C).
Step 2: Inside the onClick of yes (Your positiveButton), call this dialog opening method recursively if your condition is not satisfied (By using if...else...). Like below :

private void openSave() {
   
    final AlertDialog.Builder builder=new AlertDialog.Builder(Phase2Activity.this);

    builder.setTitle("SAVE")
            .setIcon(R.drawable.ic_save_icon)
            .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    
                        if((!editText.getText().toString().isEmpty() && !editText1.getText().toString().isEmpty())){

                                createPdf(fileName,title,file);
                            
                        }else {
                            openSave();
                            Toast.makeText(Phase2Activity.this, "Some fields are empty.", Toast.LENGTH_SHORT).show();
                        }

                    
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               dialogInterface.dismiss();
            }
        })
            .setCancelable(false)
            .create()
            .show();

}

But this will make the dialog disappear just for a moment and it will appear again instantly. :)

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

Make columns of equal width in <table>

I think that this will do the trick:

table{
    table-layout: fixed;
    width: 300px;
}

Change Name of Import in Java, or import two classes with the same name

Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.

If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7

Character reading from file in Python

Not sure about the (errors="ignore") option but it seems to work for files with strange Unicode characters.

with open(fName, "rb") as fData:
    lines = fData.read().splitlines()
    lines = [line.decode("utf-8", errors="ignore") for line in lines]

How do you redirect HTTPS to HTTP?

For those that are using a .conf file.

<VirtualHost *:443>
    ServerName domain.com
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/domain.crt
    SSLCertificateKeyFile /etc/apache2/ssl/domain.key
    SSLCACertificateFile /etc/apache2/ssl/domain.crt

</VirtualHost>

How to disable keypad popup when on edittext?

Only thing you need to do is that add android:focusableInTouchMode="false" to the EditText in xml and thats all.(If someone still needs to know how to do that with the easy way)

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

About "*.d.ts" in TypeScript

Like @takeshin said .d stands for declaration file for typescript (.ts).

Few points to be clarified before proceeding to answer this post -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

For ex -

If you install javascript library -

npm install --save mylib

and try importing it in typescript code -

import * from "mylib";

you will get error.

"Cannot find module 'mylib'."

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

Now when you try -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

Pushing empty commits to remote

As long as you clearly reference the other commit from the empty commit it should be fine. Something like:

Commit message errata for [commit sha1]

[new commit message]

As others have pointed out, this is often preferable to force pushing a corrected commit.

Property getters and setters

Try using this:

var x:Int!

var xTimesTwo:Int {
    get {
        return x * 2
    }
    set {
        x = newValue / 2
    }
}

This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int, in mine, my x variable is like this: var x: Int!, so all I did was make it an optional type.

REST API error return good practices

Please stick to the semantics of protocol. Use 2xx for successful responses and 4xx , 5xx for error responses - be it your business exceptions or other. Had using 2xx for any response been the intended use case in the protocol, they would not have other status codes in the first place.

How to enable PHP's openssl extension to install Composer?

After editting the "right" files (all php.ini's). i had still the issue. My solution was:

  1. Adding a System variable: OPENSSL_CONF

    the value of OPENSSL_CONF should be the openssl.cnf file of your current php version.

for me it was:

  • C:\wamp\bin\php\php5.6.12\extras\ssl\openssl.cnf

-> Restart WAMP -> should work now

Source: http://php.net/manual/en/openssl.installation.php

Can a CSV file have a comment?

No, CSV doesn't specify any way of tagging comments - they will just be loaded by programs like Excel as additional cells containing text.

The closest you can manage (with CSV being imported into a specific application such as Excel) is to define a special way of tagging comments that Excel will ignore. For Excel, you can "hide" the comment (to a limited degree) by embedding it into a formula. For example, try importing the following csv file into Excel:

=N("This is a comment and will appear as a simple zero value in excel")
John, Doe, 24

You still end up with a cell in the spreadsheet that displays the number 0, but the comment is hidden.

Alternatively, you can hide the text by simply padding it out with spaces so that it isn't displayed in the visible part of cell:

                              This is a sort-of hidden comment!,
John, Doe, 24

Note that you need to follow the comment text with a comma so that Excel fills the following cell and thus hides any part of the text that doesn't fit in the cell.

Nasty hacks, which will only work with Excel, but they may suffice to make your output look a little bit tidier after importing.

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

PHP filesize MB/KB conversion

Here is a sample:

<?php
// Snippet from PHP Share: http://www.phpshare.org

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
}
?>

How to put sshpass command inside a bash script?

Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.

You should also probably do the same with the command you are trying to run.

The problem might be that it is not finding it.

How to clean node_modules folder of packages that are not in package.json?

Due to its folder nesting Windows can’t delete the folder as its name is too long. To solve this, install RimRaf:

npm install rimraf -g

rimraf node_modules

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

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

How to make several plots on a single page using matplotlib?

To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.

CASCADE DELETE just once

Yeah, as others have said, there's no convenient 'DELETE FROM my_table ... CASCADE' (or equivalent). To delete non-cascading foreign key-protected child records and their referenced ancestors, your options include:

  • Perform all the deletions explicitly, one query at a time, starting with child tables (though this won't fly if you've got circular references); or
  • Perform all the deletions explicitly in a single (potentially massive) query; or
  • Assuming your non-cascading foreign key constraints were created as 'ON DELETE NO ACTION DEFERRABLE', perform all the deletions explicitly in a single transaction; or
  • Temporarily drop the 'no action' and 'restrict' foreign key constraints in the graph, recreate them as CASCADE, delete the offending ancestors, drop the foreign key constraints again, and finally recreate them as they were originally (thus temporarily weakening the integrity of your data); or
  • Something probably equally fun.

It's on purpose that circumventing foreign key constraints isn't made convenient, I assume; but I do understand why in particular circumstances you'd want to do it. If it's something you'll be doing with some frequency, and if you're willing to flout the wisdom of DBAs everywhere, you may want to automate it with a procedure.

I came here a few months ago looking for an answer to the "CASCADE DELETE just once" question (originally asked over a decade ago!). I got some mileage out of Joe Love's clever solution (and Thomas C. G. de Vilhena's variant), but in the end my use case had particular requirements (handling of intra-table circular references, for one) that forced me to take a different approach. That approach ultimately became recursively_delete (PG 10.10).

I've been using recursively_delete in production for a while, now, and finally feel (warily) confident enough to make it available to others who might wind up here looking for ideas. As with Joe Love's solution, it allows you to delete entire graphs of data as if all foreign key constraints in your database were momentarily set to CASCADE, but offers a couple additional features:

  • Provides an ASCII preview of the deletion target and its graph of dependents.
  • Performs deletion in a single query using recursive CTEs.
  • Handles circular dependencies, intra- and inter-table.
  • Handles composite keys.
  • Skips 'set default' and 'set null' constraints.

Load local HTML file in a C# WebBrowser

What worked for me was

<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />

from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.

Convert String (UTF-16) to UTF-8 in C#

If you want a UTF8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the followed:

public static string Utf16ToUtf8(string utf16String)
{
   /**************************************************************
    * Every .NET string will store text with the UTF16 encoding, *
    * known as Encoding.Unicode. Other encodings may exist as    *
    * Byte-Array or incorrectly stored with the UTF16 encoding.  *
    *                                                            *
    * UTF8 = 1 bytes per char                                    *
    *    ["100" for the ansi 'd']                                *
    *    ["206" and "186" for the russian '?']                   *
    *                                                            *
    * UTF16 = 2 bytes per char                                   *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["186, 3" for the russian '?']                          *
    *                                                            *
    * UTF8 inside UTF16                                          *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["206, 0" and "186, 0" for the russian '?']             *
    *                                                            *
    * We can use the convert encoding function to convert an     *
    * UTF16 Byte-Array to an UTF8 Byte-Array. When we use UTF8   *
    * encoding to string method now, we will get a UTF16 string. *
    *                                                            *
    * So we imitate UTF16 by filling the second byte of a char   *
    * with a 0 byte (binary 0) while creating the string.        *
    **************************************************************/

    // Storage for the UTF8 string
    string utf8String = String.Empty;

    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Fill UTF8 bytes inside UTF8 string
    for (int i = 0; i < utf8Bytes.Length; i++)
    {
        // Because char always saves 2 bytes, fill char with 0
        byte[] utf8Container = new byte[2] { utf8Bytes[i], 0 };
        utf8String += BitConverter.ToChar(utf8Container, 0);
    }

    // Return UTF8
    return utf8String;
}

In my case the DLL request is a UTF8 string too, but unfortunately the UTF8 string must be interpreted with UTF16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 has to be converted to the UTF16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf16ToUtf8(string utf16String)
{
    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Return UTF8 bytes as ANSI string
    return Encoding.Default.GetString(utf8Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 WideCharToMultiByte(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPWStr)] String lpWideCharStr, Int32 cchWideChar, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpMultiByteStr, Int32 cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);

public static string Utf16ToUtf8(string utf16String)
{
    Int32 iNewDataLen = WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, utf16String.Length, null, 0, IntPtr.Zero, IntPtr.Zero);
    if (iNewDataLen > 1)
    {
        StringBuilder utf8String = new StringBuilder(iNewDataLen);
        WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, -1, utf8String, utf8String.Capacity, IntPtr.Zero, IntPtr.Zero);

        return utf8String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf8ToUtf16. Hope I could be of help.

Allow only numbers to be typed in a textbox

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

and then define the isNumber function:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

You can see it in action here.

Converting Java objects to JSON with Jackson

Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:

StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

How to write to a JSON file in the correct format

To make this work on Ubuntu Linux:

  1. I installed the Ubuntu package ruby-json:

    apt-get install ruby-json
    
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO

  3. $HOME/.bashrc included:

    ${HOME}/rubybin:${PATH}
    

(On this occasion I also typed the above on the bash command line.)

Then it worked when I entered on the command line:

jsonDemo

Shortcut to create properties in Visual Studio?

You could type "prop" and then press tab twice. That will generate the following.

public TYPE Type { get; set; }

Then you change "TYPE" and "Type":

public string myString {get; set;}

You can also get the full property typing "propfull" and then tab twice. That would generate the field and the full property.

private int myVar;

public int MyProperty
{
    get { return myVar;}
    set { myVar = value;}
}

In reactJS, how to copy text to clipboard?

navigator.clipboard doesn't work over http connection according to their document. So you can check if it's coming undefined and use document.execCommand('copy') instead, this solution should cover almost all the browsers

const defaultCopySuccessMessage = 'ID copied!'

const CopyItem = (props) => {
  const { copySuccessMessage = defaultCopySuccessMessage, value } = props

  const [showCopySuccess, setCopySuccess] = useState(false)


  function fallbackToCopy(text) {
    if (window.clipboardData && window.clipboardData.setData) {
      // IE specific code path to prevent textarea being shown while dialog is visible.
      return window.clipboardData.setData('Text', text)
    } else if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
      const textarea = document.createElement('textarea')
      textarea.innerText = text
      // const parentElement=document.querySelector(".up-CopyItem-copy-button")
      const parentElement = document.getElementById('copy')
      if (!parentElement) {
        return
      }
      parentElement.appendChild(textarea)
      textarea.style.position = 'fixed' // Prevent scrolling to bottom of page in MS Edge.
      textarea.select()
      try {
        setCopySuccess(true)
        document.execCommand('copy') // Security exception may be thrown by some browsers.
      } catch (ex) {
        console.log('Copy to clipboard failed.', ex)
        return false
      } finally {
        parentElement.removeChild(textarea)
      }
    }
  }

  const copyID = () => {
    if (!navigator.clipboard) {
      fallbackToCopy(value)
      return
    }
    navigator.clipboard.writeText(value)
    setCopySuccess(true)
  }

  return showCopySuccess ? (
    <p>{copySuccessMessage}</p>
  ) : (
    <span id="copy">
      <button onClick={copyID}>Copy Item </button>
    </span>
  )
}

And you can just call and reuse the component anywhere you'd like to

const Sample=()=>(
   <CopyItem value="item-to-copy"/>
)

How to Insert Double or Single Quotes

Or Select range and Format cells > Custom \"@\"

AWS EFS vs EBS vs S3 (differences & when to use?)

The main difference between EBS and EFS is that EBS is only accessible from a single EC2 instance in your particular AWS region, while EFS allows you to mount the file system across multiple regions and instances.

Finally, Amazon S3 is an object store good at storing vast numbers of backups or user files.

How do I (or can I) SELECT DISTINCT on multiple columns?

I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using

Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering

It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.

use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering

SELECT        GrondOfLucht
FROM            dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)

How to sort by two fields in Java?

You need to implement your own Comparator, and then use it: for example

Arrays.sort(persons, new PersonComparator());

Your Comparator could look a bit like this:

public class PersonComparator implements Comparator<? extends Person> {

  public int compare(Person p1, Person p2) {
     int nameCompare = p1.name.compareToIgnoreCase(p2.name);
     if (nameCompare != 0) {
        return nameCompare;
     } else {
       return Integer.valueOf(p1.age).compareTo(Integer.valueOf(p2.age));
     }
  }
}

The comparator first compares the names, if they are not equals it returns the result from comparing them, else it returns the compare result when comparing the ages of both persons.

This code is only a draft: because the class is immutable you could think of building an singleton of it, instead creating a new instance for each sorting.

Compare two files line by line and generate the difference in another file

diff a1.txt a2.txt | grep '> ' | sed 's/> //' > a3.txt

I tried almost all the answers in this thread, but none was complete. After few trails above one worked for me. diff will give you difference but with some unwanted special charas. where you actual difference lines starts with '> '. so next step is to grep lines starts with '> 'and followed by removing the same with sed.

How do I convert a float to an int in Objective C?

int myInt = (int) myFloat;

Worked fine for me.

int myInt = [[NSNumber numberWithFloat:myFloat] intValue];

Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)

How to automatically reload a page after a given period of inactivity

If you want to refresh the page if there is no activity then you need to figure out how to define activity. Let's say we refresh the page every minute unless someone presses a key or moves the mouse. This uses jQuery for event binding:

<script>
     var time = new Date().getTime();
     $(document.body).bind("mousemove keypress", function(e) {
         time = new Date().getTime();
     });

     function refresh() {
         if(new Date().getTime() - time >= 60000) 
             window.location.reload(true);
         else 
             setTimeout(refresh, 10000);
     }

     setTimeout(refresh, 10000);
</script>

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

How do you concatenate Lists in C#?

targetList = list1.Concat(list2).ToList();

It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly.

What is the difference between Serialization and Marshaling?

I think that the main difference is that Marshalling supposedly also involves the codebase. In other words, you would not be able to marshal and unmarshal an object into a state-equivalent instance of a different class. .

Serialization just means that you can store the object and reobtain an equivalent state, even if it is an instance of another class.

That being said, they are typically synonyms.

How to tell if tensorflow is using gpu acceleration from inside python shell?

Ok, first launch an ipython shell from the terminal and import TensorFlow:

$ ipython --pylab
Python 3.6.5 |Anaconda custom (64-bit)| (default, Apr 29 2018, 16:14:56) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg

In [1]: import tensorflow as tf

Now, we can watch the GPU memory usage in a console using the following command:

# realtime update for every 2s
$ watch -n 2 nvidia-smi

Since we've only imported TensorFlow but have not used any GPU yet, the usage stats will be:

tf non-gpu usage

Notice how the GPU memory usage is very less (~ 700MB); Sometimes the GPU memory usage might even be as low as 0 MB.


Now, let's load the GPU in our code. As indicated in tf documentation, do:

In [2]: sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

Now, the watch stats should show an updated GPU usage memory as below:

tf gpu-watch

Observe now how our Python process from the ipython shell is using ~ 7 GB of the GPU memory.


P.S. You can continue watching these stats as the code is running, to see how intense the GPU usage is over time.

node.js, socket.io with SSL

On the same note, if your server supports both http and https you can connect using:

var socket = io.connect('//localhost');

to auto detect the browser scheme and connect using http/https accordingly. when in https, the transport will be secured by default, as connecting using

var socket = io.connect('https://localhost');

will use secure web sockets - wss:// (the {secure: true} is redundant).

for more information on how to serve both http and https easily using the same node server check out this answer.

TSQL - Cast string to integer or return default value

I know it's not pretty but it is simple. Try this:

declare @AlpaNumber nvarchar(50) = 'ABC'
declare @MyNumber int = 0
begin Try
select @MyNumber = case when ISNUMERIC(@AlpaNumber) = 1 then cast(@AlpaNumber as int) else 0 end
End Try
Begin Catch
    -- Do nothing
End Catch 

if exists(select * from mytable where mynumber = @MyNumber)
Begin
print 'Found'
End
Else
Begin
 print 'Not Found'
End

iterating over each character of a String in ruby 1.8.6 (each_char)

"ABCDEFG".chars.each do |char|
  puts char
end

also

"ABCDEFG".each_char {|char| p char}

Ruby version >2.5.1

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

what is the most efficient way of counting occurrences in pandas?

Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False (default is True)

An example:

>>> df['Embarked'].value_counts(dropna=False)
S      644
C      168
Q       77
NaN      2

Secure random token in Node.js

Check out:

var crypto = require('crypto');
crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

The accepted answer has the drawback that it doesn't take into consideration that a database can be locked by a connection that is executing a query that involves tables in a database other than the one connected to.

This can be the case if the server instance has more than one database and the query directly or indirectly (for example through synonyms) use tables in more than one database etc.

I therefore find that it sometimes is better to use syslockinfo to find the connections to kill.

My suggestion would therefore be to use the below variation of the accepted answer from AlexK:

USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), req_spid) + ';'  
FROM master.dbo.syslockinfo
WHERE rsc_type = 2
AND rsc_dbid  = db_id('MyDB')

EXEC(@kill);

How to set width of mat-table column in angular?

You can do it by using below CSS:

table {
  width: 100%;
  table-layout: fixed;
}

th, td {
  overflow: hidden;
  width: 200px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Here is a StackBlitz Example with Sample Data

How to switch text case in visual studio code

For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.

  1. Open "File -> Preferences -> Keyboard Shortcuts" or "Code -> Preferences -> Keyboard Shortcuts" for Mac Users

  2. In the search bar type transform.

  3. By default you will not have anything under Keybinding. Now double-click on Transform to Lowercase or Transform to Uppercase.

  4. Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u for uppercase or ctrl+shift+l for lowercase.

  5. Press Enter on your keyboard to save and exit. Do same for the other option.

  6. Enjoy KEYBINDING

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Cannot run Eclipse; JVM terminated. Exit code=13

I face same issue with sts 3.8.4, so I tried different settings but not luck, I reinstall jdk again n tried but same problem. Finally I downloaded sts 3.8.2 n it runs with out any issue. Using windows 8, 64 bit os. thanks

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:

os.popen(command).read()

Python : List of dict, if exists increment a dict value, if not append a new dict

Use defaultdict:

from collections import defaultdict

urls = defaultdict(int)

for url in list_of_urls:
    urls[url] += 1

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Java Could not reserve enough space for object heap error

This was occuring for me and it is such an easy fix.

  1. you have to make sure that you have the correct java for your system such as 32bit or 64bit.
  2. if you have installed the correct software and it still occurs than goto

    control panelsystemadvanced system settings for Windows 8 or

    control panelsystem and securitysystemadvanced system settings for Windows 10.

  3. you must goto the {advanced tab} and then click on {Environment Variables}.
  4. you will click on {New} under the <system variables>
  5. you will create a new variable. Variable name: _JAVA_OPTIONS Variable Value: -Xmx512M

At least that is what worked for me.

SoapUI "failed to load url" error when loading WSDL

The following solution helped me:

-Djsse.enableSNIExtension=false

In SoapUI-5.3.0.vmoptions.

Unable to import path from django.urls

It look's as if you forgot to activate you virtual environment try running python3 -m venv venv or if you already have virtual environment set up try to activate it by running source venv/bin/activate

HTML CSS Invisible Button

You can use CSS to hide the button.

button {
  visibility: hidden;
}

If your <button> is just a clickable area on the image, why bother make it a button? You can use <map> element instead.

Using Caps Lock as Esc in Mac OS X

Since macOS 10.12.1 it is possible to remap Caps Lock to Esc natively (System Preferences -> Keyboard -> Modifier Keys).

enter image description here

Create a string with n characters

My contribution based on the algorithm for fast exponentiation.

/**
 * Repeats the given {@link String} n times.
 * 
 * @param str
 *            the {@link String} to repeat.
 * @param n
 *            the repetition count.
 * @throws IllegalArgumentException
 *             when the given repetition count is smaller than zero.
 * @return the given {@link String} repeated n times.
 */
public static String repeat(String str, int n) {
    if (n < 0)
        throw new IllegalArgumentException(
                "the given repetition count is smaller than zero!");
    else if (n == 0)
        return "";
    else if (n == 1)
        return str;
    else if (n % 2 == 0) {
        String s = repeat(str, n / 2);
        return s.concat(s);
    } else
        return str.concat(repeat(str, n - 1));
}

I tested the algorithm against two other approaches:

  • Regular for loop using String.concat() to concatenate string
  • Regular for loop using a StringBuilder

Test code (concatenation using a for loop and String.concat() becomes to slow for large n, so I left it out after the 5th iteration).

/**
 * Test the string concatenation operation.
 * 
 * @param args
 */
public static void main(String[] args) {
    long startTime;
    String str = " ";

    int n = 1;
    for (int j = 0; j < 9; ++j) {
        n *= 10;
        System.out.format("Performing test with n=%d\n", n);

        startTime = System.currentTimeMillis();
        StringUtil.repeat(str, n);
        System.out
                .format("\tStringUtil.repeat() concatenation performed in    %d milliseconds\n",
                        System.currentTimeMillis() - startTime);

        if (j <5) {
            startTime = System.currentTimeMillis();
            String string = "";
            for (int i = 0; i < n; ++i)
                string = string.concat(str);
            System.out
                    .format("\tString.concat() concatenation performed in        %d milliseconds\n",
                            System.currentTimeMillis() - startTime);
        } else
            System.out
                    .format("\tString.concat() concatenation performed in        x milliseconds\n");
        startTime = System.currentTimeMillis();
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < n; ++i)
            b.append(str);
        b.toString();
        System.out
                .format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
                        System.currentTimeMillis() - startTime);
    }
}

Results:

Performing test with n=10
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        0 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        43 milliseconds
    StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        1579 milliseconds
    StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
    StringUtil.repeat() concatenation performed in    0 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
    StringUtil.repeat() concatenation performed in    7 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
    StringUtil.repeat() concatenation performed in    80 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
    StringUtil.repeat() concatenation performed in    1372 milliseconds
    String.concat() concatenation performed in        x milliseconds
    StringBuilder.append() concatenation performed in 12125 milliseconds

Conclusion:

  • For large n - use the recursive approach
  • For small n - for loop has sufficient speed

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

How to run a command as a specific user in an init script?

If you have start-stop-daemon

start-stop-daemon --start --quiet -u username -g usergroup --exec command ...

CSS Animation onClick

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

How may I align text to the left and text to the right in the same line?

HTML FILE:

<div class='left'> Left Aligned </div> 
<div class='right'> Right Aligned </div>

CSS FILE:

.left
{
  float: left;
}

.right
{
  float: right;
}

and you are done ....

How do I select an element in jQuery by using a variable for the ID?

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

How to export data from Spark SQL to CSV

The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:

df.coalesce(1).
    write.
    format("com.databricks.spark.csv").
    option("header", "true").
    save("myfile.csv")

and rename the output of the lib (name "part-00000") to a desire filename.

This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/

PostgreSQL Crosstab Query

Sorry this isn't complete because I can't test it here, but it may get you off in the right direction. I'm translating from something I use that makes a similar query:

select mt.section, mt1.count as Active, mt2.count as Inactive
from mytable mt
left join (select section, count from mytable where status='Active')mt1
on mt.section = mt1.section
left join (select section, count from mytable where status='Inactive')mt2
on mt.section = mt2.section
group by mt.section,
         mt1.count,
         mt2.count
order by mt.section asc;

The code I'm working from is:

select m.typeID, m1.highBid, m2.lowAsk, m1.highBid - m2.lowAsk as diff, 100*(m1.highBid - m2.lowAsk)/m2.lowAsk as diffPercent
from mktTrades m
   left join (select typeID,MAX(price) as highBid from mktTrades where bid=1 group by typeID)m1
   on m.typeID = m1.typeID
   left join (select typeID,MIN(price) as lowAsk  from mktTrades where bid=0 group by typeID)m2
   on m1.typeID = m2.typeID
group by m.typeID, 
         m1.highBid, 
         m2.lowAsk
order by diffPercent desc;

which will return a typeID, the highest price bid and the lowest price asked and the difference between the two (a positive difference would mean something could be bought for less than it can be sold).

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

How to export iTerm2 Profiles

I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2.

See https://apple.stackexchange.com/a/111559

How to create a number picker dialog?

I have made a small demo of NumberPicker. This may not be perfect but you can use and modify the same.

public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener
{
    private static TextView tv;
    static Dialog d ;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        Button b = (Button) findViewById(R.id.button11);
         b.setOnClickListener(new OnClickListener()
         {

            @Override
            public void onClick(View v) {
                 show();
            }
            });
           }
     @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

         Log.i("value is",""+newVal);

     }

    public void show()
    {

         final Dialog d = new Dialog(MainActivity.this);
         d.setTitle("NumberPicker");
         d.setContentView(R.layout.dialog);
         Button b1 = (Button) d.findViewById(R.id.button1);
         Button b2 = (Button) d.findViewById(R.id.button2);
         final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker1);
         np.setMaxValue(100);
         np.setMinValue(0);
         np.setWrapSelectorWheel(false);
         np.setOnValueChangedListener(this);
         b1.setOnClickListener(new OnClickListener()
         {
          @Override
          public void onClick(View v) {
              tv.setText(String.valueOf(np.getValue()));
              d.dismiss();
           }    
          });
         b2.setOnClickListener(new OnClickListener()
         {
          @Override
          public void onClick(View v) {
              d.dismiss();
           }    
          });
       d.show();


    }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Open" />

</RelativeLayout>

dialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/numberPicker1"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="98dp"
        android:layout_toRightOf="@+id/numberPicker1"
        android:text="Cancel" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_marginRight="16dp"
        android:layout_toLeftOf="@+id/numberPicker1"
        android:text="Set" />

</RelativeLayout>

Edit:

under res/values/dimens.xml

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

</resources>

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

How to get first object out from List<Object> using Linq

var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));

"message failed to fetch from registry" while trying to install any module

You also need to install software-properties-common for add-apt-repository to work. so it will be

sudo apt-get purge nodejs npm
sudo apt-get install -y python-software-properties python g++ make software-properties-common
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

http post - how to send Authorization header?

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

Python: Assign Value if None Exists

One-liner solution here:

var1 = locals().get("var1", "default value")

Instead of having NameError, this solution will set var1 to default value if var1 hasn't been defined yet.

Here's how it looks like in Python interactive shell:

>>> var1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var1' is not defined
>>> var1 = locals().get("var1", "default value 1")
>>> var1
'default value 1'
>>> var1 = locals().get("var1", "default value 2")
>>> var1
'default value 1'
>>>

T-SQL to list all the user mappings with database roles/permissions for a Login

CREATE TABLE #tempww (
    LoginName nvarchar(max),
    DBname nvarchar(max),
    Username nvarchar(max), 
    AliasName nvarchar(max)
)

INSERT INTO #tempww 
EXEC master..sp_msloginmappings 

-- display results
SELECT * 
FROM   #tempww 
ORDER BY dbname, username

-- cleanup
DROP TABLE #tempww

How to detect Windows 64-bit platform with .NET?

Quickest way:

if(IntPtr.Size == 8) {
    // 64 bit machine
} else if(IntPtr.Size == 4)  {
    // 32 bit machine
} 

Note: this is very direct and works correctly on 64-bit only if the program does not force execution as a 32-bit process (e.g. through <Prefer32Bit>true</Prefer32Bit> in the project settings).

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

How can I make a clickable link in an NSAttributedString?

I just created a subclass of UILabel to specially address such use cases. You can add multiple links easily and define different handlers for them. It also supports highlighting the pressed link when you touch down for touch feedback. Please refer to https://github.com/null09264/FRHyperLabel.

In your case, the code may like this:

FRHyperLabel *label = [FRHyperLabel new];

NSString *string = @"This morph was generated with Face Dancer, Click to view in the app store.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};

label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];

[label setLinkForSubstring:@"Face Dancer" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
    [[UIApplication sharedApplication] openURL:aURL];
}];

Sample Screenshot (the handler is set to pop an alert instead of open a url in this case)

facedancer

Difference between Constructor and ngOnInit

The Constructor is executed when the class is instantiated. It has nothing do with the angular. It is the feature of Javascript and Angular does not have the control over it

The ngOnInit is Angular specific and is called when the Angular has initialized the component with all its input properties

The @Input properties are available under the ngOnInit lifecycle hook. This will help you to do some initialization stuff like getting data from the back-end server etc to display in the view

@Input properties are shows up as undefined inside the constructor

Is it possible to send a variable number of arguments to a JavaScript function?

The apply function takes two arguments; the object this will be binded to, and the arguments, represented with an array.

some_func = function (a, b) { return b }
some_func.apply(obj, ["arguments", "are", "here"])
// "are"

How to increase request timeout in IIS?

For AspNetCore, it looks like this:

<aspNetCore requestTimeout="00:20:00">

From here

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).

/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
   public static function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);

Get the closest number out of an array

ES6 (ECMAScript 2015) Version:

_x000D_
_x000D_
const counts = [4, 9, 15, 6, 2];
const goal = 5;

const output = counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);

console.log(output);
_x000D_
_x000D_
_x000D_

For reusability you can wrap in a curry function that supports placeholders (http://ramdajs.com/0.19.1/docs/#curry or https://lodash.com/docs#curry). This gives lots of flexibility depending on what you need:

_x000D_
_x000D_
const getClosest = _.curry((counts, goal) => {
  return counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

const closestToFive = getClosest(_, 5);
const output = closestToFive([4, 9, 15, 6, 2]);

console.log(output);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I see what I am about to push with git?

You probably want to run git difftool origin/master.... that should show the unified diff of what is on your current branch that is not on the origin/master branch yet and display it in the graphical diff tool of your choice. To be most up-to-date, run git fetch first.

Java String.split() Regex

You could also do something like:

String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");

It handles white spaces and words of variable length and produces the array:

[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

Creating default object from empty value in PHP?

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

UITableview: How to Disable Selection for Some Rows but Not Others

I agree with Bryan's answer

if I do

cell.isUserInteractionEnabled = false 

then the subviews within the cell won't be user interacted.

On the other site, setting

cell.selectionStyle = .none

will trigger the didSelect method despite not updating the selection color.

Using willSelectRowAt is the way I solved my problem. Example:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {

    if indexPath.section == 0{

        if indexPath.row == 0{
            return nil
        }

    }
    else if indexPath.section == 1{

        if indexPath.row == 0{
            return nil
        }

    }

    return indexPath

}

Send File Attachment from Form Using phpMailer and PHP

Try:

if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Basic example can also be found here.

The function definition for AddAttachment is:

public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

How to convert NSDate into unix timestamp iphone sdk?

You can create a unix timestamp date from a date this way:

NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];

How can I add a vertical scrollbar to my div automatically?

To show vertical scroll bar in your div you need to add

height: 100px;   
overflow-y : scroll;

or

height: 100px; 
overflow-y : auto;

push() a two-dimensional array

Create am array and put inside the first, in this case i get data from JSON response

$.getJSON('/Tool/GetAllActiviesStatus/',
   var dataFC = new Array();
   function (data) {
      for (var i = 0; i < data.Result.length; i++) {
          var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
          dataFC.push(serie);
       });

Execution failed app:processDebugResources Android Studio

In my case i had two declaration of

<?xml version="1.0" encoding="utf-8"?>

in my vector drawable icon

all i had to do was delete one

How do I auto size columns through the Excel interop objects?

Add this at your TODO point:

aRange.Columns.AutoFit();

How to set the color of "placeholder" text?

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

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

Here is what I use:

import Foundation
import CoreLocation
import UIKit

class BackgroundLocationManager :NSObject, CLLocationManagerDelegate {

    static let instance = BackgroundLocationManager()
    static let BACKGROUND_TIMER = 150.0 // restart location manager every 150 seconds
    static let UPDATE_SERVER_INTERVAL = 60 * 60 // 1 hour - once every 1 hour send location to server

    let locationManager = CLLocationManager()
    var timer:NSTimer?
    var currentBgTaskId : UIBackgroundTaskIdentifier?
    var lastLocationDate : NSDate = NSDate()

    private override init(){
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.activityType = .Other;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        if #available(iOS 9, *){
            locationManager.allowsBackgroundLocationUpdates = true
        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
    }

    func applicationEnterBackground(){
        FileLogger.log("applicationEnterBackground")
        start()
    }

    func start(){
        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        } else {
                locationManager.requestAlwaysAuthorization()
        }
    }
    func restart (){
        timer?.invalidate()
        timer = nil
        start()
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case CLAuthorizationStatus.Restricted:
            //log("Restricted Access to location")
        case CLAuthorizationStatus.Denied:
            //log("User denied access to location")
        case CLAuthorizationStatus.NotDetermined:
            //log("Status not determined")
        default:
            //log("startUpdatintLocation")
            if #available(iOS 9, *){
                locationManager.requestLocation()
            } else {
                locationManager.startUpdatingLocation()
            }
        }
    }
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if(timer==nil){
            // The locations array is sorted in chronologically ascending order, so the
            // last element is the most recent
            guard let location = locations.last else {return}

            beginNewBackgroundTask()
            locationManager.stopUpdatingLocation()
            let now = NSDate()
            if(isItTime(now)){
                //TODO: Every n minutes do whatever you want with the new location. Like for example sendLocationToServer(location, now:now)
            }
        }
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        CrashReporter.recordError(error)

        beginNewBackgroundTask()
        locationManager.stopUpdatingLocation()
    }

    func isItTime(now:NSDate) -> Bool {
        let timePast = now.timeIntervalSinceDate(lastLocationDate)
        let intervalExceeded = Int(timePast) > BackgroundLocationManager.UPDATE_SERVER_INTERVAL
        return intervalExceeded;
    }

    func sendLocationToServer(location:CLLocation, now:NSDate){
        //TODO
    }

    func beginNewBackgroundTask(){
        var previousTaskId = currentBgTaskId;
        currentBgTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            FileLogger.log("task expired: ")
        })
        if let taskId = previousTaskId{
            UIApplication.sharedApplication().endBackgroundTask(taskId)
            previousTaskId = UIBackgroundTaskInvalid
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(BackgroundLocationManager.BACKGROUND_TIMER, target: self, selector: #selector(self.restart),userInfo: nil, repeats: false)
    }
}

I start the tracking in AppDelegate like that:

BackgroundLocationManager.instance.start()

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

How to replace an entire line in a text file by line number

Not the greatest, but this should work:

sed -i 'Ns/.*/replacement-line/' file.txt

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

sed 'Ns/.*/replacement-line/' file.txt > new_file.txt

What do numbers using 0x notation mean?

SIMPLE

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example :

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or any base ..

Hope Helped in some way.

Good day,

'const int' vs. 'int const' as function parameters in C++ and C

I think in this case they are the same, but here is an example where order matters:

const int* cantChangeTheData;
int* const cantChangeTheAddress;

invalid command code ., despite escaping periods, using sed

If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly and giving '' as argument to -i:

find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;

See this.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

To set flashdata you need to redirect controller function

$this->session->set_flashdata('message_name', 'This is test message');

//redirect to some function
redirect("controller/function_name");

//echo in view or controller
$this->session->flashdata('message_name');

WPF binding to Listbox selectedItem

since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.

and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.

How to open Visual Studio Code from the command line on OSX?

I discovered a neat workaround for mingw32 (i.e. for those of you using the version of bash which is installed by git-scm.com on windows):

code () { VSCODE_CWD="$PWD" cmd //c code $* ;}

How to prevent page scrolling when scrolling a DIV element?

If you don't care about the compatibility with older IE versions (< 8), you could make a custom jQuery plugin and then call it on the overflowing element.

This solution has an advantage over the one Šime Vidas proposed, as it doesn't overwrite the scrolling behavior - it just blocks it when appropriate.

$.fn.isolatedScroll = function() {
    this.bind('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
            bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

$('.scrollable').isolatedScroll();

Where does Android emulator store SQLite database?

Since the question is not restricted to Android Studio, So I am giving the path for Visual Studio 2015 (worked for Xamarin).

Tools-Android-Android Device Monitor

enter image description here

  • Locate the database file mentioned in above image, and click on Pull button as it shown in image 2.
  • Save the file in your desired location.
  • You can open that file using SQLite Studio or DB Browser for SQLite.

Special Thanks to other answerers of this question.

How can I find the first occurrence of a sub-string in a python string?

Quick Overview: index and find

Next to the find method there is as well index. find and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueError whereas find returns -1. Speedwise, both have the same benchmark results.

s.find(t)    #returns: -1, or index where t starts in s
s.index(t)   #returns: Same as find, but raises ValueError if t is not in s

Additional knowledge: rfind and rindex:

In general, find and index return the smallest index where the passed-in string starts, and rfind and rindex return the largest index where it starts Most of the string searching algorithms search from left to right, so functions starting with r indicate that the search happens from right to left.

So in case that the likelihood of the element you are searching is close to the end than to the start of the list, rfind or rindex would be faster.

s.rfind(t)   #returns: Same as find, but searched right to left
s.rindex(t)  #returns: Same as index, but searches right to left

Source: Python: Visual QuickStart Guide, Toby Donaldson

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

This resolved issue for me.

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

GRANT ALL PRIVILEGES ON *.cfe TO 'root'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;

Set cookie and get cookie with JavaScript

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

Fastest way to check if a string matches a regexp in ruby?

This is the benchmark I have run after finding some articles around the net.

With 2.4.0 the winner is re.match?(str) (as suggested by @wiktor-stribizew), on previous versions, re =~ str seems to be fastest, although str =~ re is almost as fast.

#!/usr/bin/env ruby
require 'benchmark'

str = "aacaabc"
re = Regexp.new('a+b').freeze

N = 4_000_000

Benchmark.bm do |b|
    b.report("str.match re\t") { N.times { str.match re } }
    b.report("str =~ re\t")    { N.times { str =~ re } }
    b.report("str[re]  \t")    { N.times { str[re] } }
    b.report("re =~ str\t")    { N.times { re =~ str } }
    b.report("re.match str\t") { N.times { re.match str } }
    if re.respond_to?(:match?)
        b.report("re.match? str\t") { N.times { re.match? str } }
    end
end

Results MRI 1.9.3-o551:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         2.390000   0.000000   2.390000 (  2.397331)
str =~ re         2.450000   0.000000   2.450000 (  2.446893)
str[re]           2.940000   0.010000   2.950000 (  2.941666)
re.match str      3.620000   0.000000   3.620000 (  3.619922)
str.match re      4.180000   0.000000   4.180000 (  4.180083)

Results MRI 2.1.5:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         1.150000   0.000000   1.150000 (  1.144880)
str =~ re         1.160000   0.000000   1.160000 (  1.150691)
str[re]           1.330000   0.000000   1.330000 (  1.337064)
re.match str      2.250000   0.000000   2.250000 (  2.255142)
str.match re      2.270000   0.000000   2.270000 (  2.270948)

Results MRI 2.3.3 (there is a regression in regex matching, it seems):

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re =~ str         3.540000   0.000000   3.540000 (  3.535881)
str =~ re         3.560000   0.000000   3.560000 (  3.560657)
str[re]           4.300000   0.000000   4.300000 (  4.299403)
re.match str      5.210000   0.010000   5.220000 (  5.213041)
str.match re      6.000000   0.000000   6.000000 (  6.000465)

Results MRI 2.4.0:

$ ./bench-re.rb  | sort -t $'\t' -k 2
       user     system      total        real
re.match? str     0.690000   0.010000   0.700000 (  0.682934)
re =~ str         1.040000   0.000000   1.040000 (  1.035863)
str =~ re         1.040000   0.000000   1.040000 (  1.042963)
str[re]           1.340000   0.000000   1.340000 (  1.339704)
re.match str      2.040000   0.000000   2.040000 (  2.046464)
str.match re      2.180000   0.000000   2.180000 (  2.174691)

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

How to throw an exception in C?

If you write code with Happy path design pattern (i.e. for embedded device) you may simulate exception error processing (aka deffering or finally emulation) with operator "goto".

int process(int port)
{
    int rc;
    int fd1;
    int fd2;

    fd1 = open("/dev/...", ...);
    if (fd1 == -1) {
      rc = -1;
      goto out;
    }

    fd2 = open("/dev/...", ...);
    if (fd2 == -1) {
      rc = -1;
      goto out;
    }

    // Do some with fd1 and fd2 for example write(f2, read(fd1))

    rc = 0;

   out:

    //if (rc != 0) {
        (void)close(fd1);
        (void)close(fd2);
    //}

    return rc;
}

It does not actually exception handler but it take you a way to handle error at fucntion exit.

P.S. You should be careful use goto only from same or more deep scopes and never jump variable declaration.

Syntax of for-loop in SQL Server

Try it, learn it:

DECLARE @r INT = 5
DECLARE @i INT = 0
DECLARE @F varchar(max) = ''
WHILE @i < @r
BEGIN

    DECLARE @j INT = 0
    DECLARE @o varchar(max) = ''
    WHILE @j < @r - @i - 1
    BEGIN
        SET @o = @o + ' '
        SET @j += 1
    END

    DECLARE @k INT = 0
    WHILE @k < @i + 1
    BEGIN
        SET @o = @o + ' *'  -- '*'
        SET @k += 1
    END
    SET @i += 1
    SET @F = @F + @o + CHAR(13)
END
PRINT @F

With date:

DECLARE @d DATE = '2019-11-01'
WHILE @d < GETDATE()
BEGIN
    PRINT @d
    SET @d = DATEADD(DAY,1,@d)
END
PRINT 'n'
PRINT @d

How to input a regex in string.replace?

don't have to use regular expression (for your sample string)

>>> s
'this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. \nand there are many other lines in the txt files\nwith<[3> such tags </[3>\n'

>>> for w in s.split(">"):
...   if "<" in w:
...      print w.split("<")[0]
...
this is a paragraph with
 in between
 and then there are cases ... where the
 number ranges from 1-100
.
and there are many other lines in the txt files
with
 such tags

Is a GUID unique 100% of the time?

Guids are statistically unique. The odds of two different clients generating the same Guid are infinitesimally small (assuming no bugs in the Guid generating code). You may as well worry about your processor glitching due to a cosmic ray and deciding that 2+2=5 today.

Multiple threads allocating new guids will get unique values, but you should get that the function you are calling is thread safe. Which environment is this in?

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

Android - set TextView TextStyle programmatically?

You may try this one

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

Passing an array/list into a Python function

You can pass lists just like other types:

l = [1,2,3]

def stuff(a):
   for x in a:
      print a


stuff(l)

This prints the list l. Keep in mind lists are passed as references not as a deep copy.

ALTER TABLE, set null in not null column, PostgreSQL 9.1

First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

StringBuilder vs String concatenation in toString() in Java

Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.

More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?

At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder by itself.

How do I set an absolute include path in PHP?

One strategy

I don't know if this is the best way, but it has worked for me.

$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");

gulp command not found - error after installing gulp

Try to add to your PATH variable the following:

C:\Users\YOUR_USER\AppData\Roaming\npm

I had the same problem and I solved adding the path to my node modules.

How to kill/stop a long SQL query immediately?

First execute the below command:

sp_who2

After that execute the below command with SPID, which you got from above command:

KILL {SPID value}

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use zIndex for placing a view on top of another. It works like the CSS z-index property - components with a larger zIndex will render on top.

You can refer: Layout Props

Snippet:

    <ScrollView>
          <StatusBar backgroundColor="black" barStyle="light-content" />
          <Image style={styles.headerImage} source={{ uri: "http://www.artwallpaperhi.com/thumbnails/detail/20140814/cityscapes%20buildings%20hong%20kong_www.artwallpaperhi.com_18.jpg" }}>
            <View style={styles.back}>
              <TouchableOpacity>
                <Icons name="arrow-back" size={25} color="#ffffff" />
              </TouchableOpacity>
            </View>
            <Image style={styles.subHeaderImage} borderRadius={55} source={{ uri: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Albert_Einstein_1947.jpg/220px-Albert_Einstein_1947.jpg" }} />
          </Image>

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "white"
    },
    headerImage: {
        height: height(150),
        width: deviceWidth
    },
    subHeaderImage: {
        height: 110,
        width: 110,
        marginTop: height(35),
        marginLeft: width(25),
        borderColor: "white",
        borderWidth: 2,
        zIndex: 5
    },

make html text input field grow as I type?

For those strictly looking for a solution that works for input or textarea, this is the simplest solution I've came across. Only a few lines of CSS and one line of JS.

The JavaScript sets a data-* attribute on the element equal to the value of the input. The input is set within a CSS grid, where that grid is a pseudo-element that uses that data-* attribute as its content. That content is what stretches the grid to the appropriate size based on the input value.

Npm install cannot find module 'semver'

I got same error and I solved it.

delete package-lock.json file and node_modules folder then npm install

Ansible - read inventory hosts and variables to group_vars/all file

If you want to have your vars in files under group_vars, just move them here. Vars can be in the inventory ([group:vars] section) but also (and foremost) in files under group_vars or hosts_vars.

For instance, with your example above, you can move your vars for group tests in the file group_vars/tests :

Inventory file :

[lb]
10.112.84.122

[tomcat]
10.112.84.124

[jboss5]
10.112.84.122

...

[tests:children]
lb
tomcat
jboss5

[default:children]
tests

group_vars/tests file :

data_base_user=NETWIN-4.3
data_base_password=NETWIN
data_base_encrypted_password=
data_base_host=10.112.69.48
data_base_port=1521
data_base_service=ssdenwdb
data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb

How to display a list of images in a ListView in Android?

 package studRecords.one;

 import java.util.List;
 import java.util.Vector;

 import android.app.Activity;
 import android.app.ListActivity;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;



public class studRecords extends ListActivity 
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;

static final String[] names = new String[]
{
      "Name (Stud1)", "Name (Stud2)",   
      "Name (Stud3)","Name (Stud4)" 
};

static final String[] usn = new String[]
{
      "1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};

private Integer[] imgid = 
{
  R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
  R.drawable.stud4
};

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlist);

    layoutx = (LayoutInflater) getSystemService(
    Activity.LAYOUT_INFLATER_SERVICE);
    listValue = new Vector<RowData>();
    for(int i=0;i<names.length;i++)
    {
        try
        {
            rd = new RowData(names[i],usn[i],i);
        } 
        catch (ParseException e) 
        {
            e.printStackTrace();
        }
        listValue.add(rd);
    }


   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.detail, listValue);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,long id)
   {            


       listName = names[position];
       listUsn = usn[position];
       images = imgid[position];




       Intent myIntent = new Intent();
       Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
       startActivity(myIntent);

   }
   private class RowData
   {

       protected String mNames;
       protected String mUsn;
       protected int mId;
       RowData(String title,String detail,int id){
       mId=id;
       mNames = title;
       mUsn = detail;
    }
       @Override
    public String toString()
       {
               return mNames+" "+mUsn+" "+mId;
       }
  }

              private class CustomAdapter extends ArrayAdapter<RowData> 
          {
      public CustomAdapter(Context context, int resource,
      int textViewResourceId, List<RowData> objects)
      {               
            super(context, resource, textViewResourceId, objects);
      }
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {   
           ViewHolder holder = null;
           TextView title = null;
           TextView detail = null;
           ImageView i11=null;
           RowData rowData= getItem(position);
           if(null == convertView)
           {
                convertView = layoutx.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
           }
         holder = (ViewHolder) convertView.getTag();
         i11=holder.getImage();
         i11.setImageResource(imgid[rowData.mId]);
         title = holder.gettitle();
         title.setText(rowData.mNames);
         detail = holder.getdetail();
         detail.setText(rowData.mUsn);                                                     

         return convertView;
      }

        private class ViewHolder 
        {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row)
            {
                    mRow = row;
            }
            public TextView gettitle()
            {
                 if(null == title)
                 {
                     title = (TextView) mRow.findViewById(R.id.title);
                 }
                 return title;
            }     
            public TextView getdetail()
            {
                if(null == detail)
                {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }
            public ImageView getImage()
            {
                    if(null == i11)
                    {
                        i11 = (ImageView) mRow.findViewById(R.id.img);
                    }
                    return i11;
            }   
        }
   } 
 }

//mainlist.xml

     <?xml version="1.0" encoding="utf-8"?>
             <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:orientation="horizontal"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
             >
             <ListView
                 android:id="@android:id/list"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
              />
             </LinearLayout>

Entity Framework The underlying provider failed on Open

This solution is for someone facing this issue while deploying a windows application,

I know this is late, but this maybe useful for someone in future, In my scenario, purely this is a connection string issue I developed a windows application using entity framework (DB First approach) and I published it, the code was worked fine on my machine, but it's not worked on the client machine

Reason for this issue:-

I updated the client machine connection string in App.config file, but this is wrong, if that is a windows application, then it will not read the connection string from App.config (For deployed machines), it will read from .exe.config file,

So after deployment, we need to change the connection string in "AppicationName".exe.config file

Locating child nodes of WebElements in selenium

I also found myself in a similar position a couple of weeks ago. You can also do this by creating a custom ElementLocatorFactory (or simply passing in divA into the DefaultElementLocatorFactory) to see if it's a child of the first div - you would then call the appropriate PageFactory initElements method.

In this case if you did the following:

PageFactory.initElements(new DefaultElementLocatorFactory(divA), pageObjectInstance));
// The Page Object instance would then need a WebElement 
// annotated with something like the xpath above or @FindBy(tagName = "input")

LEFT JOIN only first row

Here is my answer using the group by clause.

SELECT *
FROM feeds f
LEFT JOIN 
(
    SELECT artist_id, feed_id
    FROM feeds_artists
    GROUP BY artist_id, feed_id 
) fa ON fa.feed_id = f.id
LEFT JOIN artists a ON a.artist_id = fa.artist_id

Spring MVC - How to return simple String as JSON in Rest Controller

I know that this question is old but i would like to contribute too:

The main difference between others responses is the hashmap return.

@GetMapping("...")
@ResponseBody
public Map<String, Object> endPointExample(...) {

    Map<String, Object> rtn = new LinkedHashMap<>();

    rtn.put("pic", image);
    rtn.put("potato", "King Potato");

    return rtn;

}

This will return:

{"pic":"a17fefab83517fb...beb8ac5a2ae8f0449","potato":"King Potato"}

Which sort algorithm works best on mostly sorted data?

Based on the highly scientific method of watching animated gifs I would say Insertion and Bubble sorts are good candidates.

How to set height property for SPAN

Another option of course is to use Javascript (Jquery here):

$('.box1,.box2').each(function(){
    $(this).height($(this).parent().height());
})

Excel VBA - How to Redim a 2D array?

i solved this in a shorter fashion.

Dim marray() as variant, array2() as variant, YY ,ZZ as integer
YY=1
ZZ=1

Redim marray(1 to 1000, 1 to 10)
Do while ZZ<100 ' this is populating the first array
marray(ZZ,YY)= "something"
ZZ=ZZ+1
YY=YY+1 
Loop
'this part is where you store your array in another then resize and restore to original
array2= marray
Redim marray(1 to ZZ-1, 1 to YY)
marray = array2

CSS background-size: cover replacement for Mobile Safari

That its the correct code of background size :

<div class="html-mobile-background">
</div>
<style type="text/css">
html {
    /* Whatever you want */
}
.html-mobile-background {
    position: fixed;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%; /* To compensate for mobile browser address bar space */
    background: url(YOUR BACKGROUND URL HERE) no-repeat; 
 center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
 background-size: 100% 100%
}
</style>

Dropping connected users in Oracle database

Here's how I "automate" Dropping connected users in Oracle database:

# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import) 
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema

if [ "$1" = "" ] 
then
    echo "Which Schema?"
    read schema
else
    echo "Are you sure? (y/n)"
    read reply
    [ ! $reply = y ] && return 1
    schema=$1
fi

sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin     
  for x in ( select sid, serial# from v\$session where username=upper('$schema') )
  loop  
   execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );  
  end loop;  
  dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

This happened to me as well. For me, Postfix was located at the same server as the PHP script, and the error was happening when I would be using SMTP authentication and smtp.domain.com instead of localhost.

So when I commented out these lines:

$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";

and set the host to

$mail->Host = "localhost";

instead

$mail->Host = 'smtp.mydomainiuse.com'

and it worked :)

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

Is there any way to configure multiple registries in a single npmrc file

For anyone looking also for a solution for authentication, I would add on the scoped packages solution that you can have multiple lines in your .npmrc file:

//internal-npm.example.com:8080/:_authToken=xxxxxxxxxxxxxxx
//registry.npmjs.org/:_authToken=yyyyyyyyyy

Each line represents a different NPM registry

Rounding integer division (instead of truncating)

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity
int div_nearest( int n, int d )
   {
   if (d<0) n*=-1, d*=-1;
   return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1);
   }

This works regardless of the sign of the numerator or denominator.


If you want to match the results of round(N/(double)D) (floating-point division and rounding), here are a few variations that all produce the same results:

int div_nearest( int n, int d )
   {
   int r=(n<0?-1:+1)*(abs(d)>>1); // eliminates a division
// int r=((n<0)^(d<0)?-1:+1)*(d/2); // basically the same as @ericbn
// int r=(n*d<0?-1:+1)*(d/2); // small variation from @ericbn
   return (n+r)/d;
   }

Note: The relative speed of (abs(d)>>1) vs. (d/2) is likely to be platform dependent.

"SMTP Error: Could not authenticate" in PHPMailer

There is no issue with your code.

Follow below two simple steps to send emails from phpmailer.

  • You have to disable 2-step verification setting for google account if you have enabled.

  • Turn ON allow access to less secure app.

How to unzip a file in Powershell?

function unzip {
    param (
        [string]$archiveFilePath,
        [string]$destinationPath
    )

    if ($archiveFilePath -notlike '?:\*') {
        $archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
    }

    if ($destinationPath -notlike '?:\*') {
        $destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
    }

    Add-Type -AssemblyName System.IO.Compression
    Add-Type -AssemblyName System.IO.Compression.FileSystem

    $archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
    $archive = [System.IO.Compression.ZipArchive]::new($archiveFile)

    if (Test-Path $destinationPath) {
        foreach ($item in $archive.Entries) {
            $destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)

            if ($destinationItemPath -like '*/') {
                New-Item $destinationItemPath -Force -ItemType Directory > $null
            } else {
                New-Item $destinationItemPath -Force -ItemType File > $null

                [System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
            }
        }
    } else {
        [System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
    }
}

Using:

unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Appending the same string to a list of strings in Python

Updating with more options

list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
    list1[index] = addstring + value #this will prepend the string
    #list1[index] = value + addstring this will append the string

Avoid using keywords as variables like 'list', renamed 'list' as 'list1' instead

Could not resolve all dependencies for configuration ':classpath'

6 years later here, but for them who are stil facing this issue, I solved it as following. It happened when my module had a different gradle version than the main project. I had gradle version 3.5.3 in project and an older version in module. So, I Just updated that version. The file is here:

./node-modules/[module-name]/android/build.gradle

Write string to output stream

By design it is to be done this way:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush

Create an instance of a class from a string

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

JSON.parse unexpected character error

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated your line below,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

or if you have JSON stored in some variable:

JSON.parse(JSON.stringify(yourJSONobject));

How to add and remove classes in Javascript without jQuery

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note: but not supported in IE <= 9 or Safari <=5.0

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

Python Dictionary contains List as Value - How to update?

dictionary["C1"]=map(lambda x:x+10,dictionary["C1"]) 

Should do it...

Travel/Hotel API's?

After several days of searching found the EAN API - http://developer.ean.com/ - it is a very big one, but it provides really good information. Free demos, XML\JSON format. Looks good.

Cannot read property 'addEventListener' of null

It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded.

You can also put your Javascript code below the html.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Its very simple for those who are using API 21 or greater Use this code below

for Dark ActionBar

<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="android:background">@color/colorDarkGrey</item>
</style>

for_LightActionBar

<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.ActionBar">
    <item name="android:background">@color/colorDarkGrey</item>
</style>

Getting the number of filled cells in a column (VBA)

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

How to enable PHP short tags?

; Default Value: On
; Development Value: Off
; Production Value: Off
; http://php.net/short-open-tag
;short_open_tag=Off   <--Comment this out
; XAMPP for Linux is currently old fashioned
short_open_tag = On   <--Uncomment this

ReactJS call parent method

Pass the method from Parent component down as a prop to your Child component. ie:

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)

How to retrieve GET parameters from JavaScript

My solution expands on @tak3r's.

It returns an empty object when there are no query parameters and supports the array notation ?a=1&a=2&a=3:

function getQueryParams () {
  function identity (e) { return e; }
  function toKeyValue (params, param) {
    var keyValue = param.split('=');
    var key = keyValue[0], value = keyValue[1];

    params[key] = params[key]?[value].concat(params[key]):value;
    return params;
  }
  return decodeURIComponent(window.location.search).
    replace(/^\?/, '').split('&').
    filter(identity).
    reduce(toKeyValue, {});
}

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

Get random item from array

echo $items[array_rand($items)];

array_rand()

Convert String to java.util.Date

It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

You declare your date format and then call the parse method with your string.

private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");

And as Guillaume says, set the timezone!

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

Breaking out of a nested loop

Use a suitable guard in the outer loop. Set the guard in the inner loop before you break.

bool exitedInner = false;

for (int i = 0; i < N && !exitedInner; ++i) {

    .... some outer loop stuff

    for (int j = 0; j < M; ++j) {

        if (sometest) {
            exitedInner = true;
            break;
        }
    }
    if (!exitedInner) {
       ... more outer loop stuff
    }
}

Or better yet, abstract the inner loop into a method and exit the outer loop when it returns false.

for (int i = 0; i < N; ++i) {

    .... some outer loop stuff

    if (!doInner(i, N, M)) {
       break;
    }

    ... more outer loop stuff
}

Subprocess check_output returned non-zero exit status 1

The word check_ in the name means that if the command (the shell in this case that returns the exit status of the last command (yum in this case)) returns non-zero status then it raises CalledProcessError exception. It is by design. If the command that you want to run may return non-zero status on success then either catch this exception or don't use check_ methods. You could use subprocess.call in your case because you are ignoring the captured output, e.g.:

import subprocess

rc = subprocess.call(['grep', 'pattern', 'file'],
                     stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
if rc == 0: # found
   ...
elif rc == 1: # not found
   ...
elif rc > 1: # error
   ...

You don't need shell=True to run the commands from your question.