Programs & Examples On #Redmine plugins

Redmine is a flexible project management web application written using Ruby on Rails framework.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

Entity Framework Queryable async

There is a massive difference in the example you have posted, the first version:

var urls = await context.Urls.ToListAsync();

This is bad, it basically does select * from table, returns all results into memory and then applies the where against that in memory collection rather than doing select * from table where... against the database.

The second method will not actually hit the database until a query is applied to the IQueryable (probably via a linq .Where().Select() style operation which will only return the db values which match the query.

If your examples were comparable, the async version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async functionality.

However the major difference (and benefit) is that the async version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).

Converting SVG to PNG using C#

I'm using Batik for this. The complete Delphi code:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
              CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
  if CreateOK then begin
    //may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end else
    ShowMessage('Unable to run ' + ProgramName);

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

procedure ConvertSVGtoPNG(aFilename: String);
const
  ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
  ExecNewProcess(ExecLine + aFilename, True);
end;

Printf long long int in C with GCC?

For portable code, the macros in inttypes.h may be used. They expand to the correct ones for the platform.

E.g. for 64 bit integer, the macro PRId64 can be used.

int64_t n = 7;
printf("n is %" PRId64 "\n", n);

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

How to Fill an array from user input C#?

Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.

Why do Sublime Text 3 Themes not affect the sidebar?

You need to restart Sublime completely in order for a theme to fully take effect. Just changing and saving Preferences.sublime-settings or using a theme-changing plugin won't do it. You need to use ?Q or Sublime Text -> Quit, not just close the window by clicking the red dot.

jQuery: Check if div with certain class name exists

The simple code is given below :

if ($('.mydivclass').length > 0) {
   //Things to do if class exist
}

To hide the div with particuler id :

if ($('#'+given_id+'.mydivclass').length > 0) {
   //Things to do if class exist
}

belongs_to through associations

So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  ...
  def question
    answer.question
  end
end

this way the you can now call question on Choice

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

How to convert binary string value to decimal

Have to think about the decimal precision, so you must to limit the bitstring length. Anyway, using BigDecimal is a good choice.

public BigDecimal bitStringToBigDecimal(String bitStr){

    BigDecimal sum = new BigDecimal("0");
    BigDecimal base = new BigDecimal(2);
    BigDecimal temp;
    for(int i=0;i<bitStr.length();i++){
        if(bitStr.charAt(i)== '1'){
            int exponent= bitStr.length()-1-i;
            temp=base.pow(exponent);
            sum=sum.add(temp);
        }

    }
    return sum;
}

How can I multiply and divide using only bit shifting and adding?

Taken from here.

This is only for division:

int add(int a, int b) {
        int partialSum, carry;
        do {
            partialSum = a ^ b;
            carry = (a & b) << 1;
            a = partialSum;
            b = carry;
        } while (carry != 0);
        return partialSum;
}

int subtract(int a, int b) {
    return add(a, add(~b, 1));
}

int division(int dividend, int divisor) {
        boolean negative = false;
        if ((dividend & (1 << 31)) == (1 << 31)) { // Check for signed bit
            negative = !negative;
            dividend = add(~dividend, 1);  // Negation
        }
        if ((divisor & (1 << 31)) == (1 << 31)) {
            negative = !negative;
            divisor = add(~divisor, 1);  // Negation
        }
        int quotient = 0;
        long r;
        for (int i = 30; i >= 0; i = subtract(i, 1)) {
            r = (divisor << i);
           // Left shift divisor until it's smaller than dividend
            if (r < Integer.MAX_VALUE && r >= 0) { // Avoid cases where comparison between long and int doesn't make sense
                if (r <= dividend) { 
                    quotient |= (1 << i);    
                    dividend = subtract(dividend, (int) r);
                }
            }
        }
        if (negative) {
            quotient = add(~quotient, 1);
        }
        return quotient;
}

Include PHP inside JavaScript (.js) files

Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

Ping with timestamp on Windows CLI

Another powershell method (I only wanted failures)

$ping = new-object System.Net.NetworkInformation.Ping
$target="192.168.0.1"
Write-Host "$(Get-Date -format 's') Start ping to $target"
while($true){
    $reply = $ping.send($target)
    if ($reply.status -eq "Success"){
        # ignore success    
        Start-Sleep -Seconds 1
    }
    else{
        Write-Host "$(Get-Date -format 's') Destination unreachable" $target

    }
}

Convert an array into an ArrayList

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}

Delete keychain items when an app is uninstalled

@amro's answer translated to Swift 4.0:

if UserDefaults.standard.object(forKey: "FirstInstall") == nil {
    UserDefaults.standard.set(false, forKey: "FirstInstall")
    UserDefaults.standard.synchronize()
}

Angular: Cannot find a differ supporting object '[object Object]'

I received this error in my code because I'd not run JSON.parse(result).

So my result was a string instead of an array of objects.

i.e. I got:

"[{},{}]" 

instead of:

[{},{}]

import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
  return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
  .then((value) => {
     let servers: Server[] = JSON.parse(value) as Server[];
                   }
  );

Benefits of inline functions in C++?

inline allows you to place a function definition in a header file and #include that header file in multiple source files without violating the one definition rule.

How to setup virtual environment for Python in VS Code?

The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.

Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:

vscode interpreter info

Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.

Google Chrome redirecting localhost to https

@Adiyat Mubarak answer did not work for me. When I attempted to clear the cache and hard-reload, the page still redirected to https.

My solution: In the upper right-hand corner of the url bar (just to the left of the favorites star icon) there is an icon with an "x" through it. Right-click on that, and it will say something about "unsafe scripts", then there is an option to load them anyway. Do that.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The problems are to do with your paths.

  1. Make sure that the directory "E:\java resources\apache-maven-2.2.0\bin" is on your command search path.

  2. Make sure that the JAVA_HOME variable refers to the home directory for your Java installation. If you are executing Java from "E:\Sun\SDK\jdk\bin", then the JAVA_HOME variable needs to point to "E:\Sun\SDK\jdk".

    NB: JAVA_HOME should NOT end with "\bin"1.

  3. Make sure that you haven't put a semicolon in the JAVA_HOME variable2.

    NB: JAVA_HOME should be a single directory name, not "PATH-like" list of directory names separated by semicolons.

Also note that you could run into problems if you have ignored this advice in the Maven on Windows instructions about spaces in key pathnames.

"Maven, like many cross-platform tools, can encounter problems when there are space characters in important pathnames."

"You need to install the Java SDK (e.g. from Oracle's download site), and you should install it to a pathname without spaces, such as c:\j2se1.6."'

"You need to unpack the Maven distribution. Don't unpack it in the middle of your source code; pick some location (with no spaces in the path!) and unpack it there."

The simple remedy for this would be to reinstall Java or Maven in a different location so that there isn't a space in the path


1 - .... unless you have made an insane choice for the name for your installation location.

2 - Apparently a common "voodoo" solution to Windows path problems is to whack a semicolon on the end. It is not recommended in general, absolutely does not work here.

SOAP client in .NET - references or examples?

Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.

Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.

There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.

Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.

How do I copy SQL Azure database to my local development server?

You can try with the tool "SQL Database Migration Wizard". This tool provide option to import and export data from azure sql.

Please check more details here.

https://sqlazuremw.codeplex.com/

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

Following two steps worked perfectly fine for me:

  1. Comment out the bind address from the file /etc/mysql/my.cnf:

    #bind-address = 127.0.0.1

  2. Run following query in phpMyAdmin:

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'; FLUSH PRIVILEGES;

jQuery find parent form

As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

Wireshark localhost traffic capture

