Programs & Examples On #Ksh

The KornShell is an open source, POSIX-compatible shell language from AT&T based upon the original Bourne shell. Make sure you know whether your ksh is ksh93 or a clone.

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

Bash or KornShell (ksh)?

Bash is the benchmark, but that's mostly because you can be reasonably sure it's installed on every *nix out there. If you're planning to distribute the scripts, use Bash.

I can not really address the actual programming differences between the shells, unfortunately.

Check if file exists and whether it contains a specific string

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi

How to mkdir only if a directory does not already exist?

The old tried and true

mkdir /tmp/qq >/dev/null 2>&1

will do what you want with none of the race conditions many of the other solutions have.

Sometimes the simplest (and ugliest) solutions are the best.

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Send password when using scp to copy files from one server to another

You should use better authentication with open keys. In these case you need no password and no expect.

If you want it with expect, use this script (see answer Automate scp file transfer using a shell script ):

#!/usr/bin/expect -f

# connect via scp
    spawn scp "[email protected]:/home/santhosh/file.dmp" /u01/dumps/file.dmp
#######################
expect {
-re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
}
-re ".*sword.*" {
    exp_send "PASSWORD\r"
}
}
interact

Also, you can use pexpect (python module):

def doScp(user,password, host, path, files):
 fNames = ' '.join(files)
 print fNames
 child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
 print 'scp %s %s@%s:%s' % (fNames, user, host,path)
    i = child.expect(['assword:', r"yes/no"], timeout=30)
    if i == 0:
        child.sendline(password)
    elif i == 1:
        child.sendline("yes")
        child.expect("assword:", timeout=30)
        child.sendline(password)
    data = child.read()
    print data
    child.close()

Get exit code for command in bash/ksh

It should be $cmd instead of $($cmd). Works fine with that on my box.

Edit: Your script works only for one-word commands, like ls. It will not work for "ls cpp". For this to work, replace cmd="$1"; $cmd with "$@". And, do not run your script as command="some cmd"; safeRun command, run it as safeRun some cmd.

Also, when you have to debug your bash scripts, execute with '-x' flag. [bash -x s.sh].

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

In a unix shell, how to get yesterday's date into a variable?

For Hp-UX only below command worked for me:

TZ=aaa24 date +%Y%m%d

you can use it as :

ydate=`TZ=aaa24 date +%Y%m%d`

echo $ydate

How to get the second column from command output?

You don't need awk for that. Using read in Bash shell should be enough, e.g.

some_command | while read c1 c2; do echo $c2; done

or:

while read c1 c2; do echo $c2; done < in.txt

How to set the From email address for mailx command?

On Ubuntu Bionic 18.04, this works as desired:

$ echo -e "testing email via yourisp.com from command line\n\nsent on: $(date)" | mailx --append='FROM:Foghorn Leghorn <[email protected]>' -s "test cli email $(date)" -- [email protected]

Border length smaller than div width?

The border is given the whole html element. If you want half bottom border, you can wrap it with some other identifiable block like span.

HTML code:

<div> <span>content here </span></div>

CSS as below:

 div{
    width:200px;
    height:50px;   
    }
 span{
        width:100px;
        border-bottom:1px solid magenta;   
    } 

Entity Framework Core add unique constraint code-first

To use it in EF core via model configuration

public class ApplicationCompanyConfiguration : IEntityTypeConfiguration<Company>
{
    public void Configure(EntityTypeBuilder<Company> builder)
    {
        builder.ToTable("Company"); 
        builder.HasIndex(p => p.Name).IsUnique();
    }
}

How to set environment via `ng serve` in Angular 6

You need to use the new configuration option (this works for ng build and ng serve as well)

ng serve --configuration=local

or

ng serve -c local

If you look at your angular.json file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)

"configurations": {
  "production": {
    "optimization": true,
    "outputHashing": "all",
    "sourceMap": false,
    "extractCss": true,
    "namedChunks": false,
    "aot": true,
    "extractLicenses": true,
    "vendorChunk": false,
    "buildOptimizer": true,
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  }
}

You can get more info here for managing environment specific configurations.

As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.

Adding a new environment

Edit: To make it clear, file replacements must be specified in the build section. So if you want to use ng serve with a specific environment file (say dev2), you first need to modify the build section to add a new dev2 configuration

"build": {
   "configurations": {
        "dev2": {

          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.dev2.ts"
            }
            /* You can add all other options here, such as aot, optimization, ... */
          ],
          "serviceWorker": true
        },

Then modify your serve section to add a new configuration as well, pointing to the dev2 build configuration you just declared

"serve":
      "configurations": {
        "dev2": {
          "browserTarget": "projectName:build:dev2"
        }

Then you can use ng serve -c dev2, which will use the dev2 config file

Highlight a word with jQuery

Here's a variation that ignores and preserves case:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

Set and Get Methods in java?

I don't see a simple answer to the second question (why) here. So here goes.

Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.

Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.

Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.

Best practice to validate null and empty collection in Java

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

How to convert/parse from String to char in java?

If your string contains exactly one character the simplest way to convert it to a character is probably to call the charAt method:

char c = s.charAt(0);

Python - 'ascii' codec can't decode byte

Always encode from unicode to bytes.
In this direction, you get to choose the encoding.

>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??

The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.

>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??

This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:

  • A unicode object is decoded already, you never want to call decode on it.
  • A bytestring object is encoded already, you never want to call encode on it.

Now, on seeing .encode on a byte string, Python 2 first tries to implicitly convert it to text (a unicode object). Similarly, on seeing .decode on a unicode string, Python 2 implicitly tries to convert it to bytes (a str object).

These implicit conversions are why you can get UnicodeDecodeError when you've called encode. It's because encoding usually accepts a parameter of type unicode; when receiving a str parameter, there's an implicit decoding into an object of type unicode before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder, giving you the decoding error inside an encoder.

In fact, in Python 3 the methods str.decode and bytes.encode don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.

...or whatever coding sys.getdefaultencoding() mentions; usually this is 'ascii'

css to make bootstrap navbar transparent

in bootstrap 3.3.7 (and 4.0 presumably), this works:

instead of:

<nav class="navbar navbar-inverse navbar-fixed-top">

use:

<nav class="navbar bg-transparent navbar-fixed-top">

no CSS required!

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

In C can a long printf statement be broken up into multiple lines?

The C compiler can glue adjacent string literals into one, like

printf("foo: %s "
       "bar: %d", foo, bar);

The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):

printf("foo %s \
bar: %d", foo, bar);

How to merge many PDF files into a single one?

There are lots of free tools that can do this.

I use PDFTK (a open source cross-platform command-line tool) for things like that.

How to print VARCHAR(MAX) using Print Statement?

Or simply:

PRINT SUBSTRING(@SQL_InsertQuery, 1, 8000)
PRINT SUBSTRING(@SQL_InsertQuery, 8001, 16000)

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

For Spring 5.2+ this works for me:

@PostMapping("/foo")
ResponseEntity<Void> foo(@PathVariable UUID fooId) {
    return fooService.findExam(fooId)
            .map(uri -> ResponseEntity.noContent().<Void>build())
            .orElse(ResponseEntity.notFound().build());
}

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

How to download/checkout a project from Google Code in Windows?

Another simple solution without the TortoiseSVN overhead is RapidSVN. It is a lightweight open-source SVN client that is easy to install and easy to use.

The Download SVN tool did also work quite well, but it had problems with SVN repositories that don't provide a web interface. RapidSVN works fine with those.

Open source face recognition for Android

Here are some links that I found on face recognition libraries.

Image Identification links:

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

set NODE_ENV=production & nodemon app/app.js

will cause NODE_ENV to contain a space at the end:

process.env.NODE_ENV == 'production'; //false
process.env.NODE_ENV == 'production '; //true

As mentioned in a comment here, use this instead:

NODE_ENV=production&& nodemon app/app.js

Passing string parameter in JavaScript function

Use this:

document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')

ajax jquery simple get request

var dataString = "flag=fetchmediaaudio&id="+id;

$.ajax
({
  type: "POST",
  url: "ajax.php",
  data: dataString,
  success: function(html)
  {
     alert(html);
  }
});

Check if all checkboxes are selected

I think the easiest way is checking for this condition:

$('.abc:checked').length == $('.abc').length

You could do it every time a new checkbox is checked:

$(".abc").change(function(){
    if ($('.abc:checked').length == $('.abc').length) {
       //do something
    }
});