For Windows,

You cannot capture packets for Local Loopback in Wireshark however, you can use a very tiny but useful program called RawCap;

RawCap

Run RawCap on command prompt and select the Loopback Pseudo-Interface (127.0.0.1) then just write the name of the packet capture file (.pcap)

A simple demo is as below;

C:\Users\Levent\Desktop\rawcap>rawcap
Interfaces:
 0.     169.254.125.51  Local Area Connection* 12       Wireless80211
 1.     192.168.2.254   Wi-Fi   Wireless80211
 2.     169.254.214.165 Ethernet        Ethernet
 3.     192.168.56.1    VirtualBox Host-Only Network    Ethernet
 4.     127.0.0.1       Loopback Pseudo-Interface 1     Loopback
Select interface to sniff [default '0']: 4
Output path or filename [default 'dumpfile.pcap']: test.pcap
Sniffing IP : 127.0.0.1
File        : test.pcap
Packets     : 48^C

SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

select Subject, 
       CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration 
where MerchantId =@MerchantID 

Excel how to fill all selected blank cells with text

OK, what you can try is

Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.

That should replace all blank cells in the USED range with NULL

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

Using jQuery to compare two arrays of Javascript objects

I found this discussion because I needed a way to deep compare arrays and objects. Using the examples here, I came up with the following (broken up into 3 methods for clarity):

jQuery.extend({
    compare : function (a,b) {
        var obj_str = '[object Object]',
            arr_str = '[object Array]',
            a_type  = Object.prototype.toString.apply(a),
            b_type  = Object.prototype.toString.apply(b);

            if ( a_type !== b_type) { return false; }
            else if (a_type === obj_str) {
                return $.compareObject(a,b);
            }
            else if (a_type === arr_str) {
                return $.compareArray(a,b);
            }
            return (a === b);
        }
});

jQuery.extend({
    compareArray: function (arrayA, arrayB) {
        var a,b,i,a_type,b_type;
        // References to each other?
        if (arrayA === arrayB) { return true;}

        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        a = jQuery.extend(true, [], arrayA);
        b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (i = 0, l = a.length; i < l; i+=1) {
            a_type = Object.prototype.toString.apply(a[i]);
            b_type = Object.prototype.toString.apply(b[i]);

            if (a_type !== b_type) {
                return false;
            }

            if ($.compare(a[i],b[i]) === false) {
                return false;
            }
        }
        return true;
    }
});

jQuery.extend({
    compareObject : function(objA,objB) {

        var i,a_type,b_type;

        // Compare if they are references to each other 
        if (objA === objB) { return true;}

        if (Object.keys(objA).length !== Object.keys(objB).length) { return false;}
        for (i in objA) {
            if (objA.hasOwnProperty(i)) {
                if (typeof objB[i] === 'undefined') {
                    return false;
                }
                else {
                    a_type = Object.prototype.toString.apply(objA[i]);
                    b_type = Object.prototype.toString.apply(objB[i]);

                    if (a_type !== b_type) {
                        return false; 
                    }
                }
            }
            if ($.compare(objA[i],objB[i]) === false){
                return false;
            }
        }
        return true;
    }
});

Testing

var a={a : {a : 1, b: 2}},
    b={a : {a : 1, b: 2}},
    c={a : {a : 1, b: 3}},
    d=[1,2,3],
    e=[2,1,3];

console.debug('a and b = ' + $.compare(a,b)); // a and b = true
console.debug('b and b = ' + $.compare(b,b)); // b and b = true
console.debug('b and c = ' + $.compare(b,c)); // b and c = false
console.debug('c and d = ' + $.compare(c,d)); // c and d = false
console.debug('d and e = ' + $.compare(d,e)); // d and e = true

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

The permission denied error probably indicates that SSH private key authentication has failed. Assuming that you're using an image derived from the Debian or Centos images recommended by gcutil, it's likely one of the following:

  1. You don't have any ssh keys loaded into your ssh keychain, and you haven't specified a private ssh key with the -i option.
  2. None of your ssh keys match the entries in .ssh/authorized_keys for the account you're attempting to log in to.
  3. You're attempting to log into an account that doesn't exist on the machine, or attempting to log in as root. (The default images disable direct root login – most ssh brute-force attacks are against root or other well-known accounts with weak passwords.)

How to determine what accounts and keys are on the instance:

There's a script that runs every minute on the standard Compute Engine Centos and Debian images which fetches the 'sshKeys' metadata entry from the metadata server, and creates accounts (with sudoers access) as necessary. This script expects entries of the form "account:\n" in the sshKeys metadata, and can put several entries into authorized_keys for a single account. (or create multiple accounts if desired)

In recent versions of the image, this script sends its output to the serial port via syslog, as well as to the local logs on the machine. You can read the last 1MB of serial port output via gcutil getserialportoutput, which can be handy when the machine isn't responding via SSH.

How gcutil ssh works:

gcutil ssh does the following:

  1. Looks for a key in $HOME/.ssh/google_compute_engine, and calls ssh-keygen to create one if not present.
  2. Checks the current contents of the project metadata entry for sshKeys for an entry that looks like ${USER}:$(cat $HOME/.ssh/google_compute_engine.pub)
  3. If no such entry exists, adds that entry to the project metadata, and waits for up to 5 minutes for the metadata change to propagate and for the script inside the VM to notice the new entry and create the new account.
  4. Once the new entry is in place, (or immediately, if the user:key was already present) gcutil ssh invokes ssh with a few command-line arguments to connect to the VM.

A few ways this could break down, and what you might be able to do to fix them:

  1. If you've removed or modified the scripts that read sshKeys, the console and command line tool won't realize that modifying sshKeys doesn't work, and a lot of the automatic magic above can get broken.
  2. If you're trying to use raw ssh, it may not find your .ssh/google_compute_engine key. You can fix this by using gcutil ssh, or by copying your ssh public key (ends in .pub) and adding to the sshKeys entry for the project or instance in the console. (You'll also need to put in a username, probably the same as your local-machine account name.)
  3. If you've never used gcutil ssh, you probably don't have a .ssh/google_compute_engine.pub file. You can either use ssh-keygen to create a new SSH public/private keypair and add it to sshKeys, as above, or use gcutil ssh to create them and manage sshKeys.
  4. If you're mostly using the console, it's possible that the account name in the sshKeys entry doesn't match your local username, you may need to supply the -l argument to SSH.

Mailto links do nothing in Chrome but work in Firefox?

I solved the problem using this code:

_x000D_
_x000D_
    _x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
    var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

It worked for me like a charm !

Java equivalent of unsigned long long?

Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:

Long l1 = Long.parseUnsignedLong("17916881237904312345");

To print it, you can not simply print l1, but you have to first:

String l1Str = Long.toUnsignedString(l1)

Then

System.out.println(l1Str);

Write a function that returns the longest palindrome in a given string

The Algo 2 may not work for all string. Here is an example of such a string "ABCDEFCBA".

Not that the string has "ABC" and "CBA" as its substring. If you reverse the original string, it will be "ABCFEDCBA". and the longest matching substring is "ABC" which is not a palindrome.

You may need to additionally check if this longest matching substring is actually a palindrome which has the running time of O(n^3).

Java HTTPS client certificate authentication

For those of you who simply want to set up a two-way authentication (server and client certificates), a combination of these two links will get you there :

Two-way auth setup:

https://linuxconfig.org/apache-web-server-ssl-authentication

You don't need to use the openssl config file that they mention; just use

  • $ openssl genrsa -des3 -out ca.key 4096

  • $ openssl req -new -x509 -days 365 -key ca.key -out ca.crt