How to set the default value for radio buttons in AngularJS?

<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
               <%=rs.getString(6).equals("male") ? "checked='checked'": "" %>

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

In my case I was unable to edit the hosts file because using a pc from the university.

I fixed the problem running rmiregistry in another port (instead of 1099) with:

rmiregistry <port>

and then running the server on that port.

It was basically an error caused by occupied port.

Could not load file or assembly '' or one of its dependencies

Okay this may sound very stupid, but heres how I solved the issue after trying out every other solution and spending a night on this stupid thing.

I was getting the same error with some DLL missing from Bin Folder. I tried to delete , get back up everything from Team Foundation Server but didn't work. Got a copy of Bin folder from my office-matelocal machine, and replaced it. It didn't work either. At last, I manually FTPed server, got the copy of DLL which was showing up as missing, and then it started showing up that next file in the file list sequence is missing.

So I ftped server Got all Bin Folder, Manually replaced each file one by one. (Not Ctrl + All and replace.. I tried : it didn't work.) And somehow it worked...

How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<T>>() {
            public Type getType() {
                return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
        }
    });
    return response;
}

public class MyParameterizedTypeImpl implements ParameterizedType {
    private ParameterizedType delegate;
    private Type[] actualTypeArguments;

    MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
        this.delegate = delegate;
        this.actualTypeArguments = actualTypeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return delegate.getRawType();
    }

    @Override
    public Type getOwnerType() {
        return delegate.getOwnerType();
    }

}

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Checking if a key exists in a JavaScript object?

It will return undefined.

_x000D_
_x000D_
var aa = {hello: "world"};_x000D_
alert( aa["hello"] );      // popup box with "world"_x000D_
alert( aa["goodbye"] );    // popup box with "undefined"
_x000D_
_x000D_
_x000D_

undefined is a special constant value. So you can say, e.g.

// note the three equal signs so that null won't be equal to undefined
if( aa["goodbye"] === undefined ) {
    // do something
}

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

// this works even if you have {"goodbye": undefined}
if( "goodbye" in aa ) {
    // do something
}

LINQ-to-SQL vs stored procedures?

LINQ is new and has its place. LINQ is not invented to replace stored procedure.

Here I will focus on some performance myths & CONS, just for "LINQ to SQL", of course I might be totally wrong ;-)

(1)People say LINQ statment can "cache" in SQL server, so it doesn't lose performance. Partially true. "LINQ to SQL" actually is the runtime translating LINQ syntax to TSQL statment. So from the performance perspective,a hard coded ADO.NET SQL statement has no difference than LINQ.

(2)Given an example, a customer service UI has a "account transfer" function. this function itself might update 10 DB tables and return some messages in one shot. With LINQ, you have to build a set of statements and send them as one batch to SQL server. the performance of this translated LINQ->TSQL batch can hardly match stored procedure. Reason? because you can tweak the smallest unit of the statement in Stored procedue by using the built-in SQL profiler and execution plan tool, you can not do this in LINQ.

The point is, when talking single DB table and small set of data CRUD, LINQ is as fast as SP. But for much more complicated logic, stored procedure is more performance tweakable.

(3)"LINQ to SQL" easily makes newbies to introduce performance hogs. Any senior TSQL guy can tell you when not to use CURSOR (Basically you should not use CURSOR in TSQL in most cases). With LINQ and the charming "foreach" loop with query, It's so easy for a newbie to write such code:

foreach(Customer c in query)
{
  c.Country = "Wonder Land";
}
ctx.SubmitChanges();

You can see this easy decent code is so attractive. But under the hood, .NET runtime just translate this to an update batch. If there are only 500 lines, this is 500 line TSQL batch; If there are million lines, this is a hit. Of course, experienced user won't use this way to do this job, but the point is, it's so easy to fall in this way.

Class constants in python

Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:

def module_register_class_constants(klass, attr_prefix):
    globals().update(
        (name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
    )

class Animal(object):
    SIZE_HUGE = "Huge"
    SIZE_BIG = "Big"

module_register_class_constants(Animal, "SIZE_")

class Horse(Animal):
    def printSize(self):
        print SIZE_BIG

An existing connection was forcibly closed by the remote host

This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.

    SocketError errorCode;
    int nBytesRec = socket.EndReceive(ar, out errorCode);
    if (errorCode != SocketError.Success)
    {
        nBytesRec = 0;
    }

Cannot read property 'map' of undefined

in my case it happens when I try add types to Promise.all handler:

Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));

If remove : [number, number], the error is gone.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

I had this issue and it was because the machine running the application isnt trusted for delegation on the domain by active directory. If it is a .net app running under an application pool identity DOMAIN_application.environment for example.. the identity can't make calls out to SQL unless the machine is trusted.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

low dpi is 0.75x dimensions of medium dpi

high dpi is 1.5x dimensions of medium dpi

extra high dpi is 2x dimensinons of medium dpi

It's a good practice to make all the images in vector based format so you can resize them easily using a vector design software like Illustrator etc..

Can't find file executable in your configured search path for gnc gcc compiler

Fistly, Code Blocks is not a compiler. It is just an integrated development environment.

So, you must show the path of your compiler at first, (if you dont have a compiler you have to download an install, it is not difficult to find. f.e. GCC is good one.) If code blocks could not find automatically the path of compiler it is an obligation to show it yourself.

But when you install, probably Code Blocks automatically find your compiler.

Enjoy.

How do I encode/decode HTML entities in Ruby?

I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.

Samples:

a = Nokogiri::HTML.parse "foo&nbsp;b&auml;r"    
a.text 
=> "foo bär"

or

a = Nokogiri::HTML.parse "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"

adding child nodes in treeview

It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:
treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode and add the children to it.

Try TreeView to get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...

I'm missing a whole lot of safety checks here!

Something like (untested):

private void addChildNode_Click(object sender, EventArgs e) {
  TreeNode ParentNode = treeView2.SelectedNode;  // for ease of debugging!
  if (ParentNode != null) {
    ParentNode.Nodes.Add("Name Of Node");
    treeView2.ExpandAll();   // so you can see what's been added              
    treeView2.Invalidate();  // requests a redraw
  }
}

How to assign a value to a TensorFlow variable?

So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:

other_variable = tf.get_variable("other_variable", dtype=tf.int32,
  initializer=tf.constant([23, 42]))

here i'm creating a variable as well as assigning it values at the same time

Import Excel Data into PostgreSQL 9.3

The typical answer is this:

  1. In Excel, File/Save As, select CSV, save your current sheet.

  2. transfer to a holding directory on the Pg server the postgres user can access

  3. in PostgreSQL:

    COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
    

But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:

  1. Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.

  2. Use CSV and the fdw_file to access it as a pseudo-table

  3. Use DBILink and DBD::Excel

  4. Write your own foreign data wrapper for reading Excel files.

The possibilities are literally endless....

how to filter out a null value from spark dataframe

There are two ways to do it: creating filter condition 1) Manually 2) Dynamically.

Sample DataFrame:

val df = spark.createDataFrame(Seq(
  (0, "a1", "b1", "c1", "d1"),
  (1, "a2", "b2", "c2", "d2"),
  (2, "a3", "b3", null, "d3"),
  (3, "a4", null, "c4", "d4"),
  (4, null, "b5", "c5", "d5")
)).toDF("id", "col1", "col2", "col3", "col4")

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
|  2|  a3|  b3|null|  d3|
|  3|  a4|null|  c4|  d4|
|  4|null|  b5|  c5|  d5|
+---+----+----+----+----+

1) Creating filter condition manually i.e. using DataFrame where or filter function

df.filter(col("col1").isNotNull && col("col2").isNotNull).show

or

df.where("col1 is not null and col2 is not null").show

Result:

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
|  2|  a3|  b3|null|  d3|
+---+----+----+----+----+

2) Creating filter condition dynamically: This is useful when we don't want any column to have null value and there are large number of columns, which is mostly the case.

To create the filter condition manually in these cases will waste a lot of time. In below code we are including all columns dynamically using map and reduce function on DataFrame columns:

val filterCond = df.columns.map(x=>col(x).isNotNull).reduce(_ && _)

How filterCond looks:

filterCond: org.apache.spark.sql.Column = (((((id IS NOT NULL) AND (col1 IS NOT NULL)) AND (col2 IS NOT NULL)) AND (col3 IS NOT NULL)) AND (col4 IS NOT NULL))

Filtering:

val filteredDf = df.filter(filterCond)

Result:

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  0|  a1|  b1|  c1|  d1|
|  1|  a2|  b2|  c2|  d2|
+---+----+----+----+----+

How to send password using sftp batch file

You mention batch files, am I correct then assuming that you're talking about a Windows system? If so you cannot use sshpass, and you will have to switch to a different option.

Two of such options, that follow diametrically opposite philosophies are:

  • psftp: command-line tool that you can call from within your batch scripts; psftp is part of the PuTTY package and you can find it here http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
  • Syncplify.me FTP Script: a scriptable FTP/S and SFTP client for Windows that allows you to store your password in encrypted "profile files"; check it out here http://www.syncplify.me/products/ftp-script/

Either way, switching from password to PKI authentication is strongly recommended.

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

How to add Active Directory user group as login in SQL Server

In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins and right-click New Login:

enter image description here

Then in the dialog box that pops up, pick the types of objects you want to see (Groups is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory) and then find your AD group.

enter image description here

You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!

Any member of that AD group can now login to SQL Server and use your database.

What is uintptr_t data type

It's an unsigned integer type exactly the size of a pointer. Whenever you need to do something unusual with a pointer - like for example invert all bits (don't ask why) you cast it to uintptr_t and manipulate it as a usual integer number, then cast back.

How do I extract the contents of an rpm?

For those who do not have rpm2cpio, here is the ancient rpm2cpio.sh script that extracts the payload from a *.rpm package.

Reposted for posterity … and the next generation.

Invoke like this: ./rpm2cpio.sh .rpm | cpio -dimv

#!/bin/sh

pkg=$1
if [ "$pkg" = "" -o ! -e "$pkg" ]; then
    echo "no package supplied" 1>&2
    exit 1
fi

leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "sig il: $il dl: $dl"

sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "hdr il: $il dl: $dl"

hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
EXTRACTOR="dd if=$pkg ibs=$o skip=1"

COMPRESSION=`($EXTRACTOR |file -) 2>/dev/null`
if echo $COMPRESSION |grep -q gzip; then
        DECOMPRESSOR=gunzip
elif echo $COMPRESSION |grep -q bzip2; then
        DECOMPRESSOR=bunzip2
elif echo $COMPRESSION |grep -iq xz; then # xz and XZ safe
        DECOMPRESSOR=unxz
elif echo $COMPRESSION |grep -q cpio; then
        DECOMPRESSOR=cat
else
        # Most versions of file don't support LZMA, therefore we assume
        # anything not detected is LZMA
        DECOMPRESSOR=`which unlzma 2>/dev/null`
        case "$DECOMPRESSOR" in
            /* ) ;;
            *  ) DECOMPRESSOR=`which lzmash 2>/dev/null`
             case "$DECOMPRESSOR" in
                     /* ) DECOMPRESSOR="lzmash -d -c" ;;
                     *  ) DECOMPRESSOR=cat ;;
                 esac
                 ;;
        esac
fi

$EXTRACTOR 2>/dev/null | $DECOMPRESSOR

MySQL with Node.js

node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented.

How to delete from multiple tables in MySQL?

The syntax looks right to me ... try to change it to use INNER JOIN ...

Have a look at this.

Right Align button in horizontal LinearLayout

I know this is old but here is another one in a Linear Layout would be:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">

<TextView
    android:id="@+id/lblExpenseCancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cancel"
    android:textColor="#404040"
    android:layout_marginLeft="10dp"
    android:textSize="20sp"
    android:layout_marginTop="9dp" />

<Button
    android:id="@+id/btnAddExpense"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:background="@drawable/stitch_button"
    android:layout_marginLeft="10dp"
    android:text="@string/add"
    android:layout_gravity="center_vertical|bottom|right|top"
    android:layout_marginRight="15dp" />

Please note the layout_gravity as opposed to just gravity.

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

The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.

This should work however (and doesn't need a join):

UPDATE sales
SET status='ACTIVE'
WHERE id IN (
  SELECT MIN(id) FROM sales
  GROUP BY saleprice, saledate
  HAVING COUNT(id) = 1
)

You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

Set object property using reflection

You can also do:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

where target is the object that will have its property set.

Compiling C++ on remote Linux machine - "clock skew detected" warning

According to user m9dhatter on LinuxQuestions.org:

"make" uses the time stamp of the file to determine if the file it is trying to compile is old or new. if your clock is bonked, it may have problems compiling.

if you try to modify files at another machine with a clock time ahead by a few minutes and transfer them to your machine and then try to compile it may cough up a warning that says the file was modified from the future. clock may be skewed or something to that effect ( cant really remember ). you could just ls to the offending file and do this:

#touch <filename of offending file>

Android Studio Emulator and "Process finished with exit code 0"

I had this issue in Android Studio 3.1 :

I only have on board graphics. Went to Tools -> AVD Manager -> (Edit this AVD) under Actions -> Emulated Performance (Graphics): select "Software GLES 2.0".

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

Copy struct to struct in C

copy structure in c you just need to assign the values as follow:

struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;

RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;

RTCclkBuffert=RTCclk1;

now RTCclkBuffert.hour will have value 5,

RTCclkBuffert.minute will have value 4

RTCclkBuffert.second will have value 3

Anchor links in Angularjs?

$anchorScroll is indeed the answer to this, but there's a much better way to use it in more recent versions of Angular.

Now, $anchorScroll accepts the hash as an optional argument, so you don't have to change $location.hash at all. (documentation)

This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set $location.hash(id), before $anchorScroll could do its magic.

Here is how to use it... first, in the directive or controller:

$scope.scrollTo = function (id) {
  $anchorScroll(id);  
}

and then in the view:

<a href="" ng-click="scrollTo(id)">Text</a>

Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):

  .run(function ($anchorScroll) {
      //this will make anchorScroll scroll to the div minus 50px
      $anchorScroll.yOffset = 50;
  });

How to set layout_weight attribute dynamically from code?

You can pass it in as part of the LinearLayout.LayoutParams constructor:

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT,
    1.0f
);
YOUR_VIEW.setLayoutParams(param);

The last parameter is the weight.

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue which was fixed following the instructions below

Test enabling “Access for less secure apps” (which just means the client/app doesn’t use OAuth 2.0 - https://oauth.net/2/) for the account you are trying to access. It's found in the account settings on the Security tab, Account permissions (not available to accounts with 2-step verification enabled): https://support.google.com/accounts/answer/6010255?hl=en

original link for the answer: https://support.google.com/mail/thread/5621336?msgid=6292199

Fatal error: Class 'Illuminate\Foundation\Application' not found

Just in case I trip over this error in 2 weeks again... My case: Checkout an existing project via git and pull in all dependencies via composer. Came down to the same error listed within the title of this post.

Solution:

composer dump-autoload
composer install --no-scripts

make sure everything works now as expected (no errors!)

composer update

Sending Multipart File as POST parameters with RestTemplate requests

You may simply use MultipartHttpServletRequest

Example:

 @RequestMapping(value={"/upload"}, method = RequestMethod.POST,produces = "text/html; charset=utf-8")
 @ResponseBody
 public String upload(MultipartHttpServletRequest request /*@RequestBody MultipartFile file*/){
    String responseMessage = "OK";
    MultipartFile file = request.getFile("file");
    String param = request.getParameter("param");
    try {
        System.out.println(file.getOriginalFilename());
        System.out.println("some param = "+param);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
        // read file
    }
    catch(Exception ex){
        ex.printStackTrace();
        responseMessage = "fail";
    }
     return responseMessage;
}

Where parameters names in request.getParameter() must be same with corresponding frontend names.

Note, that file extracted via getFile() while other additional parameters extracted via getParameter()

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

android - listview get item view by position

Listview lv = (ListView) findViewById(R.id.previewlist);

    final BaseAdapter adapter = new PreviewAdapter(this, name, age);

    confirm.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            View view = null;

            String value;
            for (int i = 0; i < adapter.getCount(); i++) {

                view = adapter.getView(i, view, lv);

                Textview et = (TextView) view.findViewById(R.id.passfare);


                value=et.getText().toString();

                 Toast.makeText(getApplicationContext(), value,
                 Toast.LENGTH_SHORT).show();
            }



        }
    });

How do I download a file using VBA (without Internet Explorer)

Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub Example()
    DownloadFile$ = "someFile.ext" 'here the name with extension
    URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
    LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
    MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub

Source

I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.

This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!

How to change the floating label color of TextInputLayout

In the latest version of the support library (23.0.0+), TextInputLayout takes the following attribute in XML to edit the floating label color: android:textColorHint="@color/white"

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Better/Faster to Loop through set or list?

Just use a set. Its semantics are exactly what you want: a collection of unique items.

Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.

How to add a tooltip to an svg graphic?

You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/

Operation Not Permitted when on root - El Capitan (rootless disabled)

Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:

csrutil disable
reboot 

This is a result of System Integrity Protection. More info here.

EDIT

If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.

However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.

PHP how to get local IP of system

It is very simple and above answers are complicating things. Simply you can get both local and public ip addresses using this method.

   <?php 
$publicIP = file_get_contents("http://ipecho.net/plain");
echo $publicIP;

$localIp = gethostbyname(gethostname());
echo $localIp;

?>

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

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

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

Get all child elements

Here is a code to get the child elements (In java):

String childTag = childElement.getTagName();
if(childTag.equals("html")) 
{
    return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath("..")); 
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) 
{
    WebElement childrenElement = childrenElements.get(i);
    String childrenElementTag = childrenElement.getTagName();
    if(childTag.equals(childrenElementTag)) 
    {
        count++;
    }
 }

Detect click inside/outside of element with single event handler

If you want to add a click listener in chrome console, use this

document.querySelectorAll("label")[6].parentElement.onclick = () => {console.log('label clicked');}

Create a new cmd.exe window from within another cmd.exe prompt

You can just type these 3 commands from command prompt:

  1. start

  2. start cmd

  3. start cmd.exe

Defining array with multiple types in TypeScript

Im using this version:

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

It is a little bit similar to the other suggestions but still easy and quite good to remember.

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

How do I Merge two Arrays in VBA?

Unfortunately, the Array type in VB6 didn't have all that many razzmatazz features. You are pretty much going to have to just iterate through the arrays and insert them manually into the third

Assuming both arrays are of the same length

Dim arr1() As Variant
Dim arr2() As Variant
Dim arr3() As Variant

arr1() = Array("A", 1, "B", 2)
arr2() = Array("C", 3, "D", 4)

ReDim arr3(UBound(arr1) + UBound(arr2) + 1)

Dim i As Integer
For i = 0 To UBound(arr1)
    arr3(i * 2) = arr1(i)
    arr3(i * 2 + 1) = arr2(i)
Next i

Updated: Fixed the code. Sorry about the previous buggy version. Took me a few minutes to get access to a VB6 compiler to check it.

How can I set the aspect ratio in matplotlib?

After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at

https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl

With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:

ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)

The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.

Thanks for all great answers received - especially @Yann's which will remain the winner.

How to communicate between Docker containers via "hostname"

As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.

If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address.

Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:

wordpress:                                                                         
  image: wordpress:4.1                                                             
  stateful: true                                                                   
  ports:                                                                           
    - 80:80                                                                      
  links:                                                                           
    - mysql:wordpress-mysql                                                        
  environment:                                                                     
    - WORDPRESS_DB_HOST=wordpress-mysql.kontena.local                              
    - WORDPRESS_DB_PASSWORD=secret                                                 
mysql:                                                                             
  image: mariadb:5.5                                                               
  stateful: true                                                                   
  environment:                                                                     
    - MYSQL_ROOT_PASSWORD=secret

Why should hash functions use a prime number modulus?

Primes are used because you have good chances of obtaining a unique value for a typical hash-function which uses polynomials modulo P. Say, you use such hash-function for strings of length <= N, and you have a collision. That means that 2 different polynomials produce the same value modulo P. The difference of those polynomials is again a polynomial of the same degree N (or less). It has no more than N roots (this is here the nature of math shows itself, since this claim is only true for a polynomial over a field => prime number). So if N is much less than P, you are likely not to have a collision. After that, experiment can probably show that 37 is big enough to avoid collisions for a hash-table of strings which have length 5-10, and is small enough to use for calculations.

What are the differences between if, else, and else if?

you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions

  • go with an umbrella
  • go without an umbrella

and both the two actions are bound to one condition, i.e is it raining?

now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

Determine direct shared object dependencies of a Linux binary?

If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…

You may use ldd command. ldd - print shared library dependencies

How to know a Pod's own IP address from inside a container in the Pod?

You could use

kubectl describe pod `hostname` | grep IP | sed -E 's/IP:[[:space:]]+//'

which is based on what @mibbit suggested.

This takes the following facts into account:

How can I display just a portion of an image in HTML/CSS?

adjust the background-position to move background images in different positions of the div

div { 
       background-image: url('image url')
       background-position: 0 -250px; 
    }

Display image as grayscale using matplotlib

The following code will load an image from a file image.png and will display it as grayscale.

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()

If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'.

How to retry after exception?

Using while and a counter:

count = 1
while count <= 3:  # try 3 times
    try:
        # do_the_logic()
        break
    except SomeSpecificException as e:
        # If trying 3rd time and still error?? 
        # Just throw the error- we don't have anything to hide :)
        if count == 3:
            raise
        count += 1

function to return a string in java

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

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

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

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

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

Typescript sleep

For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

Read response headers from API response - Angular 5 + TypeScript

In my case in the POST response I want to have the authorization header because I was having the JWT Token in it. So what I read from this post is the header I we want should be added as an Expose Header from the back-end. So what I did was added the Authorization header to my Exposed Header like this in my filter class.

response.addHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Custom-header");
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); // HEADER_STRING == Authorization

And at my Angular Side

In the Component.

this.authenticationService.login(this.f.email.value, this.f.password.value)
  .pipe(first())
  .subscribe(
    (data: HttpResponse<any>) => {
      console.log(data.headers.get('authorization'));
    },
    error => {
      this.loading = false;
    });

At my Service Side.

return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password},
  {observe: 'response' as 'body'})
  .pipe(map(user => {
       return user;
  }));

What does Ruby have that Python doesn't, and vice versa?

Ruby has a line by line loop over input files (the '-n' flag) from the commandline so it can be used like AWK. This Ruby one-liner:

ruby -ne 'END {puts $.}'

will count lines like the AWK one-liner:

awk 'END{print NR}'

Ruby gets feature this through Perl, which took it from AWK as a way of getting sysadmins on board with Perl without having to change the way they do things.

Conditional formatting based on another cell's value

One more example:

If you have Column from A to D, and need to highlight the whole line (e.g. from A to D) if B is "Complete", then you can do it following:

"Custom formula is":  =$B:$B="Completed" 
Background Color:     red 
Range:                A:D

Of course, you can change Range to A:T if you have more columns.

If B contains "Complete", use search as following:

"Custom formula is":  =search("Completed",$B:$B) 
Background Color:     red 
Range:                A:D

Javascript one line If...else...else if statement

I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:

var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));

Example:

var answer = value === 'foo' ? 1 :
    (value === 'bar' ? 2 : 
        (value === 'foobar' ? 3 : 0));

Javascript | Set all values of an array

Actually, you can use this perfect approach:

let arr = Array.apply(null, Array(5)).map(() => 0);
// [0, 0, 0, 0, 0]

This code will create array and fill it with zeroes. Or just:

let arr = new Array(5).fill(0)

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting the same error today:

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

What I did:

  • I simply updated all my dependencies to 27.1.1 instead of 26.1.0
  • Also, updated my compileSdkVersion 27 and targetSdkVersion 27 which were 26 earlier

And com.android.support:support-annotations error was gone!

For Ref:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Write a file in external storage in Android

You should read the documentation on storing stuff externally on Android. There's a multitude of problems that could exist with your current code, and I think going over the documentation might help you iron them out.

Android error: Failed to install *.apk on device *: timeout

I have encountered the same problem and tried to change the ADB connection timeout. That did not work. I switched between my PC's USB ports (front -> back) and it fixed the problem!!!

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Assuming the value is nvarchar type for that only we are using N''

denied: requested access to the resource is denied : docker

Not sure what happened to docker hub, but none of the solutions posted worked for me. Here is the work-around that ended up working for me as of Jan-2018:

  1. Go to hub.docker.com and change your repository to private
  2. In your shell do:

docker images

REPOSITORY TAG IMAGE ID CREATED SIZE verse_gapminder_gsl latest 023ab91c6291 3 minutes ago 1.975 GB verse_gapminder latest bb38976d03cf 13 minutes ago 1.955 GB rocker/verse latest 0168d115f220 3 days ago 1.954 GB