to generate your own CA certificate, and then generate and sign the server and client keys via:

  • $ openssl genrsa -des3 -out server.key 4096

  • $ openssl req -new -key server.key -out server.csr

  • $ openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 100 -out server.crt

and

  • $ openssl genrsa -des3 -out client.key 4096

  • $ openssl req -new -key client.key -out client.csr

  • $ openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 101 -out client.crt

For the rest follow the steps in the link. Managing the certificates for Chrome works the same as in the example for firefox that is mentioned.

Next, setup the server via:

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

Note that you have already created the server .crt and .key so you don't have to do that step anymore.

How can I convert a string to a number in Perl?

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

After $2+0 Perl notices that you've treated $2 as a number, because you used a numeric operator.

I noticed this whilst trying to compare two hashes with Data::Dumper.

Invert "if" statement to reduce nesting

Personally I prefer only 1 exit point. It's easy to accomplish if you keep your methods short and to the point, and it provides a predictable pattern for the next person who works on your code.

eg.

 bool PerformDefaultOperation()
 {
      bool succeeded = false;

      DataStructure defaultParameters;
      if ((defaultParameters = this.GetApplicationDefaults()) != null)
      {
           succeeded = this.DoSomething(defaultParameters);
      }

      return succeeded;
 }

This is also very useful if you just want to check the values of certain local variables within a function before it exits. All you need to do is place a breakpoint on the final return and you are guaranteed to hit it (unless an exception is thrown).

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Search code inside a Github project

While @VonC's answer works for some repositories, unfortunately for many repositories you can't right now. Github is simply not indexing them (as commented originally by @emddudley). They haven't stated this anywhere on their website, but they will tell you if you ask support:

From: Tim Pease
We have stopped adding newly pushed code into our codesearch index. The volume of code has outgrown our current search index, and we are working on moving to a more scalable search architecture. I'm sorry for the annoyance. We do not have an estimate for when this new search index will be up and running, but when it is ready a blog post will be published (https://github.com/blog).

Annoyingly there is no way to tell which repositories are not indexed other than the lack of results (which also could be from a bad query).

There also is no way to track this issue other than waiting for them to blog it (or watching here on SO).

From: Tim Pease
I am afraid our issue tracker is internal, but we can notify you as soon as the new search index is up and running.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Could not locate Gemfile

You do not have Gemfile in a directory where you run that command. Gemfile is a file containing your gem settings for a current program.

How to grant all privileges to root user in MySQL 8.0

I had the same problem on CentOS and this worked for me (version: 8.0.11):

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Counting number of words in a file

Just keep a boolean flag around that lets you know if the previous character was whitespace or not (pseudocode follows):

boolean prevWhitespace = false;
int wordCount = 0;
while (char ch = getNextChar(input)) {
  if (isWhitespace(ch)) {
    if (!prevWhitespace) {
      prevWhitespace = true;
      wordCount++;
    }
  } else {
    prevWhitespace = false;
  }
}

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I had the same issue, if you enable Microsoft Scripting Runtime you should be good. You can do so under tools > references > and then check the box for Microsoft Scripting Runtime. This should solve your issue.

How can I remove leading and trailing quotes in SQL Server?

I have just tested this code in MS SQL 2008 and validated it.

Remove left-most quote:

UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'

Remove right-most quote: (Revised to avoid error from implicit type conversion to int)

UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'

The type arguments for method cannot be inferred from the usage

Get<S, T> takes two type arguments. When you call service.Get(new Signatur()); how does the compiler know what T is? You'll have to pass it explicitly or change something else about your type hierarchies. Passing it explicitly would look like:

service.Get<Signatur, bool>(new Signatur());

Saving an image in OpenCV

Sorry to bring up an old post, but I wanted to provide another answer for anyone that comes across this thread.

I had the same problem. No matter what I did, the image just looked like it was complete black. I tried making multiple consecutive calls to cvQueryFrame and noticed that when I made 5 or more, I could see the image. So I started removing the calls one by one to see where the "breaking point" was. What I ended up finding was that the image got darker and darker as I removed each call. Making just a single call provided an image that was almost completely black, but if I looked very closely, I could make out my image.

I tried 10 consecutive calls to test my theory, and sure enough, I was given a very bright image, considering that I'm in a dimly lit room. Hopefully, this was the same problem you were encountering.

I don't know much about imaging, but it looks like multiple consecutive calls to cvQueryFrame increases the length of exposure for the camera. This definitely fixes the problem, though it doesn't seem like the most elegant solution. I'm going to see if I can find a parameter that will increase the exposure, or perhaps some other parameter that will brighten up my images.

Good luck!

Smart way to truncate long strings

Somewhere Smart :D