docker tag bb38976d03cf dockhubusername/verse_gapminder:mytag

docker login docker.io

docker push dockhubusername/verse_gapminder:mytag

  1. Go back to docker hub and change repo back to public. That worked for me.

DropDownList in MVC 4 with Razor

_x000D_
_x000D_
List<tblstatu> status = new List<tblstatu>();_x000D_
            status = psobj.getstatus();_x000D_
            model.statuslist = status;_x000D_
            model.statusid = status.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.StatusId.ToString(),_x000D_
                Text = x.StatusName_x000D_
            });_x000D_
_x000D_
_x000D_
  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })
_x000D_
_x000D_
_x000D_

Eclipse won't compile/run java file

Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.

If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.

Setting Action Bar title and subtitle

The title for the actionbar could be in the AndroidManifest, here:

<activity 
    . . .
          android:label="string resource" 
    . . .
</activity>

android:label A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It's often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is used instead (see the element's label attribute). The activity's label — whether set here or by the element — is also the default label for all the activity's intent filters (see the element's label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you're developing the application, it can also be set as a raw string.

What is the email subject length limit?

RFC2322 states that the subject header "has no length restriction"

but to produce long headers but you need to split it across multiple lines, a process called "folding".

subject is defined as "unstructured" in RFC 5322

here's some quotes ([...] indicate stuff i omitted)

3.6.5. Informational Fields
  The informational fields are all optional.  The "Subject:" and
  "Comments:" fields are unstructured fields as defined in section
  2.2.1, [...]

2.2.1. Unstructured Header Field Bodies
  Some field bodies in this specification are defined simply as
  "unstructured" (which is specified in section 3.2.5 as any printable
  US-ASCII characters plus white space characters) with no further
  restrictions.  These are referred to as unstructured field bodies.
  Semantically, unstructured field bodies are simply to be treated as a
  single line of characters with no further processing (except for
  "folding" and "unfolding" as described in section 2.2.3).

2.2.3  [...]  An unfolded header field has no length restriction and
  therefore may be indeterminately long.

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close() method:

>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor

The line del f deletes the last reference to the file object, causing its destructor file.__del__ to be called. The internal state of the file object indicates the file is still open since f.close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

Since the implementation of os.system() does not create any Python file objects, it does not seem likely that the system() call is the origin of the error. Maybe you could show a bit more code?

How to remove white space characters from a string in SQL Server

Looks like the invisible character -

ALT+255

Try this

select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE 
from DimProducts
where ProductAlternateKey  like '46783815%'

Raj

Edit: Based on ASCII() results, try ALT+10 - use numeric keypad

Ternary operator in AngularJS templates

For texts in angular template (userType is property of $scope, like $scope.userType):

<span>
  {{userType=='admin' ? 'Edit' : 'Show'}}
</span>

How to wrap text in textview in Android

By setting android:maxEms to a given value together with android:layout_weight="1" will cause the TextView to wrap once it reaches the given length of the ems.

Get value of a string after last slash in JavaScript

light weigh

string.substring(start,end)

where

start = Required. The position where to start the extraction. First character is at index 0`.

end = Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string.

    var string = "var1/var2/var3";

    start   = string.lastIndexOf('/');  //console.log(start); o/p:- 9
    end     = string.length;            //console.log(end);   o/p:- 14

    var string_before_last_slash = string.substring(0, start);
    console.log(string_before_last_slash);//o/p:- var1/var2

    var string_after_last_slash = string.substring(start+1, end);
    console.log(string_after_last_slash);//o/p:- var3

OR

    var string_after_last_slash = string.substring(start+1);
    console.log(string_after_last_slash);//o/p:- var3

java.net.URL read stream to byte[]

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

How do I check in python if an element of a list is empty?

Unlike in some laguages, empty is not a keyword in Python. Python lists are constructed form the ground up, so if element i has a value, then element i-1 has a value, for all i > 0.

To do an equality check, you usually use either the == comparison operator.

>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True

Here's a link to the strip method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.

How to use this boolean in an if statement?

if(stop == true)

or

if(stop)

= is for assignment.

== is for checking condition.

if(stop = true) 

It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.

C# Generics and Type Checking

By default know there is not a great way. Awhile back I got frustrated with this and wrote a little utility class that helped out a bit and made the syntax a bit cleaner. Essentially it turns the code into

TypeSwitcher.Do(clause[0],
  TypeSwitch.Case<int>(x => ...),  // x is an int
  TypeSwitch.Case<decimal>(d => ...), // d is a decimal 
  TypeSwitch.Case<string>(s => ...)); // s is a string

Full blog post and details on the implementation are available here

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

We can mute it in this way (device and simulator need different values):

Add the Name OS_ACTIVITY_MODE and the Value ${DEBUG_ACTIVITY_MODE} and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).

enter image description here

Add User-Defined Setting DEBUG_ACTIVITY_MODE, then add Any iOS Simulator SDK for Debug and set it's value to disable (in Project -> Build settings -> + -> User-Defined Setting)

enter image description here

What is the cleanest way to ssh and run multiple commands in Bash?

How about a Bash Here Document:

ssh otherhost << EOF
  ls some_folder; 
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

To avoid the problems mentioned by @Globalz in the comments, you may be able to (depending what you're doing on the remote site) get away with replacing the first line with

ssh otherhost /bin/bash << EOF

Note that you can do variable substitution in the Here document, but you may have to deal with quoting issues. For instance, if you quote the "limit string" (ie. EOF in the above), then you can't do variable substitutions. But without quoting the limit string, variables are substituted. For example, if you have defined $NAME above in your shell script, you could do

ssh otherhost /bin/bash << EOF
touch "/tmp/${NAME}"
EOF

and it would create a file on the destination otherhost with the name of whatever you'd assigned to $NAME. Other rules about shell script quoting also apply, but are too complicated to go into here.

How to call a function from a string stored in a variable?

What I learnt from this question and the answers. Thanks all!

Let say I have these variables and functions:

$functionName1 = "sayHello";
$functionName2 = "sayHelloTo";
$functionName3 = "saySomethingTo";

$friend = "John";
$datas = array(
    "something"=>"how are you?",
    "to"=>"Sarah"
);

function sayHello()
{
echo "Hello!";
}

function sayHelloTo($to)
{
echo "Dear $to, hello!";
}

function saySomethingTo($something, $to)
{
echo "Dear $to, $something";
}
  1. To call function without arguments

    // Calling sayHello()
    call_user_func($functionName1); 
    

    Hello!

  2. To call function with 1 argument

    // Calling sayHelloTo("John")
    call_user_func($functionName2, $friend);
    

    Dear John, hello!

  3. To call function with 1 or more arguments This will be useful if you are dynamically calling your functions and each function have different number of arguments. This is my case that I have been looking for (and solved). call_user_func_array is the key

    // You can add your arguments
    // 1. statically by hard-code, 
    $arguments[0] = "how are you?"; // my $something
    $arguments[1] = "Sarah"; // my $to
    
    // 2. OR dynamically using foreach
    $arguments = NULL;
    foreach($datas as $data) 
    {
        $arguments[] = $data;
    }
    
    // Calling saySomethingTo("how are you?", "Sarah")
    call_user_func_array($functionName3, $arguments);
    

    Dear Sarah, how are you?

Yay bye!

How to declare a variable in MySQL?

SET

SET @var_name = value 

OR

SET @var := value

both operators = and := are accepted


SELECT

SELECT col1, @var_name := col2 from tb_name WHERE "conditon";

if multiple record sets found only the last value in col2 is keep (override);

SELECT col1, col2 INTO @var_name, col3 FROM .....

in this case the result of select is not containing col2 values


Ex both methods used

-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations

...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col =  IFNULL( @NR, 0 ) + 1;
...

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

CSS transition between left -> right and top -> bottom positions

For elements with dynamic width it's possible to use transform: translateX(-100%); to counter the horizontal percentage value. This leads to two possible solutions:

1. Option: moving the element in the entire viewport:

Transition from:

transform: translateX(0);

to

transform: translateX(calc(100vw - 100%));

_x000D_
_x000D_
#viewportPendulum {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateX(calc(100vw - 100%));_x000D_
  }_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
_x000D_
_x000D_

2. Option: moving the element in the parent container:

Transition from:

transform: translateX(0);
left: 0;

to

left: 100%;
transform: translateX(-100%);

_x000D_
_x000D_
#parentPendulum {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  animation: 2s ease-in-out infinite alternate swingParent;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
    left: 0;_x000D_
  }_x000D_
  to {_x000D_
    left: 100%;_x000D_
    transform: translateX(-100%);_x000D_
  }_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2rem 0;_x000D_
  margin: 2rem 15%;_x000D_
  background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Demo on Codepen

Note: This approach can easily be extended to work for vertical positioning. Visit example here.

How do I remove duplicates from a C# array?

Below is an simple logic in java you traverse elements of array twice and if you see any same element you assign zero to it plus you don't touch the index of element you are comparing.

import java.util.*;
class removeDuplicate{
int [] y ;

public removeDuplicate(int[] array){
    y=array;

    for(int b=0;b<y.length;b++){
        int temp = y[b];
        for(int v=0;v<y.length;v++){
            if( b!=v && temp==y[v]){
                y[v]=0;
            }
        }
    }
}

Git copy file preserving history

Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.

The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).

So in git this is not a matter of how you commit your changes but how you look at the committed changes later.

Center a H1 tag inside a DIV

On the hX tag

width: 100px;
margin-left: auto;
margin-right: auto;

Is there a native jQuery function to switch elements?

You shouldn't need two clones, one will do. Taking Paolo Bergantino answer we have:

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        $(to).replaceWith(this);
        $(this).replaceWith(copy_to);
    });
};

Should be quicker. Passing in the smaller of the two elements should also speed things up.

How to configure log4j with a properties file

just set -Dlog4j.configuration=file:log4j.properties worked for me.

log4j then looks for the file log4j.properties in the current working directory of the application.

Remember that log4j.configuration is a URL specification, so add 'file:' in front of your log4j.properties filename if you want to refer to a regular file on the filesystem, i.e. a file not on the classpath!

Initially I specified -Dlog4j.configuration=log4j.properties. However that only works if log4j.properties is on the classpath. When I copied log4j.properties to main/resources in my project and rebuild so that it was copied to the target directory (maven project) this worked as well (or you could package your log4j.properties in your project jars, but that would not allow the user to edit the logger configuration!).

Is it possible to remove the focus from a text input when a page loads?

A jQuery solution would be something like:

$(function () {
    $('input').blur();
});

Spring Boot REST service exception handling

What about this code ? I use a fallback request mapping to catch 404 errors.

@Controller
@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        //If exception has a ResponseStatus annotation then use its response code
        ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);

        return buildModelAndViewErrorPage(request, response, ex, responseStatusAnnotation != null ? responseStatusAnnotation.value() : HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @RequestMapping("*")
    public ModelAndView fallbackHandler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return buildModelAndViewErrorPage(request, response, null, HttpStatus.NOT_FOUND);
    }

    private ModelAndView buildModelAndViewErrorPage(HttpServletRequest request, HttpServletResponse response, Exception ex, HttpStatus httpStatus) {
        response.setStatus(httpStatus.value());

        ModelAndView mav = new ModelAndView("error.html");
        if (ex != null) {
            mav.addObject("title", ex);
        }
        mav.addObject("content", request.getRequestURL());
        return mav;
    }

}

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

Platform.runLater and Task in JavaFX

It can now be changed to lambda version

@Override
public void actionPerformed(ActionEvent e) {
    Platform.runLater(() -> {
        try {
            //an event with a button maybe
            System.out.println("button is clicked");
        } catch (IOException | COSVisitorException ex) {
            Exceptions.printStackTrace(ex);
        }
    });
}

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Select * from myTable m
where m.status not like 'Done%' 
and m.status not like 'Finished except%'
and m.status not like 'In Progress%'

How to Programmatically Add Views to Views

The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.

All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild() method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].

Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:

Step 1:

In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".

Step 2 Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

</TextView>

BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.

android:layout_width="wrap_content"
android:layout_height="wrap_content"

If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.

Step 3

In your onCreate method, do this :

FrameLayout frameLayout = findViewById(R.id.container);
                TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
                frameLayout.addView(textView);

(Note that setting last parameter of findViewById to null and adding view by calling addView() on container view (frameLayout) is same as simply attaching the inflated view by passing true in 3rd parameter of findViewById(). For more, see this.)

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Though I'm using Mac OS 10.9, this solution may work for someone else as well, perhaps on Ubuntu.

In the XAMPP console, I only found that phpMyAdmin started working again after restarting everything including the Apache Web Server.

No problemo, now.

MySQL "between" clause not inclusive?

select * from person where dob between '2011-01-01 00:00:00' and '2011-01-31 23:59:59'

Android Firebase, simply get one child object's data

I store my data this way:

accountsTable ->
  key1 -> account1
  key2 -> account2

in order to get object data:

accountsDb = mDatabase.child("accountsTable");

accountsDb.child("some   key").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {

                    try{

                        Account account  = snapshot.getChildren().iterator().next()
                                  .getValue(Account.class);


                    } catch (Throwable e) {
                        MyLogger.error(this, "onCreate eror", e);
                    }
                }
                @Override public void onCancelled(DatabaseError error) { }
            });

How to ignore the certificate check when ssl

Tip: You can also use this method to track certificates that are due to expire soon. This can save your bacon if you discover a cert that is about to expire and can get it fixed in time. Good also for third party companies - for us this is DHL / FedEx. DHL just let a cert expire which is screwing us up 3 days before Thanksgiving. Fortunately I'm around to fix it ... this time!

    private static DateTime? _nextCertWarning;
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    {
        if (error == SslPolicyErrors.None)
        {
            var cert2 = cert as X509Certificate2;
            if (cert2 != null)
            { 
                // If cert expires within 2 days send an alert every 2 hours
                if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
                {
                    if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
                    {
                        _nextCertWarning = DateTime.Now.AddHours(2);

                        ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString());   // this is my own function
                    }
                }
            }

            return true;
        }
        else
        {
            switch (cert.GetCertHashString())
            {
                // Machine certs - SELF SIGNED
                case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":    

                    return true;

                default:
                    ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
                    return false;
            }
        }
    }

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

I wasted couple of hours on the same issue. In my case, I had to reset_index() of a dataframe before using apply function. Before merging, or looking up from another indexed dataset, you need to reset the index as 1 dataset can have only 1 Index.

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

Print a string as hex bytes?

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) - more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Xcode Project vs. Xcode Workspace - Differences

Xcode Workspace vs Project

  1. What is the difference between the two of them?

Workspace is a set of projects

  1. What are they responsible for?

Workspace is responsible for dependencies between projects. Project is responsible for the source code.

  1. Which one of them should I work with when I'm developing my Apps in team/alone?

You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.

  1. Is there anything else I should be aware of in matter of these two files?

A competitor of workspace is cross-project references[About]

[Xcode components]

How to initialize a variable of date type in java?

java.util.Date constructor with parameters like new Date(int year, int month, int date, int hrs, int min). is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.

Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();

Notice that month number starts from 0

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Difference between logical addresses, and physical addresses?

A logical address is a reference to memory location independent of the current assignment of data to memory. A physical address or absolute address is an actual location in main memory.

It is in chapter 7.2 of Stallings.

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Downloading images with node.js

var fs = require('fs'),
http = require('http'),
https = require('https');

var Stream = require('stream').Transform;

var downloadImageToUrl = (url, filename, callback) => {

    var client = http;
    if (url.toString().indexOf("https") === 0){
      client = https;
     }

    client.request(url, function(response) {                                        
      var data = new Stream();                                                    

      response.on('data', function(chunk) {                                       
         data.push(chunk);                                                         
      });                                                                         

      response.on('end', function() {                                             
         fs.writeFileSync(filename, data.read());                               
      });                                                                         
   }).end();
};

downloadImageToUrl('https://www.google.com/images/srpr/logo11w.png', 'public/uploads/users/abc.jpg');

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Adding placeholder text to textbox

Let's extend the TextBox with PlcaeHoldText and PlaceHoldBackround. I stripped some code form my project.

say goodbye to Grid or Canvas!

<TextBox x:Class="VcpkgGui.View.PlaceHoldedTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:VcpkgGui.View"
             mc:Ignorable="d"
             Name="placeHoldTextBox"
             TextAlignment="Left"
         >
    <TextBox.Resources>
        <local:FrameworkWidthConverter x:Key="getElemWidth"/>
        <local:FrameworkHeightConverter x:Key="getElemHeight"/>
        <VisualBrush x:Key="PlaceHoldTextBrush" TileMode="None" Stretch="None" AlignmentX="Left" AlignmentY="Center" Opacity="1">
            <VisualBrush.Visual>
                <Border Background="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldBackground}"
                        BorderThickness="0"
                        Margin="0,0,0,0"
                        Width="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemWidth}}"
                        Height="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemHeight}}"
                        >
                    <Label Content="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldText}"
                           Background="Transparent"
                           Foreground="#88000000"
                           HorizontalAlignment="Stretch"
                           VerticalAlignment="Stretch"
                           HorizontalContentAlignment="Left"
                           VerticalContentAlignment="Center"
                           ClipToBounds="True"
                           Padding="0,0,0,0"
                           FontSize="14"
                           FontStyle="Normal"
                           Opacity="1"/>
                </Border>
            </VisualBrush.Visual>
        </VisualBrush>
    </TextBox.Resources>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Text" Value="{x:Null}">
                    <Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
                </Trigger>
                <Trigger Property="Text" Value="">
                    <Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace VcpkgGui.View
{
    /// <summary>
    /// PlaceHoldedTextBox.xaml ?????
    /// </summary>
    public partial class PlaceHoldedTextBox : TextBox
    {

        public string PlaceHoldText
        {
            get { return (string)GetValue(PlaceHoldTextProperty); }
            set { SetValue(PlaceHoldTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PlaceHolderText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PlaceHoldTextProperty =
            DependencyProperty.Register("PlaceHoldText", typeof(string), typeof(PlaceHoldedTextBox), new PropertyMetadata(string.Empty));



        public Brush PlaceHoldBackground
        {
            get { return (Brush)GetValue(PlaceHoldBackgroundProperty); }
            set { SetValue(PlaceHoldBackgroundProperty, value); }
        }

        public static readonly DependencyProperty PlaceHoldBackgroundProperty =
            DependencyProperty.Register(nameof(PlaceHoldBackground), typeof(Brush), typeof(PlaceHoldedTextBox), new PropertyMetadata(Brushes.White));

        public PlaceHoldedTextBox() :base()
        {
            InitializeComponent();
        }
    }

    [ValueConversion(typeof(FrameworkElement), typeof(double))]
    internal class FrameworkWidthConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value is FrameworkElement elem)
                return double.IsNaN(elem.Width) ? elem.ActualWidth : elem.Width;
            else
                return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    [ValueConversion(typeof(FrameworkElement), typeof(double))]
    internal class FrameworkHeightConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is FrameworkElement elem)
                return double.IsNaN(elem.Height) ? elem.ActualHeight : elem.Height;
            else
                return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

}

php string to int

Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)

intval(str_replace(" ", "", $b))

CSS media query to target iPad and iPad only?

I am a bit late to answer this but none of the above worked for me.

This is what worked for me

@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
    //your styles here
   }

JSON to pandas DataFrame

Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.

# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize

class DFConverter:

    #Converts the input JSON to a DataFrame
    def convertToDF(self,dfJSON):
        return(json_normalize(dfJSON))

    #Converts the input DataFrame to JSON 
    def convertToJSON(self, df):
        resultJSON = df.to_json(orient='records')
        return(resultJSON)

How to truncate the time on a DateTime object in Python?

>>> import datetime
>>> dt = datetime.datetime.now()
>>> datetime.datetime.date(dt)
datetime.date(2019, 4, 2)

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

Android - How to download a file from a webserver

Starting from api level 11 or Honeycomb doing network operations on main thread is forbidden. Use thread or asynctask. For more info visit https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

How to insert new cell into UITableView in Swift

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

    yourArray.append(4)

    tableView.beginUpdates()
    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
    tableView.endUpdates()

How to get the selected item from ListView?

MyClass selItem = (MyClass) myList.getSelectedItem(); //

You never instantiated your class.

File being used by another process after using File.Create()

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

Reverse ip, find domain names on ip address

This worked for me to get domain in intranet

https://gist.github.com/jrothmanshore/2656003

It's a powershell script. Run it in PowerShell

.\ip_lookup.ps1 <ip>

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

Get Selected Item Using Checkbox in Listview

make the checkbox non-focusable, and on list-item click do this, here codevalue is the position.

    Arraylist<Integer> selectedschools=new Arraylist<Integer>();

    lvPickSchool.setOnItemClickListener(new AdapterView.OnItemClickListener() 
  {

   @Override
        public void onItemClick(AdapterView<?> parent, View view, int codevalue, long id)
   {
                      CheckBox cb = (CheckBox) view.findViewById(R.id.cbVisitingStatus);

            cb.setChecked(!cb.isChecked());
            if(cb.isChecked())
            {

                if(!selectedschool.contains(codevaule))
                {
                    selectedschool.add(codevaule);
                }
            }
            else
            {
                if(selectedschool.contains(codevaule))
                {
                    selectedschool.remove(codevaule);
                }
            }
        }
    });

Show just the current branch in Git

I guess this should be quick and can be used with a Python API:

git branch --contains HEAD
* master

Calling multiple JavaScript functions on a button click

Because you're returning from the first method call, the second doesn't execute.

Try something like

OnClientClick="var b = validateView();ShowDiv1(); return b"

or reverse the situation,

OnClientClick="ShowDiv1();return validateView();"

or if there is a dependency of div1 on the validation routine.

OnClientClick="var b = validateView(); if (b) ShowDiv1(); return b"

What might be best is to encapsulate multiple inline statements into a mini function like so, to simplify the call:

// change logic to suit taste
function clicked()  {
    var b = validateView(); 
    if (b) 
        ShowDiv1()
    return b;
}

and then

OnClientClick="return clicked();"

What is an idiomatic way of representing enums in Go?

Quoting from the language specs:Iota

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:

const (  // iota is reset to 0
        c0 = iota  // c0 == 0
        c1 = iota  // c1 == 1
        c2 = iota  // c2 == 2
)

const (
        a = 1 << iota  // a == 1 (iota has been reset)
        b = 1 << iota  // b == 2
        c = 1 << iota  // c == 4
)

const (
        u         = iota * 42  // u == 0     (untyped integer constant)
        v float64 = iota * 42  // v == 42.0  (float64 constant)
        w         = iota * 42  // w == 84    (untyped integer constant)
)

const x = iota  // x == 0 (iota has been reset)
const y = iota  // y == 0 (iota has been reset)

Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:

const (
        bit0, mask0 = 1 << iota, 1<<iota - 1  // bit0 == 1, mask0 == 0
        bit1, mask1                           // bit1 == 2, mask1 == 1
        _, _                                  // skips iota == 2
        bit3, mask3                           // bit3 == 8, mask3 == 7
)

This last example exploits the implicit repetition of the last non-empty expression list.


So your code might be like

const (
        A = iota
        C
        T
        G
)

or

type Base int

const (
        A Base = iota
        C
        T
        G
)

if you want bases to be a separate type from int.

Differentiate between function overloading and function overriding

In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.

Static method in a generic class?

It is possible to do what you want by using the syntax for generic methods when declaring your doIt() method (notice the addition of <T> between static and void in the method signature of doIt()):

class Clazz<T> {
  static <T> void doIt(T object) {
    // shake that booty
  }
}

I got Eclipse editor to accept the above code without the Cannot make a static reference to the non-static type T error and then expanded it to the following working program (complete with somewhat age-appropriate cultural reference):

public class Clazz<T> {
  static <T> void doIt(T object) {
    System.out.println("shake that booty '" + object.getClass().toString()
                       + "' !!!");
  }

  private static class KC {
  }

  private static class SunshineBand {
  }

  public static void main(String args[]) {
    KC kc = new KC();
    SunshineBand sunshineBand = new SunshineBand();
    Clazz.doIt(kc);
    Clazz.doIt(sunshineBand);
  }
}

Which prints these lines to the console when I run it:

shake that booty 'class com.eclipseoptions.datamanager.Clazz$KC' !!!
shake that booty 'class com.eclipseoptions.datamanager.Clazz$SunshineBand' !!!

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Try to use

https://www.youtube.com/embed/YOUR_VIDEO_CODE

You can find all embeded code in 'Embeded Code' section and that looks like this

<iframe width="560" height="315"  src="https://www.youtube.com/embed/YOUR_VIDEO_CODE" frameborder="0" allowfullscreen></iframe>

Java String new line

Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).

  • For Linux and Mac, we can use "\n".
  • For Windows, we can use "\r\n".

Sample:

System.out.println("I\r\nam\r\na\r\nboy");

Result:
output

It worked for me.

Compiled vs. Interpreted Languages

A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?

Other languages, which are compiled as well as interpreted, are Scala, Haskell or Ocaml. Each of these languages has an interactive interpreter, as well as a compiler to byte-code or native machine code.

So generally categorizing languages by "compiled" and "interpreted" doesn't make much sense.

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

Show compose SMS view in Android

I add my SMS method if it can help someone. Be careful with smsManager.sendTextMessage, If the text is too long, the message does not go away. You have to respect max length depending of encoding. More information here SMS Manager send mutlipart message when there is less than 160 characters

//TO USE EveryWhere

SMSUtils.sendSMS(context, phoneNumber, message);

//Manifest

<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

 <receiver
     android:name=".SMSUtils"
     android:enabled="true"
     android:exported="true">
     <intent-filter>
         <action android:name="SMS_SENT"/>
         <action android:name="SMS_DELIVERED"/>
      </intent-filter>
 </receiver>

//JAVA

public class SMSUtils extends BroadcastReceiver {

    public static final String SENT_SMS_ACTION_NAME = "SMS_SENT";
    public static final String DELIVERED_SMS_ACTION_NAME = "SMS_DELIVERED";

    @Override
    public void onReceive(Context context, Intent intent) {
        //Detect l'envoie de sms
        if (intent.getAction().equals(SENT_SMS_ACTION_NAME)) {
            switch (getResultCode()) {
                case Activity.RESULT_OK: // Sms sent
                    Toast.makeText(context, context.getString(R.string.sms_send), Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE: // generic failure
                    Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE: // No service
                    Toast.makeText(context, context.getString(R.string.sms_not_send_no_service), Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU: // null pdu
                    Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF: //Radio off
                    Toast.makeText(context, context.getString(R.string.sms_not_send_no_radio), Toast.LENGTH_LONG).show();
                    break;
            }
        }
        //detect la reception d'un sms
        else if (intent.getAction().equals(DELIVERED_SMS_ACTION_NAME)) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, context.getString(R.string.sms_receive), Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(context, context.getString(R.string.sms_not_receive), Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }

    /**
     * Test if device can send SMS
     * @param context
     * @return
     */
    public static boolean canSendSMS(Context context) {
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
    }

    public static void sendSMS(final Context context, String phoneNumber, String message) {

        if (!canSendSMS(context)) {
            Toast.makeText(context, context.getString(R.string.cannot_send_sms), Toast.LENGTH_LONG).show();
            return;
        }

        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT_SMS_ACTION_NAME), 0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED_SMS_ACTION_NAME), 0);

        final SMSUtils smsUtils = new SMSUtils();
        //register for sending and delivery
        context.registerReceiver(smsUtils, new IntentFilter(SMSUtils.SENT_SMS_ACTION_NAME));
        context.registerReceiver(smsUtils, new IntentFilter(DELIVERED_SMS_ACTION_NAME));

        SmsManager sms = SmsManager.getDefault();
        ArrayList<String> parts = sms.divideMessage(message);

        ArrayList<PendingIntent> sendList = new ArrayList<>();
        sendList.add(sentPI);

        ArrayList<PendingIntent> deliverList = new ArrayList<>();
        deliverList.add(deliveredPI);

        sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);

        //we unsubscribed in 10 seconds 
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                context.unregisterReceiver(smsUtils);
            }
        }, 10000);

    }
}

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

Case Insensitive String comp in C

I've found built-in such method named from which contains additional string functions to the standard header .

Here's the relevant signatures :

int  strcasecmp(const char *, const char *);
int  strncasecmp(const char *, const char *, size_t);

I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.

tolower(unsigned char ch) {
    if (ch >= 'A' && ch <= 'Z')
        ch = 'a' + (ch - 'A');
    return ch;
 }

int strcasecmp(const char *s1, const char *s2) {
    const unsigned char *us1 = (const u_char *)s1,
                        *us2 = (const u_char *)s2;

    while (tolower(*us1) == tolower(*us2++))
        if (*us1++ == '\0')
            return (0);
    return (tolower(*us1) - tolower(*--us2));
}

Use different Python version with virtualenv

In windows subsystem for linux:

  1. Create environment for python3:

    virtualenv --python=/usr/bin/python3 env
    
  2. Activate it:

    source env/bin/activate
    

Permission denied for relation

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

Log4net rolling daily filename with date in the file name

I've tried all the answers, but there was always something missing and not functioning as expected for me.

Then I experimented a bit with the hints given in each answer and was successful with the following setting:

<appender name="RollingActivityLog" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="C:\temp\LOG4NET_Sample_Activity.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <staticLogFileName value="false" />
  <preserveLogFileNameExtension value="true" />
  <datePattern value="-yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level - %message%newline" />
  </layout>
</appender>

The issue with other combinations of parameters was that the latest file didn't have the time pattern, or that the time pattern was appended as .log20171215 which created a new file time (and a new file type!) each day - or both issues appeared.

Now with this setting you are getting files like this one:

LOG4NET_Sample_Activity-20171215.log

which is what I wanted.


To summarize:

  • Don't put the date pattern in the <file value=... attribute, just define it in the datePattern.

  • Make sure you have the preserveLogFileNameExtension value attribute set to true.

  • Make sure you have the staticLogFileName value set to false.

  • Set the rollingStyle attribute value to Date.

Using Intent in an Android application to show another activity

Intent i = new Intent("com.Android.SubActivity");
startActivity(i);

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

java.util.regex - importance of Pattern.compile()?

When you compile the Pattern Java does some computation to make finding matches in Strings faster. (Builds an in-memory representation of the regex)

If you are going to reuse the Pattern multiple times you would see a vast performance increase over creating a new Pattern every time.

In the case of only using the Pattern once, the compiling step just seems like an extra line of code, but, in fact, it can be very helpful in the general case.

Download File Using Javascript/jQuery

I know I'm late for the party, but I'd like to share my solution which is variation of Imagine Breaker's solution above. I tried to use his solution, because his solution seems most simple and easy to me. But like other said, it didn't work for some browsers, so I put some variation on it by using jquery.

Hope this could help someone out there.

function download(url) {
  var link = document.createElement("a");
  $(link).click(function(e) {
    e.preventDefault();
    window.location.href = url;
  });
  $(link).click();
}

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Iterating through a string word by word

When you do -

for word in string:

You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split() , and then iterate through that . Example -

my_string = "this is a string"
for word in my_string.split():
    print (word)

Please note, str.split() , without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).

Use Toast inside Fragment

To help another people with my same problem, the complete answer to Use Toast inside Fragment is:

Activity activity = getActivity();

@Override
public void onClick(View arg0) {

    Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}

Java: convert seconds to minutes, hours and days

An example using built in TimeUnit.

long uptime = System.currentTimeMillis();

long days = TimeUnit.MILLISECONDS
    .toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);

long hours = TimeUnit.MILLISECONDS
    .toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);

long minutes = TimeUnit.MILLISECONDS
    .toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);

long seconds = TimeUnit.MILLISECONDS
    .toSeconds(uptime);

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Create a separate JavaScript function that can be called to close the dialog using the specific object id, and place the function outside of $(document).ready() like this:

function closeDialogWindow() { 
$('#dialogWindow').dialog('close');
}

NOTE: The function must be declared outside of $(document).ready() so jQuery doesn't try to trigger the close event on the dialog before it is created in the DOM.

how to make twitter bootstrap submenu to open on the left side?

If I've understood this right, bootstrap provides a CSS class for just this case. Add 'pull-right' to the menu 'ul':

<ul class="dropdown-menu pull-right">

..and the end result is that the menu options appear right-aligned, in line with the button they drop down from.

Asp Net Web API 2.1 get client IP address

string userRequest = System.Web.HttpContext.Current.Request.UserHostAddress;

This works on me.

System.Web.HttpContext.Current.Request.UserHostName; this one return me the same return I get from the UserHostAddress.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

SQL Server NOLOCK and joins

Neither. You set the isolation level to READ UNCOMMITTED which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.

How to get first N number of elements from an array

You can filter using index of array.

_x000D_
_x000D_
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
_x000D_
_x000D_

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

Client on Node.js: Uncaught ReferenceError: require is not defined

Replace all require statements with import statements. Example:

// Before:
const Web3 = require('web3');

// After:
import Web3 from 'web3';

It worked for me.