_x000D_
_x000D_
//My Huge Huge String_x000D_
    let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).`_x000D_
    _x000D_
//Trim Max Length_x000D_
 const maxValue = 50_x000D_
// The barber._x000D_
 const TrimMyString = (string, maxLength, start = 0) => {_x000D_
//Note - `start` is if I want to start after some point of the string_x000D_
     if (string.length > maxLength) {_x000D_
     let trimmedString = string.substr(start, maxLength)_x000D_
      return (_x000D_
        trimmedString.substr(_x000D_
        start,_x000D_
        Math.min(trimmedString.length,   trimmedString.lastIndexOf(' '))_x000D_
           ) + ' ...'_x000D_
         )_x000D_
       }_x000D_
    return string_x000D_
}_x000D_
_x000D_
console.log(TrimMyString(tooHugeToHandle, maxValue))
_x000D_
_x000D_
_x000D_

Input text dialog Android

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

Within your class:

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

My app has a fragment to loading in 3 secs, but when the fist screen is preparing to show, I press home button and resume run it, it show the same error, so It edit my code and it ran very smooth:

new Handler().post(new Runnable() {
        public void run() {
            if (saveIns == null) {
                mFragment = new Fragment_S1_loading();
                getFragmentManager().beginTransaction()
                        .replace(R.id.container, mFragment).commit();
            }
            getActionBar().hide();
            // Loading screen in 3 secs:
            mCountDownTimerLoading = new CountDownTimer(3000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    if (saveIns == null) {// TODO bug when start app and press home
                                            // button
                        getFragmentManager()
                                .beginTransaction()
                                .replace(R.id.container,
                                        new Fragment_S2_sesstion1()).commitAllowingStateLoss();
                    }
                    getActionBar().show();
                }
            }.start();
        }
    });

NOTE: add commitAllowingStateLoss() instead of commit()

Get error message if ModelState.IsValid fails?

I have no idea if this is your problem, but if you add a user and then change the name of your application, that user will remain in the database (of course), but will be invalid (which is correct behavior). However, there will be no error added for this type of failure. The error list is empty, but ModelState.IsValid will return false for the login.

How to print a dictionary line by line in Python?

A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:

def dumpclean(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print k
                dumpclean(v)
            else:
                print '%s : %s' % (k, v)
    elif isinstance(obj, list):
        for v in obj:
            if hasattr(v, '__iter__'):
                dumpclean(v)
            else:
                print v
    else:
        print obj

This produces the output:

A
color : 2
speed : 70
B
color : 3
speed : 60

I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.

import sys

def dump(obj, nested_level=0, output=sys.stdout):
    spacing = '   '
    if isinstance(obj, dict):
        print >> output, '%s{' % ((nested_level) * spacing)
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
        print >> output, '%s}' % (nested_level * spacing)
    elif isinstance(obj, list):
        print >> output, '%s[' % ((nested_level) * spacing)
        for v in obj:
            if hasattr(v, '__iter__'):
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
        print >> output, '%s]' % ((nested_level) * spacing)
    else:
        print >> output, '%s%s' % (nested_level * spacing, obj)

Using this function, the OP's output looks like this:

{
   A:
   {
      color: 2
      speed: 70
   }
   B:
   {
      color: 3
      speed: 60
   }
}

which I personally found to be more useful and descriptive.

Given the slightly less-trivial example of:

{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}

The OP's requested solution yields this:

test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)

whereas the 'enhanced' version yields this:

{
   test:
   [
      {
         1: 3
      }
   ]
   test3:
   {
      (1, 2):
      [
         abc
         def
         ghi
      ]
      (4, 5): def
   }
   test2:
   [
      (1, 2)
      (3, 4)
   ]
}

I hope this provides some value to the next person looking for this type of functionality.

How can you create pop up messages in a batch script?

You can take advantage of CSCRIPT.EXE or WSCRIPT.EXE (which have been present in every version of Windows since, I believe, Windows 95) like this:

echo msgbox "Hey! Here is a message!" > %tmp%\tmp.vbs
cscript /nologo %tmp%\tmp.vbs
del %tmp%\tmp.vbs

or

echo msgbox "Hey! Here is a message!" > %tmp%\tmp.vbs
wscript %tmp%\tmp.vbs
del %tmp%\tmp.vbs

You could also choose the more customizeable PopUp command. This example gives you a 10 second window to click OK, before timing out:

echo set WshShell = WScript.CreateObject("WScript.Shell") > %tmp%\tmp.vbs
echo WScript.Quit (WshShell.Popup( "You have 10 seconds to Click 'OK'." ,10 ,"Click OK", 0)) >> %tmp%\tmp.vbs
cscript /nologo %tmp%\tmp.vbs
if %errorlevel%==1 (
  echo You Clicked OK
) else (
  echo The Message timed out.
)
del %tmp%\tmp.vbs

In their above context, both cscript and wscript will act the same. When called from a batch file, bot cscript and wscript will pause the batch file until they finish their script, then allow the file to continue.

When called manually from the command prompt, cscript will not return control to the command prompt until it is finished, while wscript will create a seprate thread for the execution of it's script, returning control to the command prompt even before it's script has finished.

Other methods discussed in this thread do not cause the execution of batch files to pause while waiting for the message to be clicked on. Your selection will be dictated by your needs.

Note: Using this method, multiple button and icon configurations are available to cover various yes/no/cancel/abort/retry queries to the user: https://technet.microsoft.com/en-us/library/ee156593.aspx

enter image description here

MySQL - How to select rows where value is in array?

If the array element is not integer you can use something like below :

$skus  = array('LDRES10','LDRES12','LDRES11');   //sample data

if(!empty($skus)){     
    $sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "      
}

Oracle: how to UPSERT (update or insert into a table?)

Copy & paste example for upserting one table into another, with MERGE:

CREATE GLOBAL TEMPORARY TABLE t1
    (id VARCHAR2(5) ,
     value VARCHAR2(5),
     value2 VARCHAR2(5)
     )
  ON COMMIT DELETE ROWS;

CREATE GLOBAL TEMPORARY TABLE t2
    (id VARCHAR2(5) ,
     value VARCHAR2(5),
     value2 VARCHAR2(5))
  ON COMMIT DELETE ROWS;
ALTER TABLE t2 ADD CONSTRAINT PK_LKP_MIGRATION_INFO PRIMARY KEY (id);

insert into t1 values ('a','1','1');
insert into t1 values ('b','4','5');
insert into t2 values ('b','2','2');
insert into t2 values ('c','3','3');


merge into t2
using t1
on (t1.id = t2.id) 
when matched then 
  update set t2.value = t1.value,
  t2.value2 = t1.value2
when not matched then
  insert (t2.id, t2.value, t2.value2)  
  values(t1.id, t1.value, t1.value2);

select * from t2

Result:

  1. b 4 5
  2. c 3 3
  3. a 1 1

How to make a owl carousel with arrows instead of next previous

A note for others who may be using Owl Carousel v 1.3.2:

You can replace the navigation text in the settings where you're enabling the navigation.

navigation:true,
navigationText: [
   "<i class='fa fa-chevron-left'></i>",
   "<i class='fa fa-chevron-right'></i>"
]

String to HashMap JAVA

You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

Example:

Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");

JSONObject json= new JSONObject(map);

String result= json.toString();

System.out.print(result);

result:

{'myNumber':100, 'myString':'String'}

Your can also get key from it like

System.out.print(json.get("myNumber"));

result:

100

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Oracle 12c Installation failed to access the temporary location

The error is caused due to administrative shares are being disabled. If they cannot be enabled then perform the following workaround:

6.2.23 INS-30131 Error When Installing Oracle Database or Oracle Client

If the administrative shares are not enabled when performing a single instance Oracle Database or Oracle Client installation for 12c Release 1 (12.1) on Microsoft Windows 7, Microsoft Windows 8, and Microsoft Windows 10, then the installation fails with an INS-30131 error.

Workaround:

Execute the net share command to ensure that the administrative shares are enabled. If they are disabled, then enable them by following the instructions in the Microsoft Windows documentation. Alternatively, perform the client or server installation by specifying the following options:

  • For a client installation:

    -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

  • For a server installation:

    -ignorePrereq -J"-Doracle.install.db.validate.supportedOSCheck=false"

This issue is tracked with Oracle bug 21452473.

Source: Oracle Database Release Notes (Section 6.2.23)

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

Best tool for inspecting PDF files?

Adobe Acrobat has a very cool but rather well hidden mode allowing you to inspect PDF files. I wrote a blog article explaining it at https://blog.idrsolutions.com/2009/04/viewing-pdf-objects/

How to place a file on classpath in Eclipse?

This might not be the most useful answer, more of an addendum, but the above answer (from greenkode) confused me for all of 10 seconds.

"Add Folder" only lets you see folders that are the sub-folders of the project whose build path you are looking at.

The "Link Source" button in the above image would be called "Add External Folder" in an ideal world.

I had to make a properties file that is to be shared between multiple projects, and by keeping the properties file in an external folder, I am able to have only one, instead of having a copy in each project.

How to reload current page in ReactJS?

use this might help

window.location.reload();

C#: How to add subitems in ListView

I think the quickest/neatest way to do this:

For each class have string[] obj.ToListViewItem() method and then do this:

foreach(var item in personList)
{
    listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}

Here is an example definition

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }
    public uint ID { get; set; }

    public string[] ToListViewItem()
    {
        return new string[] {
            ID.ToString("000000"),
            Name,
            Address,
            DOB.ToShortDateString()
        };
    }
}

As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with

listView1.Columns.AddRange(Person.ListViewHeaders());

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

How to have conditional elements and keep DRY with Facebook React's JSX?

Personally, I really think the ternary expressions show in (JSX In Depth) are the most natural way that conforms with the ReactJs standards.

See the following example. It's a little messy at first sight but works quite well.

<div id="page">
  {this.state.banner ? (
    <div id="banner">
     <div class="another-div">
       {this.state.banner}
     </div>
    </div>
  ) : 
  null} 
  <div id="other-content">
    blah blah blah...
  </div>
</div>

SecurityException: Permission denied (missing INTERNET permission?)

Just like Tom mentioned. When you start with capital A then autocomplete will complete it as.

ANDROID.PERMISSION.INTERNET

When you start typing with a then autocomplete will complete it as

android.permission.INTERNET

The second one is the correct one.

Truncating all tables in a Postgres database

FrustratedWithFormsDesigner is correct, PL/pgSQL can do this. Here's the script:

CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
    statements CURSOR FOR
        SELECT tablename FROM pg_tables
        WHERE tableowner = username AND schemaname = 'public';
BEGIN
    FOR stmt IN statements LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
    END LOOP;
END;
$$ LANGUAGE plpgsql;

This creates a stored function (you need to do this just once) which you can afterwards use like this:

SELECT truncate_tables('MYUSER');

How do I clone a range of array elements to a new array?

The following code does it in one line:

// Source array
string[] Source = new string[] { "A", "B", "C", "D" };
// Extracting a slice into another array
string[] Slice = new List<string>(Source).GetRange(2, 2).ToArray();

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid and I didn't..

How to align absolutely positioned element to center?

position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

PHP Get name of current directory

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__) 

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

You can use basename() to get the trailing part of the path :)

In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

Eg:

main.php
libs/common.php
libs/images/editor.php

In your common.php you need to use functions in editor.php, so you use

common.php:

require_once dirname(__FILE__) . '/images/editor.php';

main.php:

require_once libs/common.php

That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

Add error bars to show standard deviation on a plot in R

A solution with ggplot2 :

qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)

enter image description here

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

Is there a way to perform "if" in python's lambda

Hope this will help a little

you can resolve this problem in the following way

f = lambda x:  x==2   

if f(3):
  print("do logic")
else:
  print("another logic")

pip install gives error: Unable to find vcvarsall.bat

You need to have Visual Studio's bin dir in your path. Pip install is trying to compile some C code.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

return string with first match Regex

If you only need the first match, then use re.search instead of re.findall:

>>> m = re.search('\d+', 'aa33bbb44')
>>> m.group()
'33'
>>> m = re.search('\d+', 'aazzzbbb')
>>> m.group()
Traceback (most recent call last):
  File "<pyshell#281>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'

Then you can use m as a checking condition as:

>>> m = re.search('\d+', 'aa33bbb44')
>>> if m:
        print('First number found = {}'.format(m.group()))
    else:
        print('Not Found')


First number found = 33

What is an ORM, how does it work, and how should I use one?

Object Model is concerned with the following three concepts Data Abstraction Encapsulation Inheritance The relational model used the basic concept of a relation or table. Object-relational mapping (OR mapping) products integrate object programming language capabilities with relational databases.

Using LINQ to group a list of objects

var result = from cx in CustomerList
         group cx by cx.GroupID into cxGroup
     orderby cxGroup.Key
     select cxGroup; 

foreach (var cxGroup in result) { 
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key)); 
  foreach (var cx in cxGroup) { 
    Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}", 
      new object[] { cx.ID, cx.Name, cx.GroupID })); 
  }
}

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

Changing button text onclick

var count=0;
document.getElementById("play").onclick = function(){


if(count%2 =="1"){

                document.getElementById("video").pause();
                document.getElementById("play").innerHTML ="Pause";
            }else {

            document.getElementById("video").play();
            document.getElementById("play").innerHTML ="Play";

            }
            ++count;

Unresolved Import Issues with PyDev and Eclipse

KD.py

class A:
a=10;

KD2.py 
from com.jbk.KD import A;
class B:
  b=120;

aa=A();
print(aa.a)

THIS works perfectly file for me

Another example is

main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff

_init();
stuff();

settings.py
==========
def _init():
print("kiran")


subfile.py
==========
def stuff():
print("asasas")    

Eclipse: stop code from running (java)

For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...

new window will open and then search using keyword "debug" -> select debug from list

it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)

Fastest way to find second (third...) highest/lowest value in vector or column

Here is the simplest way I found,

num <- c(5665,1615,5154,65564,69895646)

num <- sort(num, decreasing = F)

tail(num, 1)                           # Highest number
head(tail(num, 2),1)                   # Second Highest number
head(tail(num, 3),1)                   # Third Highest number
head(tail(num, n),1)                   # Generl equation for finding nth Highest number

How can I get the current directory name in Javascript?

For both / and \:

window.location.pathname.replace(/[^\\\/]*$/, '');

To return without the trailing slash, do:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');

Get resultset from oracle stored procedure

My solution was to create a pipelined function. The advantages are that the query can be a single line:

  • select * from table(yourfunction(param1, param2));
  • You can join your results to other tables or filter or sort them as you please..
  • the results appear as regular query results so you can easily manipulate them.

To define the function you would need to do something like the following:

  -- Declare the record columns
  TYPE your_record IS RECORD(
     my_col1 VARCHAR2(50), 
     my_col2 varchar2(4000)
  );
  TYPE your_results IS TABLE OF your_record;

  -- Declare the function
  function yourfunction(a_Param1 varchar2, a_Param2 varchar2)
  return your_results pipelined is
    rt          your_results;
  begin
    -- Your query to load the table type
    select s.col1,s.col2
    bulk collect into rt
    from your_table s
    where lower(s.col1) like lower('%'||a_Param1||'%');

    -- Stuff the results into the pipeline..
    if rt.count > 0 then 
      for i in rt.FIRST .. rt.LAST loop 
        pipe row (rt(i)); 
      end loop; 
    end if;

    -- Add more results as you please....
    return;
  end find;

And as mentioned above, all you would do to view your results is:

select * from table(yourfunction(param1, param2)) t order by t.my_col1;

Typescript ReferenceError: exports is not defined

This is fixed by setting the module compiler option to es6:

{
  "compilerOptions": {     
    "module": "es6",
    "target": "es5",    
  }
}

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

from Jackson 2.7.x+ there is a way to annotate the member variable itself:

 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<String> newsletters;

More info here: Jackson @JsonFormat

Remove blank attributes from an Object in Javascript

We can use JSON.stringify and JSON.parse to remove blank attributes from an object.

jsObject = JSON.parse(JSON.stringify(jsObject), (key, value) => {
               if (value == null || value == '' || value == [] || value == {})
                   return undefined;
               return value;
           });

HTML not loading CSS file

You have to add type="text/css" you can also specify href="./style.css" which the . specifies the current directory

SVN change username

I’ve had the exact same problem and found the solution in Where does SVN client store user authentication data?:

  1. cd to ~/.subversion/auth/.
  2. Do fgrep -l <yourworkmatesusernameORtheserverurl> */*.
  3. Delete the file found.
  4. The next operation on the repository will ask you again for username/password information.

(For Windows, the steps are analogous; the auth directory is in %APPDATA%\Subversion\).

Note that this will only work for SVN access schemes where the user name is part of the server login so it’s no use for repositories accessed using file://.

How can the size of an input text box be defined in HTML?

Try this

<input type="text" style="font-size:18pt;height:420px;width:200px;">

Or else

 <input type="text" id="txtbox">

with the css:

 #txtbox
    {
     font-size:18pt;
     height:420px;
     width:200px;
    }

How can I force clients to refresh JavaScript files?

For ASP.NET pages I am using the following

BEFORE

<script src="/Scripts/pages/common.js" type="text/javascript"></script>

AFTER (force reload)

<script src="/Scripts/pages/common.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

Adding the DateTime.Now.Ticks works very well.

Invalid column name sql error

Change this line:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";

to this:

cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

Your insert command is expecting text, and you need single quotes (') between the actual value so SQL can understand it as text.

EDIT: For those of you who aren't happy with this answer, I would like to point out that there is an issue with this code in regards to SQL Injection. When I answered this question I only considered the question in point which was the missing single-quote on his code and I pointed out how to fix it. A much better answer has been posted by Adam (and I voted for it), where he explains the issues with injection and shows a way to prevent. Now relax and be happy guys.

How to detect IE11?

Angular JS does this way.

msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
if (isNaN(msie)) {
  msie = parseInt((/trident\/.*; rv:(\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
}

msie will be positive number if its IE and NaN for other browser like chrome,firefox.

why ?

As of Internet Explorer 11, the user-agent string has changed significantly.

refer this :

msdn #1 msdn #2

Matplotlib-Animation "No MovieWriters Available"

I had the following error while running the cell. enter image description here

This may be due to not having ffmpeg in your system. Try the following command in your terminal.

sudo apt install ffmpeg

This works for me. I hope it will work out for you too.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Be sure your site's Application Pool uses the correct framework version. I got the "Unable to start debugging" error on an ASP.Net 2005 site. It was incorrectly using the DefaultAppPool on Windows 7 (which I believe was using .Net Framework 4). I created a new a App Pool based on .Net Framework 2 and assigned it to the problem web site. After that debugging worked fine.

How to create streams from string in Node.Js?

Heres a tidy solution in TypeScript:

import { Readable } from 'stream'

class ReadableString extends Readable {
    private sent = false

    constructor(
        private str: string
    ) {
        super();
    }

    _read() {
        if (!this.sent) {
            this.push(Buffer.from(this.str));
            this.sent = true
        }
        else {
            this.push(null)
        }
    }
}

const stringStream = new ReadableString('string to be streamed...')

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

Makefile ifeq logical or

I don't think there's a concise, sensible way to do that, but there are verbose, sensible ways (such as Foo Bah's) and concise, pathological ways, such as

ifneq (,$(findstring $(GCC_MINOR),4-5))
    CFLAGS += -fno-strict-overflow
endif

(which will execute the command provided that the string $(GCC_MINOR) appears inside the string 4-5).

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

For me, this code worked. Just add it on your package.json file :

"scripts": {
    "dev-server": "encore dev-server",
    "dev": "webpack-dev-server --progress --colors",
    "watch": "encore dev --watch",
    "build": "encore production --progress"
},

And run the script "build" by running npm run build

If Else If In a Sql Server Function

No one seems to have picked that if (yes=no)>na or (no=na)>yes or (na=yes)>no, you get NULL as the result. Don't believe this is what you are after.

Here's also a more condensed form of the function, which works even if any of yes, no or na_ans is NULL.

USE [***]
GO
/****** Object:  UserDefinedFunction [dbo].[fnActionSq]    Script Date: 02/17/2011 10:21:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
RETURNS nvarchar(3)
AS 
BEGIN
return (select (
       select top 1 Result from
       (select 'Yes' Result, yes_ans union all
        select 'No', no_ans union all
        select 'N/A', na_ans) [ ]
        order by yes_ans desc, Result desc)
       from dbo.qrc_maintally
       where school_id = @SchoolId)
End

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Right click your project and choose properties in the properties dialog check the Java Compiler settings, maybe you have different workspace settings.

File Upload In Angular?

I've upload file using reference. No package is required to upload file this way.

// code to be written in .ts file

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

// code to be written in service.ts file

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

// code to be written in html

<input type="file" #fileInput>

Placing/Overlapping(z-index) a view above another view in android

RelativeLayout works the same way, the last image in the relative layout wins.

Convert multiple rows into one with comma as separator

If you're executing this through PHP, what about this?

$hQuery = mysql_query("SELECT * FROM users");
while($hRow = mysql_fetch_array($hQuery)) {
    $hOut .= $hRow['username'] . ", ";
}
$hOut = substr($hOut, 0, strlen($hOut) - 1);
echo $hOut;

How to fill Matrix with zeros in OpenCV?

You can use this to fill zeroes in a Mat object already containing data:

image1 = Scalar::all(0);

For eg, if you use it this way:

Mat image,image1;
image = imread("IMG_20160107_185956.jpg", CV_LOAD_IMAGE_COLOR);   // Read the file

if(! image.data )                              // Check for invalid input
{
    cout <<  "Could not open or find the image" << std::endl ;
    return -1;
}
cvtColor(image,image1,CV_BGR2GRAY);
image1 = Scalar::all(0);

It will work fine. But you cannot use this for uninitialised Mat. For that you can go for other options mentioned in above answers, like

Mat drawing = Mat::zeros( image.size(), CV_8UC3 );

C# getting its own class name

Try this:

this.GetType().Name

Exists Angularjs code/naming conventions?

I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171

Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower

And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec

Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub

Signed versus Unsigned Integers

Generally speaking that is correct. Without knowing anything more about why you are looking for the differences I can't think of any other differentiators between signed and unsigned.

Repeat table headers in print mode

Some browsers repeat the thead element on each page, as they are supposed to. Others need some help: Add this to your CSS:

thead {display: table-header-group;}
tfoot {display: table-header-group;}

Opera 7.5 and IE 5 won't repeat headers no matter what you try.

(source)

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

Most efficient method to groupby on an array of objects

groupByArray(xs, key) {
    return xs.reduce(function (rv, x) {
        let v = key instanceof Function ? key(x) : x[key];
        let el = rv.find((r) => r && r.key === v);
        if (el) {
            el.values.push(x);
        }
        else {
            rv.push({
                key: v,
                values: [x]
            });
        }
        return rv;
    }, []);
}

This one outputs array.

LIKE vs CONTAINS on SQL Server

The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.

The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.


The CONTAINS query should be:

SELECT * FROM table WHERE CONTAINS(Column, 'test');

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Create Pandas DataFrame from a string

A simple way to do this is to use StringIO.StringIO (python2) or io.StringIO (python3) and pass that to the pandas.read_csv function. E.g:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")

How to get multiple select box values using jQuery?

Html Code:

 <select id="multiple" multiple="multiple" name="multiple">
  <option value=""> -- Select -- </option>
  <option value="1">Opt1</option>
  <option value="2">Opt2</option>
  <option value="3">Opt3</option>
  <option value="4">Opt4</option>
  <option value="5">Opt5</option>
 </select>   

JQuery Code:

$('#multiple :selected').each(function(i, sel){ 
    alert( $(sel).val() ); 

});

Hope it works

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

Singular matrix issue with Numpy

As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0. But if you still want to get inverse matrix, you can use np.linalg.pinv, which leverages SVD to approximate initial matrix.

Find object by its property in array of objects with AngularJS way

How about plain JavaScript? More about Array.prototype.filter().

_x000D_
_x000D_
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
  return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
_x000D_
_x000D_

How to fix Python indentation

The reindent script did not work for me, due to some missing module. Anyway, I found this sed command which does the job perfect for me:

sed -r 's/^([  ]*)([^ ])/\1\1\2/' file.py

String to Binary in C#

It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010

This will do that for you...

//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
    //storage for the resulting string
    string result = string.Empty;
    //iterate through the byte[]
    foreach(byte value in data)
    {
        //storage for the individual byte
        string binarybyte = Convert.ToString(value, 2);
        //if the binarybyte is not 8 characters long, its not a proper result
        while(binarybyte.Length < 8)
        {
            //prepend the value with a 0
            binarybyte = "0" + binarybyte;
        }
        //append the binarybyte to the result
        result += binarybyte;
    }
    //return the result
    return result;
}

How to change the Content of a <textarea> with JavaScript

Like this:

document.getElementById('myTextarea').value = '';

or like this in jQuery:

$('#myTextarea').val('');

Where you have

<textarea id="myTextarea" name="something">This text gets removed</textarea>

For all the downvoters and non-believers:

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

MongoDB and "joins"

The database does not do joins -- or automatic "linking" between documents. However you can do it yourself client side. If you need to do 2, that is ok, but if you had to do 2000, the number of client/server turnarounds would make the operation slow.

In MongoDB a common pattern is embedding. In relational when normalizing things get broken into parts. Often in mongo these pieces end up being a single document, so no join is needed anyway. But when one is needed, one does it client-side.

Consider the classic ORDER, ORDER-LINEITEM example. One order and 8 line items are 9 rows in relational; in MongoDB we would typically just model this as a single BSON document which is an order with an array of embedded line items. So in that case, the join issue does not arise. However the order would have a CUSTOMER which probably is a separate collection - the client could read the cust_id from the order document, and then go fetch it as needed separately.

There are some videos and slides for schema design talks on the mongodb.org web site I belive.

Converting a date string to a DateTime object using Joda Time library

I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:

DateTime date = DateTime.parse("04/02/2011 20:27:05", 
                  DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));

Java dynamic array sizes?

You can use ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

...

ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

Javascript Audio Play on click

HTML:

<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>

JavaScript:

let play = function(){document.getElementById("audio").play()}

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

How to remove newlines from beginning and end of a string?

I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.

To remove newlines from the beginning:

// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);

System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");

and end of a string:

// Trim right
String z = "\n\nfrom the end\n\n";

System.out.println("-" + z.split("\\n+$", 2)[0] + "-");

I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.

Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.

How to make git mark a deleted and a new file as a file move?

Here's a quick and dirty solution for one, or a few, renamed and modified files that are uncommitted.

Let's say the file was named foo and now it's named bar:

  1. Rename bar to a temp name:

    mv bar side
    
  2. Checkout foo:

    git checkout HEAD foo
    
  3. Rename foo to bar with Git:

    git mv foo bar
    
  4. Now rename your temporary file back to bar.

    mv side bar
    

This last step is what gets your changed content back into the file.

While this can work, if the moved file is too different in content from the original git will consider it more efficient to decide this is a new object. Let me demonstrate:

$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ git add README.md work.js # why are the changes unstaged, let's add them.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ git stash # what? let's go back a bit
Saved working directory and index state WIP on dir: f7a8685 update
HEAD is now at f7a8685 update
$ git status
On branch workit
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .idea/

nothing added to commit but untracked files present (use "git add" to track)
$ git stash pop
Removing README
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README
    modified:   work.js

Dropped refs/stash@{0} (1ebca3b02e454a400b9fb834ed473c912a00cd2f)
$ git add work.js
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README

$ git add README # hang on, I want it removed
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ mv README.md Rmd # Still? Try the answer I found.
$ git checkout README
error: pathspec 'README' did not match any file(s) known to git.
$ git checkout HEAD README # Ok the answer needed fixing.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README.md
    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ git mv README README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ mv Rmd README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ # actually that's half of what I wanted; \
  # and the js being modified twice? Git prefers it in this case.

If else embedding inside html

You will find multiple different methods that people use and they each have there own place.

<?php if($first_condition): ?>
  /*$first_condition is true*/
<?php elseif ($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
<?php else: ?>
  /*$first_condition and $second_condition are false*/
<?php endif; ?>

If in your php.ini attribute short_open_tag = true (this is normally found on line 141 of the default php.ini file) you can replace your php open tag from <?php to <?. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php. short_open_tag is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag turned off.

A quick search of short_open_tag in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag That's a lot of people having problems with something they should just not play with.

with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag set to true.

short_open_tag will be removed in PHP6 so don't use short hand tags.

all future PHP versions will be dropping short_open_tag

"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working

and

Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .

Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem

and

To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?

You may also see people use the following example:

<?php if($first_condition){ ?>
  /*$first_condition is true*/
<?php }else if ($second_condition){ ?>
  /*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
  /*$first_condition and $second_condition are false*/
<?php } ?>

This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.

The following example shows when to use the bracket method

<?php
if($first_condition){
   /*$first_condition is true*/
}else if ($second_condition){
   /*$first_condition is false and $second_condition is true*/
}else{
   /*$first_condition and $second_condition are false*/
}
?>

If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.

UPDATE

based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.

Calculating the position of points in a circle

Placing a number in a circular path

// variable

let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle

for(let i=1; i<=number; i++) {
  let ang = i*(Math.PI/(number/2));
  let left = cx + (r*Math.cos(ang));
  let top = cy + (r*Math.sin(ang));
  console.log("top: ", top, ", left: ", left);
}

Are complex expressions possible in ng-hide / ng-show?

Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.

ng-show="column != 'vendorid' && column !='billingMonth'"

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Per batch, 65536 * Network Packet Size which is 4k so 256 MB

However, IN will stop way before that but it's not precise.

You end up with memory errors but I can't recall the exact error. A huge IN will be inefficient anyway.

Edit: Remus reminded me: the error is about "stack size"

android: how to use getApplication and getApplicationContext from non activity / service class

Sending your activity context to other classes could cause memoryleaks because holding that context alive is the reason that the GC can't dispose the object

How to install both Python 2.x and Python 3.x in Windows

Check your system environment variables after installing Python, python 3's directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.

How do I remove an array item in TypeScript?

With ES6 you can use this code :

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}

Read file line by line in PowerShell

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}

Kubernetes pod gets recreated when deleted

If you have a job that continues running, you need to search the job and delete it:

kubectl get job --all-namespaces | grep <name>

and

kubectl delete job <job-name>

Entity Framework Core add unique constraint code-first

Ef core support unique configuration.

protected override void OnModelCreating(ModelBuilder builder)
{
  builder.Entity<Account>()
    .HasIndex(account => account.Email)
      .IsUnique();
}

Ef core support multiple unique keys

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<Account>()
      .HasKey(account => new { account.Id, account.Email, account.RoleId });
}

Don't forget run ef core command to make migration and update the database

>> dotnet ef migrations add MigrationName -c YourDbContextName
>> dotnet ef database update -c YourDbContextName

What does the "+=" operator do in Java?

It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

ex :-

To use your example:

The binary representation of 5 is 0101. The binary representation of 4 is 0100.

A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

How to convert string to string[]?

A string holds one value, but a string[] holds many strings, as it's an array of string.

See more here

What is causing "Unable to allocate memory for pool" in PHP?

Looking at the internets there can be various of causes. In my case leaving everything default except...

apc.shm_size = 64M

...cleared the countless warnings that I was getting earlier.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How do I fix "The expression of type List needs unchecked conversion...'?

Even easier

return new ArrayList<?>(getResultOfHibernateCallback(...))

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk

java.lang.IllegalArgumentException: contains a path separator

I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!

 public class MyClass {    

 private String state;
 public File myFilename;

 @Override
 protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
    super.onCreate(savedInstanceState);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
        if (!myFilename.exists()) {
            myFilename.mkdirs();
        }
    }
 }

 public void myMethod {

 File fileTo = new File(myFilename.toString() + "/myPic.png");  
 // use fileTo object to save your file in your new directory that was created in the onCreate method
 }
}

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

In my experience, this message occurs when the primary file (.mdf) has no space to save the metadata of the database. This file include the system tables and they only save their data into it.

Make some space in the file and the commands works again. That's all, Enjoy

Bootstrap button - remove outline on Chrome OS X

In bootstrap 4 the outline is no longer used, but the box-shadow. If it is your case, just do the following:

.btn:focus {
    box-shadow: none;
}

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

How to save password when using Subversion from the console

Just to emphasize what Tomasz Gandor and Domain said about having the right version of svn and that it was compiled to enable plain text password storage, you need verify what you have:

svn --version
svn, version 1.9.7 (r1800392)
...
WARNING: Plaintext password storage is enabled!
...

The following authentication credential caches are available:

* Plaintext cache in /gr/home/ffvdqb/.subversion
* GPG-Agent

Versus:

svn --version
svn, version 1.12.2 (r1863366)
...

The following authentication credential caches are available:

* Gnome Keyring
* GPG-Agent
* KWallet (KDE)

Once you see that your version of svn was enabled for plain text password storage, then apply all the rest of the answers here.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Remove the :iml file found in java and test folders inside the project and invalidate and restart .

It will ask can I remove the projects . Put Yes. The error will goes off.

How to skip a iteration/loop in while-loop

Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html

Open local folder from link

Only IE6-8 - there's an ActiveX workaround this local-files issue in JavaScript:

        function OpenImage(filePath)
        {
            var myshell = new ActiveXObject("WScript.shell");
            myshell.run(filePath, 1, true); 
        }

What are FTL files

'ftl' stands for freemarker. It combines server side objects and view side (HTML/JQuery) contents into a single viewable template on the client browser.
Some documentation which might help:

http://freemarker.org/docs/

Tutorials:

http://www.vogella.com/tutorials/FreeMarker/article.html

http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/

Add custom icons to font awesome

If you want some icons (or all) from font-awesome including yout custom svg icons you can:

1- Go to http://fontawesome.io/ Download the zip and extract-it for example in your Desktop.

2- Go to http://fontastic.me/ use your email to create an account.

3- Once you have been logged-in click on the header option: Add More Icons.

4- Select the SVG of font-awesome located in your extracted zip inside fonts.

5- Repeat the procces uploading your own svg files.

6- Inside Home (at the header of the page) Select the icons you want to download, customize them to give your custom names and select publish to have a link or download the fonts and css.

Sorry about my english ! :D

Visual Studio: How to break on handled exceptions?

Check Managing Exceptions with the Debugger page, it explains how to set this up.

Essentially, here are the steps (during debugging):

  1. On the Debug menu, click Exceptions.

  2. In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.

    -or-

    Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.

Initializing C# auto-properties

Update - the answer below was written before C# 6 came along. In C# 6 you can write:

public class Foo
{
    public string Bar { get; set; } = "bar";
}

You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):

public class Foo
{
    public string Bar { get; }

    public Foo(string bar)
    {
        Bar = bar;
    }
}

It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)

Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.

This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.

How to check if element has any children in Javascript?

You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.

https://developer.mozilla.org/En/DOM/Node.hasChildNodes

C# Lambda expressions: Why should I use them?

I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.

private ComboBox combo;
private Label label;

public CreateControls()
{
    combo = new ComboBox();
    label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}

void combo_SelectedIndexChanged(object sender, EventArgs e)
{
    label.Text = combo.SelectedValue;
}

thanks to lambda expressions you can use it like this:

public CreateControls()
{
    ComboBox combo = new ComboBox();
    Label label = new Label();
    //some initializing code
    combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}

Much easier.

How can I determine whether a 2D Point is within a Polygon?

For Detecting hit on Polygon we need to test two things:

  1. If Point is inside polygon area. (can be accomplished by Ray-Casting Algorithm)
  2. If Point is on the polygon border(can be accomplished by same algorithm which is used for point detection on polyline(line)).

How can I list all the deleted files in a Git repository?

git log --diff-filter=D --summary

See Find and restore a deleted file in a Git repository

If you don't want all the information about which commit they were removed in, you can just add a grep delete in there.

git log --diff-filter=D --summary | grep delete

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

The 'Compat' library now also supports the generateViewId() method for API levels prior 17.

Just make sure to use a version of the Compat library that is 27.1.0+

For example, in your build.gradle file, put :

implementation 'com.android.support:appcompat-v7:27.1.1

Then you can simply use the generateViewId() from the ViewCompat class instead of the View class as follow:

//Will assign a unique ID myView.id = ViewCompat.generateViewId()

Happy coding !

Linq code to select one item

These are the preferred methods:

var item = Items.SingleOrDefault(x => x.Id == 123);

Or

var item = Items.Single(x => x.Id == 123);

Bootstrap collapse animation not smooth

Adding to @CR Rollyson answer,

In case if you have a collapsible div which has a min-height attribute, it will also cause the jerking. Try removing that attribute from directly collapsible div. Use it in the child div of the collapsible div.

<div class="form-group">
    <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">+ Not Jerky</a>
    <div class="collapse" id="collapseOne" style="padding: 0;">
        <textarea class="form-control" rows="4" style="padding: 20px;">No padding on animated element. Padding on child.</textarea>
    </div>
</div>

Fiddle

Adjust icon size of Floating action button (fab)

off of @IRadha's answer in vector drawable setting android:height="_dp" and setting the scale type to android:scaleType="center" sets the drawable to whatever size was set

What is the difference between Numpy's array() and asarray() functions?

Here's a simple example that can demonstrate the difference.

The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.

import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)

The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build

Error: Cannot find module 'ejs'

I my case, I just added ejs manually in package.json:

 {
   "name": "myApp"
   "dependencies": {
     "express": "^4.12.2",
     "ejs": "^1.0.0"
   }
 }

And run npm install (may be you need run it with sudo) Please note, that ejs looks views directory by default

Create Test Class in IntelliJ

  1. Right click on project then select new->directory. Create a new directory and name it "test".
  2. Right click on "test" folder then select Mark Directory As->Test Sources Root
  3. Click on Navigate->Test->Create New Test
    Select Testing library(JUnit4 or any)
    Specify Class Name
    Select Member

That's it. We can modify the directory structure as per our need. Good luck!

Storing WPF Image Resources

I found to be the best practice of using images, videos, etc. is:

  • Change your files "Build action" to "Content". Be sure to check Copy to build directory.
    • Found on the "Right-Click" menu at the Solution Explorer window.
  • Image Source in the following format:
    • "/«YourAssemblyName»;component/«YourPath»/«YourImage.png»"

Example

<Image Source="/WPFApplication;component/Images/Start.png" />

Benefits:

  • Files are not embedded into the assembly.
    • The Resource Manager will raise some memory overflow problems with too many resources (at build time).
  • Can be called between assemblies.

What does it mean if a Python object is "subscriptable" or not?

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

Using Java 8 to convert a list of objects into a string obtained from the toString() method

Just in case anyone is trying to do this without java 8, there is a pretty good trick. List.toString() already returns a collection that looks like this:

[1,2,3]

Depending on your specific requirements, this can be post-processed to whatever you want as long as your list items don't contain [] or , .

For instance:

list.toString().replace("[","").replace("]","") 

or if your data might contain square brackets this:

String s=list.toString();
s = s.substring(1,s.length()-1) 

will get you a pretty reasonable output.

One array item on each line can be created like this:

list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")

I used this technique to make html tooltips from a list in a small app, with something like:

list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")

If you have an array then start with Arrays.asList(list).toString() instead

I'll totally own the fact that this is not optimal, but it's not as inefficient as you might think and is pretty straightforward to read and understand. It is, however, quite inflexible--in particular don't try to separate the elements with replaceAll if your data might contain commas and use the substring version if you have square brackets in your data, but for an array of numbers it's pretty much perfect.

change pgsql port

You can also change the port when starting up:

$ pg_ctl -o "-F -p 5433" start

Or

$ postgres -p 5433

More about this in the manual.

Redirect From Action Filter Attribute

It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute. If so, you should make sure that you inherit that, and not ActionFilterAttribute, in order to let ASP.NET MVC do more of the work for you.

Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Do whatever checking you need here

        // If you want the base check as well (against users/roles) call
        base.OnAuthorization(filterContext);
    }
}

There is a good question with an answer with more details here on SO.