Programs & Examples On #Latin9

awk without printing newline

one way

awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm using n (Node version management)

You can install it in two ways

brew install n

or

npm install -g n

You can switch between different version of node and io. Here's an example from my current env when I call n without params:

$ n

  io/3.3.1
  node/0.12.7
  node/4.0.0
  node/5.0.0
? node/5.10.1 

Does java have a int.tryparse that doesn't throw an exception for bad data?

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

Apache shutdown unexpectedly

On your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Xcode Project vs. Xcode Workspace - Differences

Xcode Workspace vs Project

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

Workspace is a set of projects

  1. What are they responsible for?

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

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

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

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

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

[Xcode components]

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This is happening because of the CORS error. CORS stands for Cross Origin Resource Sharing. In simple words, this error occurs when we try to access a domain/resource from another domain.

Read More about it here: CORS error with jquery

To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.

How to get a cross-origin resource sharing (CORS) post request working

These links may help

What's the best way to calculate the size of a directory in .NET?

Directory.GetFiles(@"C:\Users\AliBayat","*",SearchOption.AllDirectories)
.Select (d => new FileInfo(d))
.Select (d => new { Directory = d.DirectoryName,FileSize = d.Length} )
.ToLookup (d => d.Directory )
.Select (d => new { Directory = d.Key,TotalSizeInMB =Math.Round(d.Select (x =>x.FileSize)
.Sum () /Math.Pow(1024.0,2),2)})
.OrderByDescending (d => d.TotalSizeInMB).ToList();

Calling GetFiles with SearchOption.AllDirectories returns the full name of all the files in all the subdirectories of the specified directory. The OS represents the size of files in bytes. You can retrieve the file’s size from its Length property. Dividing it by 1024 raised to the power of 2 gives you the size of the file in megabytes. Because a directory/folder can contain many files, d.Select(x => x.FileSize) returns a collection of file sizes measured in megabytes. The final call to Sum() finds the total size of the files in the specified directory.

Update: the filterMask="." does not work with files without extension

How to create a floating action button (FAB) in android, using AppCompat v21?

There is no longer a need for creating your own FAB nor using a third party library, it was included in AppCompat 22.

https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

Just add the new support library called design in in your gradle-file:

compile 'com.android.support:design:22.2.0'

...and you are good to go:

<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_happy_image" />

Get a list of URLs from a site

Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.

How do I retrieve an HTML element's actual width and height?

If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100

/\d*/.exec(MyElement.style.width)

Usage of \b and \r in C

I have experimented many of the backslash escape characters. \n which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.

Code:

#include <stdio.h>
int main(void){
    printf("Hello World!");
    printf("Goodbye \a");
    printf("Hi \b");
    printf("Yo\f");
    printf("What? \t");
    printf("pewpew");
    return 0;
}

Error: stray '\240' in program

SOLUTION: DELETE THAT LINE OF CODE [*IF YOU COPIED IT FROM ANOTHER SOURCE DOCUMENT] AND TYPE IT YOURSELF.

Error: stray '\240' in program is simply a character encoding error message.

From my experience, it is just a matter of character encoding. For example, if you copy a piece of code from a web page or you first write it in a text editor before copying and pasting in an IDE, it can come with the character encoding of the source document or editor.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

After testing on Juno, Kepler and Luna, I found JD only works for *.class files on build path.

  1. Adding the jar as a lib of an existing project
  2. Go to Preferences->General->Editors->File Associations, set *.class without source to Class File Editor with a cup icon

How to Truncate a string in PHP to the word closest to a certain number of characters?

By using the wordwrap function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:

substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));

One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:

if (strlen($string) > $your_desired_width) 
{
    $string = wordwrap($string, $your_desired_width);
    $string = substr($string, 0, strpos($string, "\n"));
}

The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:

function tokenTruncate($string, $your_desired_width) {
  $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
  $parts_count = count($parts);

  $length = 0;
  $last_part = 0;
  for (; $last_part < $parts_count; ++$last_part) {
    $length += strlen($parts[$last_part]);
    if ($length > $your_desired_width) { break; }
  }

  return implode(array_slice($parts, 0, $last_part));
}

Also, here is the PHPUnit testclass used to test the implementation:

class TokenTruncateTest extends PHPUnit_Framework_TestCase {
  public function testBasic() {
    $this->assertEquals("1 3 5 7 9 ",
      tokenTruncate("1 3 5 7 9 11 14", 10));
  }

  public function testEmptyString() {
    $this->assertEquals("",
      tokenTruncate("", 10));
  }

  public function testShortString() {
    $this->assertEquals("1 3",
      tokenTruncate("1 3", 10));
  }

  public function testStringTooLong() {
    $this->assertEquals("",
      tokenTruncate("toooooooooooolooooong", 10));
  }

  public function testContainingNewline() {
    $this->assertEquals("1 3\n5 7 9 ",
      tokenTruncate("1 3\n5 7 9 11 14", 10));
  }
}

EDIT :

Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:

$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);

Is there a pretty print for PHP?

error_log(print_r($variable,true));

to send to syslog or eventlog for windows

Counting repeated elements in an integer array

private static void getRepeatedNumbers() {

    int [] numArray = {2,5,3,8,1,2,8,3,3,1,5,7,8,12,134};
    Set<Integer> nums = new HashSet<Integer>();
    
    for (int i =0; i<numArray.length; i++) {
        if(nums.contains(numArray[i]))
            continue;
            int count =1;
            for (int j = i+1; j < numArray.length; j++) {
                if(numArray[i] == numArray[j]) {
                    count++;
                }
                    
            }
            System.out.println("The "+numArray[i]+ " is repeated "+count+" times.");
            nums.add(numArray[i]);
        }
    }
    

Border for an Image view in Android?

I almost gave up about this.

This is my condition using glide to load image, see detailed glide issue here about rounded corner transformations and here

I've also the same attributes for my ImageView, for everyone answer here 1, here 2 & here 3

android:cropToPadding="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"`
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/path_to_rounded_drawable"

But still no success.

After researching for awhile, using a foreground attributes from this SO answer here give a result android:foreground="@drawable/all_round_border_white"

unfortunately it giving me the "not nice" border corner like below image:

enter image description here

Show Error on the tip of the Edit Text Android

you could use an onchange event to trigger a validation and then you can display a toast if this is enough for you

.gitignore after commit

No you cannot force a file that is already committed in the repo to be removed just because it is added to the .gitignore

You have to git rm --cached to remove the files that you don't want in the repo. ( --cached since you probably want to keep the local copy but remove from the repo. ) So if you want to remove all the exe's from your repo do

git rm --cached /\*.exe

(Note that the asterisk * is quoted from the shell - this lets git, and not the shell, expand the pathnames of files and subdirectories)

window.location.href not working

Try this

`var url = "http://stackoverflow.com";    
$(location).attr('href',url);`

Or you can do something like this

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

and add a return false at the end of your function call

Add/remove HTML inside div using JavaScript

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

How do I initialize an empty array in C#?

If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.

Use a List<string> instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray() on the variable.

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

If you must create an empty array you can do this:

string[] emptyStringArray = new string[0]; 

Cannot find java. Please use the --jdkhome switch

With the Netbeans 10, commenting out the netbeans_jdkhome setting in .../etc/netbeans.conf doesn't do the job anymore. It is necessary to specify the right directory depending of 32/64 bitness.

E.g. for 64 bit application: netbeans_jdkhome="C:\Program Files\AdoptOpenJDK\jdk8u202-b08"

update query with join on two tables

Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like

Update addresses
Set cid = (
            Select c.id
            From customers As c
            where c.id = a.id
            )
Where Exists    (
                Select 1
                From customers As C1
                Where C1.id = addresses.id
                )

However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:

Update addresses
Set cid = c.id
From addresses As a
    Join customers As c
        On c.id = a.id

How can I force a long string without any blank to be wrapped?

I don't think you can do this with CSS. Instead, at regular 'word lengths' along the string, insert an HTML soft-hyphen:

ACTGATCG&shy;AGCTGAAG&shy;CGCAGTGC&shy;GATGCTTC&shy;GATGATGC&shy;TGACGATG

This will display a hyphen at the end of the line, where it wraps, which may or may not be what you want.

Note Safari seems to wrap the long string in a <textarea> anyway, unlike Firefox.

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

Lock, mutex, semaphore... what's the difference?

Wikipedia has a great section on the differences between Semaphores and Mutexes:

A mutex is essentially the same thing as a binary semaphore and sometimes uses the same basic implementation. The differences between them are:

Mutexes have a concept of an owner, which is the process that locked the mutex. Only the process that locked the mutex can unlock it. In contrast, a semaphore has no concept of an owner. Any process can unlock a semaphore.

Unlike semaphores, mutexes provide priority inversion safety. Since the mutex knows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the mutex.

Mutexes also provide deletion safety, where the process holding the mutex cannot be accidentally deleted. Semaphores do not provide this.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

If for any chance you don't have to Xcode or had to delete it, e.g. in a situation when you needed to free up disc space in order to perform update simply install Xcode from the App Store. Once it'll be done and when you'll be launching this for the first time Xcode will ask you if you'd like to install components, click Install and it'll fix the issue as well.

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

How do I watch a file for changes?

I don't know any Windows specific function. You could try getting the MD5 hash of the file every second/minute/hour (depends on how fast you need it) and compare it to the last hash. When it differs you know the file has been changed and you read out the newest lines.

Two dimensional array list

for (Project project : listOfLists) {
    String nama_project = project.getNama_project();
    if (project.getModelproject().size() > 1) {
        for (int i = 1; i < project.getModelproject().size(); i++) {
            DataModel model = project.getModelproject().get(i);
            int id_laporan = model.getId();
            String detail_pekerjaan = model.getAlamat();
        }
    }
}

Check if datetime instance falls in between other two datetime objects

DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.

// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
    // targetDt is in between d1 and d2
}  

adding child nodes in treeview

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

How to tar certain file types in all subdirectories?

This will handle paths with spaces:

find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

_x000D_
_x000D_
<div>_x000D_
  <div style="width: 20%; float: left;">_x000D_
    <p>Some Contentsssssssssss</p>_x000D_
  </div>_x000D_
  <div style="float: left; width: 80%;">_x000D_
    <textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
  </div>_x000D_
  <div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
 
_x000D_
_x000D_
_x000D_

What is the difference between Amazon SNS and Amazon SQS?

Here's a comparison of the two:

Entity Type

  • SQS: Queue (Similar to JMS)
  • SNS: Topic (Pub/Sub system)

Message consumption

  • SQS: Pull Mechanism - Consumers poll and pull messages from SQS
  • SNS: Push Mechanism - SNS Pushes messages to consumers

Use Case

  • SQS: Decoupling two applications and allowing parallel asynchronous processing
  • SNS: Fanout - Processing the same message in multiple ways

Persistence

  • SQS: Messages are persisted for some (configurable) duration if no consumer is available (maximum two weeks), so the consumer does not have to be up when messages are added to queue.
  • SNS: No persistence. Whichever consumer is present at the time of message arrival gets the message and the message is deleted. If no consumers are available then the message is lost after a few retries.

Consumer Type

  • SQS: All the consumers are typically identical and hence process the messages in the exact same way (each message is processed once by one consumer, though in rare cases messages may be resent)
  • SNS: The consumers might process the messages in different ways

Sample applications

  • SQS: Jobs framework: The Jobs are submitted to SQS and the consumers at the other end can process the jobs asynchronously. If the job frequency increases, the number of consumers can simply be increased to achieve better throughput.
  • SNS: Image processing. If someone uploads an image to S3 then watermark that image, create a thumbnail and also send a Thank You email. In that case S3 can publish notifications to an SNS topic with three consumers listening to it. The first one watermarks the image, the second one creates a thumbnail and the third one sends a Thank You email. All of them receive the same message (image URL) and do their processing in parallel.

How do I read all classes from a Java package in the classpath?

  1. Bill Burke has written a (nice article about class scanning] and then he wrote Scannotation.

  2. Hibernate has this already written:

    • org.hibernate.ejb.packaging.Scanner
    • org.hibernate.ejb.packaging.NativeScanner
  3. CDI might solve this, but don't know - haven't investigated fully yet

.

@Inject Instance< MyClass> x;
...
x.iterator() 

Also for annotations:

abstract class MyAnnotationQualifier
extends AnnotationLiteral<Entity> implements Entity {}

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

Transparent ARGB hex value

Here is the table of % to hex values:

Example: For 85% white, you would use #D9FFFFFF. Here 85% = "D9" & White = "FFFFFF"


100% — FF
95% — F2
90% — E6

85% — D9

80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

How is it calculated?

FF is number written in hex mode. That number represent 255 in decimal. For example, if you want 42% to calculate you need to find 42% of numbeer 255 and convert that number to hex. 255 * 0.42 ~= 107 107 to hex is "6B – maleta

'too many values to unpack', iterating over a dict. key=>string, value=>list

For Python 3.x iteritems has been removed. Use items instead.

for field, possible_values in fields.items():
    print(field, possible_values)

Detect if a page has a vertical scrollbar?

    <script>
    var scrollHeight = document.body.scrollHeight;
    var clientHeight = document.documentElement.clientHeight;
    var hasVerticalScrollbar = scrollHeight > clientHeight;

    alert(scrollHeight + " and " + clientHeight); //for checking / debugging.
    alert("hasVerticalScrollbar is " + hasVerticalScrollbar + "."); //for checking / debugging.
    </script>

This one will tell you if you have a scrollbar or not. I've included some information that may help with debugging, which will display as a JavaScript alert.

Put this in a script tag, after the closing body tag.

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

'Use of Unresolved Identifier' in Swift

Sometimes the compiler gets confused about the syntax in your class. This happens a lot if you paste in source from somewhere else.

Try reducing the "unresolved" source file down to the bare minimum, cleaning and building. Once it builds successfully add all the complexity back to your class.

This has made it go away for me when re-starting Xcode did not work.

python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

Accessing a Dictionary.Keys Key through a numeric index

You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: SortedList Class , SortedList Generic Class .

It is more efficient to use if-return-return or if-else-return?

I know the question is tagged python, but it mentions dynamic languages so thought I should mention that in ruby the if statement actually has a return type so you can do something like

def foo
  rv = if (A > B)
         A+1
       else
         A-1
       end
  return rv 
end

Or because it also has implicit return simply

def foo 
  if (A>B)
    A+1
  else 
    A-1
  end
end

which gets around the style issue of not having multiple returns quite nicely.

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

How can I check if PostgreSQL is installed or not via Linux script?

For many years I used the command:

ps aux | grep postgres

On one hand it is useful (for any process) and gives useful info (but from process POV). But on the other hand it is for checking if the server you know, you already installed is running.

At some point I found this tutorial, where the usage of the locate command is shown. It looks like this command is much more to the point for this case.

How to write inside a DIV box with javascript

I would suggest Jquery:

$("#log").html("Type what you want to be shown to the user");   

How to rename with prefix/suffix?

If it's open to a modification, you could use a suffix instead of a prefix. Then you could use tab-completion to get the original filename and add the suffix.

Otherwise, no this isn't something that is supported by the mv command. A simple shell script could cope though.

Rails: Can't verify CSRF token authenticity when making a POST request

The simplest solution for the problem is do standard things in your controller or you can directely put it into ApplicationController

class ApplicationController < ActionController::Base protect_from_forgery with: :exception, prepend: true end

What is the main difference between PATCH and PUT request?

HTTP verbs are probably one of the most cryptic things about the HTTP protocol. They exist, and there are many of them, but why do they exist?

Rails seems to want to support many verbs and add some verbs that aren't supported by web browsers natively.

Here's an exhaustive list of http verbs: http://annevankesteren.nl/2007/10/http-methods

There the HTTP patch from the official RFC: https://datatracker.ietf.org/doc/rfc5789/?include_text=1

The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request- URI. The set of changes is represented in a format called a "patch document" identified by a media type. If the Request-URI does not point to an existing resource, the server MAY create a new resource, depending on the patch document type (whether it can logically modify a null resource) and permissions, etc.

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

As far as I know, the PATCH verb is not used as it is in rails applications... As I understand this, the RFC patch verb should be used to send patch instructions like when you do a diff between two files. Instead of sending the whole entity again, you send a patch that could be much smaller than resending the whole entity.

Imagine you want to edit a huge file. You edit 3 lines. Instead of sending the file back, you just have to send the diff. On the plus side, sending a patch request could be used to merge files asynchronously. A version control system could potentially use the PATCH verb to update code remotely.

One other possible use case is somewhat related to NoSQL databases, it is possible to store documents. Let say we use a JSON structure to send back and forth data from the server to the client. If we wanted to delete a field, we could use a syntax similar to the one in mongodb for $unset. Actually, the method used in mongodb to update documents could be probably used to handle json patches.

Taking this example:

db.products.update(
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

We could have something like this:

PATCH /products?sku=unknown
{ "$unset": { "quantity": "", "instock": "" } }

Last, but not least, people can say whatever they want about HTTP verbs. There is only one truth, and the truth is in the RFCs.

Android Studio is slow (how to speed up)?

to sum it up

1) in AndroidStudio's settings > compile enable checkbox named Compile independent modules in parallel.

2) Under Help> Edit Custom VM Options I have:

-Xms1024m 
-Xmx4096m # <------ increase this to most of your RAM 
-XX:MaxPermSize=1024m 
-XX:ReservedCodeCacheSize=440m 
-XX:+UseCompressedOops 
-XX:-HeapDumpOnOutOfMemoryError 
-Dfile.encoding=UTF-8

P.S. - Some people say Note, instead of VM options, it's better to combine can be overriden by combining those lines into one line single command in gradle.properties, like this :

org.gradle.jvmargs=-Xms1024m -Xmx4096m ......

3) I have an old dual core with 4GB ram, running ubuntu. Qs command line option I have only --offline (which specifies that the build should operate without accessing network resources). I also enabled the remaining checkboxes and now it's running ok:

  • Make project automatically

  • Use in-process building Configure on demand

  • Check the AndroidStudio's settings, under compile that the checkbox Compile independent modules in parallel is enabled.

Under Vmoptions I have

-Xmx2048m -XX:MaxPermSize=1024

I have an old dual core with 4GB ram, running ubuntu. Qs commandline option I have only --offline , which specifies that the build should operate without accessing network resources. I enabled also the remaining checkboxes:

  1. Make project automatically
  2. Use in-process building
  3. Configure on demand

    and it is running ok

Edit

It is possible to provide additional options through studio.vmoptions located at (just replace X.X with version):

  • Windows: go to %USERPROFILE%\.AndroidStudioX.X\studio.exe.vmoptions (or studio64.exe.vmoptions)

  • Mac: ~/Library/Preferences/.AndroidStudioX.X/studio.vmoptions

  • Linux: ~/.AndroidStudioX.X/studio.vmoptions (and/or studio64.vmoptions)

Increasing the value of -Xmx should help a lot. E.g

-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=256m
-XX:+UseCompressedOops

will assign 4G as max heap, with initial value of 1G

Edit:

On windows the defaults are stored into C:\Program Files\Android\Android Studio\bin\*.vmoptions. The IDE allows you to tweak those values through Help->Edit Custom VM options (thanks to @Code-Read for pointing it out).

EDIT 2:

Android studio 3.5 makes easier to change same of those values. Just go to:

Preferences > Appearance & Behavior > System Settings > Memory Settings

MS-access reports - The search key was not found in any record - on save

Any spaces in the names of the columns in Excel caused the error for me. Once I removed any spaces then it imported with no problems.

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

How do I get Month and Date of JavaScript in 2 digit format?

function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

you don't - not like this. give an id to your tag , lets say it looks like this now :

<h3 id="myHeader"></h3>

then set the value like that :

myHeader.innerText = "public offers";

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In Mac OS X do this in the command prompt from the repo directory:

cd .git
rm index.lock

Update cordova plugins in one command

You don't need remove, just add again.

cordova plugin add https://github.com/apache/cordova-plugin-camera

Query for documents where array size is greater than 1

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

you can use $gt and $lt in query.

ORA-12170: TNS:Connect timeout occurred

[Gathering the answers in the comments]

The problem is that the Oracle service is running on a IP address, and the host is configured with another IP address.

To see the IP address of the Oracle service, issue an lsnrctl status command and check the address reported (in this case is 127.0.0.1, the localhost):

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521)))

To see the host IP address, issue the ipconfig (under windows) or ifconfig (under linux) command.

Howewer, in my installation, the Oracle service does not work if set on localhost address, I must set the real host IP address (for example 192.168.10.X).

To avoid this problem in the future, do not use DHCP for assigning an IP address of the host, but use a static one.

C++ error: "Array must be initialized with a brace enclosed initializer"

You cannot initialize an array to '0' like that

int cipher[Array_size][Array_size]=0;

You can either initialize all the values in the array as you declare it like this:

// When using different values
int a[3] = {10,20,30};

// When using the same value for all members
int a[3] = {0};

// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };

Or you need to initialize the values after declaration. If you want to initialize all values to 0 for example, you could do something like:

for (int i = 0; i < Array_size; i++ ) {
    a[i] = 0;
}

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

SQL Case Sensitive String Compare

You can define attribute as BINARY or use INSTR or STRCMP to perform your search.

How to find which views are using a certain table in SQL Server (2008)?

Simplest way to find used view or stored procedure for the tableName using below query -

exec dbo.dbsearch 'Your_Table_Name'

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Differences between Ant and Maven

Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

Difference between binary semaphore and mutex

While a binary semaphore may be used as a mutex, a mutex is a more specific use-case, in that only the process that locked the mutex is supposed to unlock it. This ownership constraint makes it possible to provide protection against:

  • Accidental release
  • Recursive Deadlock
  • Task Death Deadlock

These constraints are not always present because they degrade the speed. During the development of your code, you can enable these checks temporarily.

e.g. you can enable Error check attribute in your mutex. Error checking mutexes return EDEADLK if you try to lock the same one twice and EPERM if you unlock a mutex that isn't yours.

pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init (&mutex, &attr);

Once initialised we can place these checks in our code like this:

if(pthread_mutex_unlock(&mutex)==EPERM)
 printf("Unlock failed:Mutex not owned by this thread\n");

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

How do I find which program is using port 80 in Windows?

Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb, and then look through output for your program.

BTW, Skype by default tries to use ports 80 and 443 for incoming connections.

You can also run netstat -anb >%USERPROFILE%\ports.txt followed by start %USERPROFILE%\ports.txt to open the port and process list in a text editor, where you can search for the information you want.

You can also use PowerShell to parse netstat output and present it in a better way (or process it any way you want):

$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
    $g = $_.Matches[0].Groups;
    New-Object PSObject |
        Add-Member @{ Protocol =           $g[1].Value  } -PassThru |
        Add-Member @{ LocalAddress =       $g[2].Value  } -PassThru |
        Add-Member @{ LocalPort =     [int]$g[3].Value  } -PassThru |
        Add-Member @{ RemoteAddress =      $g[4].Value  } -PassThru |
        Add-Member @{ RemotePort =         $g[5].Value  } -PassThru |
        Add-Member @{ State =              $g[6].Value  } -PassThru |
        Add-Member @{ PID =           [int]$g[7].Value  } -PassThru |
        Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView

Also it does not require elevation to run.

How can I rebuild indexes and update stats in MySQL innoDB?

Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.

OPTIMIZE TABLE tbl; will rebuild the indexes and do ANALYZE; it takes time.

ANALYZE TABLE tbl; is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.

How do I use raw_input in Python 3

Starting with Python 3, raw_input() was renamed to input().

From What’s New In Python 3.0, Builtins section second item.

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

How do you detect where two line segments intersect?

FWIW, the following function (in C) both detects line intersections and determines the intersection point. It is based on an algorithm in Andre LeMothe's "Tricks of the Windows Game Programming Gurus". It's not dissimilar to some of the algorithm's in other answers (e.g. Gareth's). LeMothe then uses Cramer's Rule (don't ask me) to solve the equations themselves.

I can attest that it works in my feeble asteroids clone, and seems to deal correctly with the edge cases described in other answers by Elemental, Dan and Wodzu. It's also probably faster than the code posted by KingNestor because it's all multiplication and division, no square roots!

I guess there's some potential for divide by zero in there, though it hasn't been an issue in my case. Easy enough to modify to avoid the crash anyway.

// Returns 1 if the lines intersect, otherwise 0. In addition, if the lines 
// intersect the intersection point may be stored in the floats i_x and i_y.
char get_line_intersection(float p0_x, float p0_y, float p1_x, float p1_y, 
    float p2_x, float p2_y, float p3_x, float p3_y, float *i_x, float *i_y)
{
    float s1_x, s1_y, s2_x, s2_y;
    s1_x = p1_x - p0_x;     s1_y = p1_y - p0_y;
    s2_x = p3_x - p2_x;     s2_y = p3_y - p2_y;

    float s, t;
    s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        // Collision detected
        if (i_x != NULL)
            *i_x = p0_x + (t * s1_x);
        if (i_y != NULL)
            *i_y = p0_y + (t * s1_y);
        return 1;
    }

    return 0; // No collision
}

BTW, I must say that in LeMothe's book, though he apparently gets the algorithm right, the concrete example he shows plugs in the wrong numbers and does calculations wrong. For example:

(4 * (4 - 1) + 12 * (7 - 1)) / (17 * 4 + 12 * 10)

= 844/0.88

= 0.44

That confused me for hours. :(

What's the advantage of a Java enum versus a class with public static final fields?

Nobody mentioned the ability to use them in switch statements; I'll throw that in as well.

This allows arbitrarily complex enums to be used in a clean way without using instanceof, potentially confusing if sequences, or non-string/int switching values. The canonical example is a state machine.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!

Passing variable number of arguments around

Let's say you have a typical variadic function you've written. Because at least one argument is required before the variadic one ..., you have to always write an extra argument in usage.

Or do you?

If you wrap your variadic function in a macro, you need no preceding arg. Consider this example:

#define LOGI(...)
    ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))

This is obviously far more convenient, since you needn't specify the initial argument every time.

Changing a specific column name in pandas DataFrame

_x000D_
_x000D_
size = 10
df.rename(columns={df.columns[i]: someList[i] for i in range(size)}, inplace = True)
_x000D_
_x000D_
_x000D_

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

How can I tell if a Java integer is null?

This should help.

Integer startIn = null;

// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
  Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
  e.printStackTrace();
}

// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
  JOptionPane.showMessageDialog(null,
       "You must enter a number between 0-16.","Input Error",
       JOptionPane.ERROR_MESSAGE);                            
}

// (again optional)
if (dontContinue == true) {
  //Do-some-error-fix
}

How do I create an average from a Ruby array?

This method can be helpful.

def avg(arr)
  val = 0.0

  arr.each do |n|
    val += n
  end

  len = arr.length

  val / len 
end

p avg([0,4,8,2,5,0,2,6])

How to reset postgres' primary key sequence when it falls out of sync?

ALTER SEQUENCE sequence_name RESTART WITH (SELECT max(id) FROM table_name); Doesn't work.

Copied from @tardate answer:

SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

How to embed fonts in HTML?

Try Facetype.js, you convert your .TTF font into a Javascript file. Full SEO compatible, supports FF, IE6 and Safari and degrades gracefully on other browsers.

How can I combine flexbox and vertical scroll in a full-height app?

Flexbox spec editor here.

This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.

  • Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.

  • Since your header and footer aren't meant to flex, they should both have flex: none; set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto, so they start at their auto height and can shrink but not grow, but they're also overflow:visible by default, which triggers their default min-height:auto to prevent them from shrinking at all. If you ever set an overflow on them, the behavior of min-height:auto changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article> element.)

  • You can simplify the <article> flex too - just set flex: 1; and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.

How to do an INNER JOIN on multiple columns

something like....

SELECT f.*
      ,a1.city as from
      ,a2.city as to
FROM flights f
INNER JOIN airports a1
ON f.fairport = a1. code
INNER JOIN airports a2
ON f.tairport = a2. code

How to rotate portrait/landscape Android emulator?

See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.

On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Here is another one - ? - Unicode U+141E / CANADIAN SYLLABICS GLOTTAL STOP

SQL Server add auto increment primary key to existing table

This answer is a small addition to the highest voted answer and works for SQL Server. The question requested an auto increment primary key, the current answer does add the primary key, but it is not flagged as auto-increment. The script below checks for the columns, existence, and adds it with the autoincrement flag enabled.

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable' AND COLUMN_NAME = 'PKColumnName')
BEGIN


ALTER TABLE dbo.YourTable
   ADD PKColumnName INT IDENTITY(1,1)

CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

END

GO

React.js: Set innerHTML vs dangerouslySetInnerHTML

You can bind to dom directly

<div dangerouslySetInnerHTML={{__html: '<p>First &middot; Second</p>'}}></div>

Shell - How to find directory of some command?

If you're using Bash or zsh, use this:

type -a lshw

This will show whether the target is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH.

bash$ type -a lshw
lshw is /usr/bin/lshw
bash$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls
bash$ zsh
zsh% type -a which
which is a shell builtin
which is /usr/bin/which

In Bash, for functions type -a will also display the function definition. You can use declare -f functionname to do the same thing (you have to use that for zsh, since type -a doesn't).

Reporting Services export to Excel with Multiple Worksheets

Group your report data based on the category that you want your sheets to be based on. Specify that you want that grouping to start a new page for every new category. Each page becomes a new worksheet in the Excel workbook.

Note: I use SQL Server 2003 and Excel 2003.

Could not locate Gemfile

Here is something you could try.

Add this to any config files you use to run your app.

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
Bundler.require(:default)

Rails and other Rack based apps use this scheme. It happens sometimes that you are trying to run things which are some directories deeper than your root where your Gemfile normally is located. Of course you solved this problem for now but occasionally we all get into trouble with this finding the Gemfile. I sometimes like when you can have all you gems in the .bundle directory also. It never hurts to keep this site address under your pillow. http://bundler.io/

Git Bash won't run my python files?

Add following line in you .bashrc file

############################
# Environment path setting #
############################
export PATH=/c/Python27:/c/Python27/Scripts:$PATH

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

Postgres: clear entire database before re-creating / re-populating from bash script

I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:

$ dropdb development_db_name
$ createdb developmnent_db_name

That's how I do it, actually.

Node.js: what is ENOSPC error and how to solve?

Run the below command to avoid ENOSPC:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

Then execute:

sysctl --system

This will also persist across reboots. Technical Details Source

Examples for string find in Python

Try this:

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break

Can I install/update WordPress plugins without providing FTP access?

Just wanted to add that you must NEVER set the wp-content permission or permission of any folder to 777.

This is what I had to do to:

1) I set the ownership of the wordpress folder (recursively) to the apache user, like so:

# chown -R apache wordpress/

2) I changed the group ownership of the wordpress folder (recursively) to the apache group, like so:

# chgrp -R apache wordpress/

3) give owner full privilege to the directory, like so:

# chmod u+wrx wordpress/*

And that did the job. My wp-content folder has 755 permissions, btw.

TL;DR version:

# chown -R apache:apache wordpress
# chmod u+wrx wordpress/*

Show Current Location and Update Location in MKMapView in Swift

You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.

mapView.userTrackingMode = .follow

See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .

How do I copy the contents of one stream to another?

From .NET 4.5 on, there is the Stream.CopyToAsync method

input.CopyToAsync(output);

This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

From .NET 4.0 on, there's is the Stream.CopyTo method

input.CopyTo(output);

For .NET 3.5 and before

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

How many spaces will Java String.trim() remove?

String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

WCF, Service attribute value in the ServiceHost directive could not be found

I know this is probably the "obvious" answer, but it tripped me up for a bit. Make sure there's a dll for the project in the bin folder. When the service was published, the guy who published it deleted the dlls because he thought they were in the GAC. The one specifically for the project (QS.DialogManager.Communication.IISHost.RecipientService.dll, in this case) wasn't there.

Same error for a VERY different reason.

Border around specific rows in a table?

the trick is with outline property thanks to enigment's answer with little modification

use this class

.row-border{
    outline: thin solid black;
    outline-offset: -1px;
}

then in the HTML

<tr>....</tr>
<tr class="row-border">
    <td>...</td>
    <td>...</td>
</tr>

and the result is enter image description here hope this helps you

Setting up Eclipse with JRE Path

You are most probably missing PATH entries in your windows. Follow this instruction : How do I set or change the PATH system variable?

How do I import material design library to Android Studio?

The latest as of release of API 23 is

compile 'com.android.support:design:23.2.1'

how to redirect to home page

maybe

var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];

is what you're looking for?

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

no module named urllib.parse (How should I install it?)

With the information you have provided, your best bet will be to use Python 3.x.

Your error suggests that the code may have been written for Python 3 given that it is trying to import urllib.parse. If you've written the software and have control over its source code, you should change the import to:

from urlparse import urlparse

urllib was split into urllib.parse, urllib.request, and urllib.error in Python 3.

I suggest that you take a quick look at software collections in CentOS if you are not able to change the imports for some reason. You can bring in Python 3.3 like this:

  1. yum install centos­-release­-SCL
  2. yum install python33
  3. scl enable python33

Check this page out for more info on SCLs

Bootstrap 3 Slide in Menu / Navbar on Mobile

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu

Bootstrap 3

I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/

The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..

http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook

How to do encryption using AES in Openssl

Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.

https://github.com/saju/misc/blob/master/misc/openssl_aes.c

Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro

The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.

and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.

One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..

How to pass data between fragments

Fragment class A

public class CountryListFragment extends ListFragment{

    /** List of countries to be displayed in the ListFragment */

    ListFragmentItemClickListener ifaceItemClickListener;   

    /** An interface for defining the callback method */
    public interface ListFragmentItemClickListener {
    /** This method will be invoked when an item in the ListFragment is clicked */
    void onListFragmentItemClick(int position);
}   

/** A callback function, executed when this fragment is attached to an activity */  
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try{
        /** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
        ifaceItemClickListener = (ListFragmentItemClickListener) activity;          
    }catch(Exception e){
        Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
    }
}

Fragment Class B

public class CountryDetailsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    /** Inflating the layout country_details_fragment_layout to the view object v */
    View v = inflater.inflate(R.layout.country_details_fragment_layout, null);

    /** Getting the textview object of the layout to set the details */ 
    TextView tv = (TextView) v.findViewById(R.id.country_details);      

    /** Getting the bundle object passed from MainActivity ( in Landscape   mode )  or from 
     *  CountryDetailsActivity ( in Portrait Mode )  
     * */
    Bundle b = getArguments();

    /** Getting the clicked item's position and setting corresponding  details in the textview of the detailed fragment */
    tv.setText("Details of " + Country.name[b.getInt("position")]);     

    return v;
    }

}

Main Activity class for passing data between fragments

public class MainActivity extends Activity implements ListFragmentItemClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}


/** This method will be executed when the user clicks on an item in the listview */
@Override
public void onListFragmentItemClick(int position) {

    /** Getting the orientation ( Landscape or Portrait ) of the screen */
    int orientation = getResources().getConfiguration().orientation;


    /** Landscape Mode */
    if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
        /** Getting the fragment manager for fragment related operations */
        FragmentManager fragmentManager = getFragmentManager();

        /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        /** Getting the existing detailed fragment object, if it already exists. 
         *  The fragment object is retrieved by its tag name  *
         */
Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");

        /** Remove the existing detailed fragment object if it exists */
        if(prevFrag!=null)
    fragmentTransaction.remove(prevFrag);           

        /** Instantiating the fragment CountryDetailsFragment */
  CountryDetailsFragment fragment = new CountryDetailsFragment();

        /** Creating a bundle object to pass the data(the clicked item's   position) from the activity to the fragment */ 
        Bundle b = new Bundle();

        /** Setting the data to the bundle object */
        b.putInt("position", position);

        /** Setting the bundle object to the fragment */
        fragment.setArguments(b);           

        /** Adding the fragment to the fragment transaction */
        fragmentTransaction.add(R.id.detail_fragment_container,   fragment,"in.wptrafficanalyzer.country.details");

        /** Adding this transaction to backstack */
        fragmentTransaction.addToBackStack(null);

        /** Making this transaction in effect */
        fragmentTransaction.commit();

    }else{          /** Portrait Mode or Square mode */
        /** Creating an intent object to start the CountryDetailsActivity */
        Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");

        /** Setting data ( the clicked item's position ) to this intent */
        intent.putExtra("position", position);

        /** Starting the activity by passing the implicit intent */
        startActivity(intent);          
      }
    }
 }

Detailde acitivity class

public class CountryDetailsActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Setting the layout for this activity */
    setContentView(R.layout.country_details_activity_layout);

    /** Getting the fragment manager for fragment related operations */
    FragmentManager fragmentManager = getFragmentManager();

    /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
    FragmentTransaction fragmentTransacton = fragmentManager.beginTransaction();

    /** Instantiating the fragment CountryDetailsFragment */
    CountryDetailsFragment detailsFragment = new CountryDetailsFragment();

    /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
    Bundle b = new Bundle();

    /** Setting the data to the bundle object from the Intent*/
    b.putInt("position", getIntent().getIntExtra("position", 0));

    /** Setting the bundle object to the fragment */
    detailsFragment.setArguments(b);

    /** Adding the fragment to the fragment transaction */
    fragmentTransacton.add(R.id.country_details_fragment_container, detailsFragment);       

    /** Making this transaction in effect */
    fragmentTransacton.commit();

    }
}

Array Of Contries

public class Country {

/** Array of countries used to display in CountryListFragment */
static String name[] = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan",
        "Bhutan"
};
}

For More Details visit this link [http://wptrafficanalyzer.in/blog/itemclick-handler-for-listfragment-in-android/]. There are full example ..

How to read if a checkbox is checked in PHP?

Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set

Example:

    if(isset($_POST["testvariabel"]))
     {
       echo "testvariabel has been set!";
     }

How to do relative imports in Python?

Everyone seems to want to tell you what you should be doing rather than just answering the question.

The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.

From PEP 328:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

"Gradle Version 2.10 is required." Error

if your has this error that "supported Gradle version is 2.14.1. Current version is 2.4. ", on terminal. means your should update your gradle.

On Mac OS: you can use brew upgrade gradle

Make div 100% Width of Browser Window

If width:100% works in any cases, just use that, otherwise you can use vw in this case which is relative to 1% of the width of the viewport.

That means if you want to cover off the width, just use 100vw.

Look at the image I draw for you here:

enter image description here

Try the snippet I created for you as below:

_x000D_
_x000D_
.full-width {_x000D_
  width: 100vw;_x000D_
  height: 100px;_x000D_
  margin-bottom: 40px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
  width: 1vw;_x000D_
  height: 100px;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
_x000D_
_x000D_

How to install SQL Server Management Studio 2012 (SSMS) Express?

You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:

https://web.archive.org/web/20170507040411/https://www.microsoft.com/betaexperience/pd/SQLEXPNOCTAV2/enus/default.aspx

This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.

enter image description here

Can you use Microsoft Entity Framework with Oracle?

The answer is "mostly".

We've hit a problem using it where the EF generates code that uses the CROSS and OUTER APPLY operators. This link shows that MS knows its a problem with SQL Server previous to 2005 however, they forget to mention that these operators are not supported by Oracle either.

Create a zip file and download it

// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);

I found this soludtion here and it work for me

Available text color classes in Bootstrap

There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.

.text-black-50 and .text-white-50 are 50% transparent.

_x000D_
_x000D_
.text-body {_x000D_
  color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
  color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
  color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
_x000D_
_x000D_

What are the pros and cons of parquet format compared to other formats?

Avro is a row-based storage format for Hadoop.

Parquet is a column-based storage format for Hadoop.

If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.

If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.

Source

Github: Can I see the number of downloads for a repo?

I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here: http://somsubhra.github.io/github-release-stats/

How to write to a CSV line by line?

To complement the previous answers, I whipped up a quick class to write to CSV files. It makes it easier to manage and close open files and achieve consistency and cleaner code if you have to deal with multiple files.

class CSVWriter():

    filename = None
    fp = None
    writer = None

    def __init__(self, filename):
        self.filename = filename
        self.fp = open(self.filename, 'w', encoding='utf8')
        self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')

    def close(self):
        self.fp.close()

    def write(self, elems):
        self.writer.writerow(elems)

    def size(self):
        return os.path.getsize(self.filename)

    def fname(self):
        return self.filename

Example usage:

mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))

Have fun

How to set image in circle in swift

// code to make the image round


import UIKit

extension UIImageView {
public func maskCircle(anyImage: UIImage) {


    self.contentMode = UIViewContentMode.ScaleAspectFill
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = false
    self.clipsToBounds = true




    // make square(* must to make circle),
    // resize(reduce the kilobyte) and
    // fix rotation.
    //        self.image = prepareImage(anyImage)
}
}

// to call the function from the view controller

self.imgCircleSmallImage.maskCircle(imgCircleSmallImage.image!)

Input type for HTML form for integer

You should change your type to number If you accept decimals first and remove them on keyUp, you might solve this...

$("#state").on('keyup', function(){
    $(this).val($(this).val().replace(".", ''));
})

or

$("#state").on('keyup', function(){
    $(this).val(parseInt($(this).val()));
})

This will remove the period, but there is no 'Integer Type'.

How to block until an event is fired in c#

If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

public class Foo
{
    public delegate void MyEventHandler(object source, MessageEventArgs args);
    public event MyEventHandler _event;
    public string ReadLine()
    {
        return Observable
            .FromEventPattern<MyEventHandler, MessageEventArgs>(
                h => this._event += h,
                h => this._event -= h)
            .Select(ep => ep.EventArgs.Message)
            .First();
    }
    public void SendLine(string message)
    {
        _event(this, new MessageEventArgs() { Message = message });
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message;
}

I can use it like this:

var foo = new Foo();

ThreadPoolScheduler.Instance
    .Schedule(
        TimeSpan.FromSeconds(5.0),
        () => foo.SendLine("Bar!"));

var resp = foo.ReadLine();

Console.WriteLine(resp);

I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

How do I do a not equal in Django queryset filtering?

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

Where does Oracle SQL Developer store connections?

If you don't find the connections.xml then right-click on Connections in the Connections view of SQLDeveloper, and choose Export connections.

Textfield with only bottom border

Probably a duplicate of this post: A customized input text box in html/html5

_x000D_
_x000D_
input {_x000D_
  border: 0;_x000D_
  outline: 0;_x000D_
  background: transparent;_x000D_
  border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
_x000D_
_x000D_

How do we count rows using older versions of Hibernate (~2009)?

Here is what official hibernate docs tell us about this:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

However, it doesn't always return Integer instance, so it is better to use java.lang.Number for safety.

How to create a printable Twitter-Bootstrap page

There's a section of @media print code in the css file (Bootstrap 3.3.1 [UPDATE:] to 3.3.5), this strips virtually all the styling, so you get fairly bland print-outs even when it is working.

For now I've had to resort to stripping out the @media print section from bootstrap.css - which I'm really not happy about but my users want direct screen-grabs so this'll have to do for now. If anyone knows how to suppress it without changes to the bootstrap files I'd be very interested.

Here's the 'offending' code block, starts at line #192:

@media print {
  *,
  *:before,enter code here
  *:after {
    color: #000 !important;
    text-shadow: none !important;
    background: transparent !important;
    -webkit-box-shadow: none !important;
            box-shadow: none !important;
  }
  a,
  a:visited {
    text-decoration: underline;
  }
  a[href]:after {
    content: " (" attr(href) ")";
  }
  abbr[title]:after {
    content: " (" attr(title) ")";
  }
  a[href^="#"]:after,
  a[href^="javascript:"]:after {
    content: "";
  }
  pre,
  blockquote {
    border: 1px solid #999;

    page-break-inside: avoid;
  }
  thead {
    display: table-header-group;
  }
  tr,
  img {
    page-break-inside: avoid;
  }
  img {
    max-width: 100% !important;
  }
  p,
  h2,
  h3 {
    orphans: 3;
    widows: 3;
  }
  h2,
  h3 {
    page-break-after: avoid;
  }
  select {
    background: #fff !important;
  }
  .navbar {
    display: none;
  }
  .btn > .caret,
  .dropup > .btn > .caret {
    border-top-color: #000 !important;
  }
  .label {
    border: 1px solid #000;
  }
  .table {
    border-collapse: collapse !important;
  }
  .table td,
  .table th {
    background-color: #fff !important;
  }
  .table-bordered th,
  .table-bordered td {
    border: 1px solid #ddd !important;
  }
}

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

Correct way to write loops for promise.

function promiseLoop(promiseFunc, paramsGetter, conditionChecker, eachFunc, delay) {
    function callNext() {
        return promiseFunc.apply(null, paramsGetter())
            .then(eachFunc)
    }

    function loop(promise, fn) {
        if (delay) {
            return new Promise(function(resolve) {
                setTimeout(function() {
                    resolve();
                }, delay);
            })
                .then(function() {
                    return promise
                        .then(fn)
                        .then(function(condition) {
                            if (!condition) {
                                return true;
                            }
                            return loop(callNext(), fn)
                        })
                });
        }
        return promise
            .then(fn)
            .then(function(condition) {
                if (!condition) {
                    return true;
                }
                return loop(callNext(), fn)
            })
    }

    return loop(callNext(), conditionChecker);
}


function makeRequest(param) {
    return new Promise(function(resolve, reject) {
        var req = https.request(function(res) {
            var data = '';
            res.on('data', function (chunk) {
                data += chunk;
            });
            res.on('end', function () {
                resolve(data);
            });
        });
        req.on('error', function(e) {
            reject(e);
        });
        req.write(param);
        req.end();
    })
}

function getSomething() {
    var param = 0;

    var limit = 10;

    var results = [];

    function paramGetter() {
        return [param];
    }
    function conditionChecker() {
        return param <= limit;
    }
    function callback(result) {
        results.push(result);
        param++;
    }

    return promiseLoop(makeRequest, paramGetter, conditionChecker, callback)
        .then(function() {
            return results;
        });
}

getSomething().then(function(res) {
    console.log('results', res);
}).catch(function(err) {
    console.log('some error along the way', err);
});

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Neither one of the solutions worked form me. The only one that worked for me in Spring form is:

action="./upload?${_csrf.parameterName}=${_csrf.token}"

REPLACED WITH:

action="./upload?_csrf=${_csrf.token}"

(Spring 5 with enabled csrf in java configuration)

Android Facebook integration with invalid key hash

Use the below code in the onCreate() method of your activity:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "your application package name",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Run this code. This will generate the hash key. Copy this KeyHash in the Facebook application setting, and save changes. Then log into your application. This will work perfectly in the future too.

How do I concatenate or merge arrays in Swift?

Swift 3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

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

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

Apache and IIS side by side (both listening to port 80) on windows2003

You will need to use different IP addresses. The server, whether Apache or IIS, grabs the traffic based on the IP and Port, which ever they are bound to listen to. Once it starts listening, then it uses the headers, such as the server name to filter and determine what site is being accessed. You can't do it will simply changing the server name in the request

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I had twoo users: one that had the sysadmin role, the other one (the problematic one) didn't.

So I logged in with the other user(you can create a new one) and checked the ckeck box 'sysadmin' from: Security --> Logins --> Right ckick on your SQL user name --> Properties --> Server Roles --> make sure that the 'sysadmin' checkbox has the check mark. Press OK and try connecting with the newly checked user.

How to check status of PostgreSQL server Mac OS X

You can run the following command to determine if postgress is running:

$ pg_ctl status

You'll also want to set the PGDATA environment variable.

Here's what I have in my ~/.bashrc file for postgres:

export PGDATA='/usr/local/var/postgres'
export PGHOST=localhost
alias start-pg='pg_ctl -l $PGDATA/server.log start'
alias stop-pg='pg_ctl stop -m fast'
alias show-pg-status='pg_ctl status'
alias restart-pg='pg_ctl reload'

To get them to take effect, remember to source it like so:

$ . ~/.bashrc

Now, try it and you should get something like this:

$ show-pg-status
pg_ctl: server is running (PID: 11030)
/usr/local/Cellar/postgresql/9.2.4/bin/postgres

jQuery/JavaScript: accessing contents of an iframe

I prefer to use other variant for accessing. From parent you can have a access to variable in child iframe. $ is a variable too and you can receive access to its just call window.iframe_id.$

For example, window.view.$('div').hide() - hide all divs in iframe with id 'view'

But, it doesn't work in FF. For better compatibility you should use

$('#iframe_id')[0].contentWindow.$

C# if/then directives for debug vs release

Be sure to define the DEBUG constant in the Project Build Properties. This will enable the #if DEBUG. I don't see a pre-defined RELEASE constant, so that could imply that anything Not in a DEBUG block is RELEASE mode.

Define DEBUG constant in Project Build Properties

How do I fetch only one branch of a remote Git repository?

The answer actually depends on the current list of tracking branches you have. You can fetch a specific branch from remote with git fetch <remote_name> <branch_name> only if the branch is already on the tracking branch list (you can check it with git branch -r).

Let's suppose I have cloned the remote with --single-branch option previously, and in this case the only one tracking branch I have is the "cloned" one. I am a little bit bewildered by advises to tweak git config manually, as well as by typing git remote add <remote_name> <remote_url> commands. As "git remote add" sets up a new remote, it obviously doesn't work with the existing remote repository; supplying "-t branch" options didn't help me.

In case the remote exists, and the branch you want to fetch exists in that remote:

  1. Check with git branch -r whether you can see this branch as a tracking branch. If not (as in my case with a single branch clone), add this branch to the tracking branch list by "git remote set-branches" with --add option:
  • git remote set-branches --add <remote_name> <branch_name>
  1. Fetch the branch you have added from the remote:
  • git fetch <remote_name> <branch_name> Note: only after the new tracking branch was fetched from the remote, you can see it in the tracking branch list with git branch -r.
  1. Create and checkout a new local branch with "checkout --track", which will be given the same "branch_name" as a tracking branch:
  • git checkout --track <remote_name>/<branch_name>

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Question is little old. As this question is very noisy so posting what I did solved with static method as a util. Just copy, paste and use it!

 public static String getFormattedDate(Date date){
            Calendar cal=Calendar.getInstance();
            cal.setTime(date);
            //2nd of march 2015
            int day=cal.get(Calendar.DATE);

            if(!((day>10) && (day<19)))
            switch (day % 10) {
            case 1:  
                return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
            case 2:  
                return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
            case 3:  
                return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
            default: 
                return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
        }
        return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
    }

For testing purose

Example: calling it from main method!

Date date = new Date();
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        for(int i=0;i<32;i++){
          System.out.println(getFormattedDate(cal.getTime()));
          cal.set(Calendar.DATE,(cal.getTime().getDate()+1));
        }

Output:

22nd of February 2018
23rd of February 2018
24th of February 2018
25th of February 2018
26th of February 2018
27th of February 2018
28th of February 2018
1st of March 2018
2nd of March 2018
3rd of March 2018
4th of March 2018
5th of March 2018
6th of March 2018
7th of March 2018
8th of March 2018
9th of March 2018
10th of March 2018
11th of March 2018
12th of March 2018
13th of March 2018
14th of March 2018
15th of March 2018
16th of March 2018
17th of March 2018
18th of March 2018
19th of March 2018
20th of March 2018
21st of March 2018
22nd of March 2018
23rd of March 2018
24th of March 2018
25th of March 2018

Docker is in volume in use, but there aren't any Docker containers

I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q), but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use.

I did a docker system prune and it cleaned up what was needed to remove the last volume:

[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated

Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER              VOLUME NAME
local              uuid
[0]$ docker volume rm uuid
uuid
[0]$

docker system prune

The client and daemon API must both be at least 1.25 to use this command. Use the docker version command on the client to check your client and daemon API versions.

Get index of current item in a PowerShell loop

For PowerShell 3.0 and later, there is one built in :)

foreach ($item in $array) {
    $array.IndexOf($item)
}

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

Eclipse cannot load SWT libraries

On redhat7 :

yum install gtk2 libXtst xorg-x11-fonts-Type1

did the job, because of a swt dependency.

found here

check if file exists in php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

What exactly is node.js used for?

What can we build with NodeJS:

  • REST APIs and Backend Applications
  • Real-Time services (Chat, Games etc)
  • Blogs, CMS, Social Applications.
  • Utilities and Tools
  • Anything that is not CPU intensive.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

How to force Selenium WebDriver to click on element which is not currently visible?

There is also another case when visible element will be recognized as not visible:

  • When the Element is CSS transformed
  • When Parent Element of the Element is CSS transformed

In order to check if element you wan't to interact with is CSS transformed, on CHROME do this:

  1. open inspector
  2. Find interesting element (or more likely its parent element, supposedly div element)
  3. Select 'Computed' tab
  4. if there is a parameter: webkit-transform: matrix( ... ) it means that the element is CSS transformed, and may not be recognized by selenium 2 as a visible element

Page Redirect after X seconds wait using JavaScript

$(document).ready(function() {
    window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});

Most concise way to convert a Set<T> to a List<T>

List<String> l = new ArrayList<String>(listOfTopicAuthors);

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

SLF4J: Class path contains multiple SLF4J bindings

Gradle version;

configurations.all {
    exclude module: 'slf4j-log4j12'
}

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

Another thing to watch out for is double backslashes, since xcopy does not tolerate them in the input path parameter (but it does tolerate them in the output path...).

enter image description here

how to show only even or odd rows in sql server 2008?

Try following

SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;

Fastest way to tell if two files have the same contents in Unix/Linux?

Because I suck and don't have enough reputation points I can't add this tidbit in as a comment.

But, if you are going to use the cmp command (and don't need/want to be verbose) you can just grab the exit status. Per the cmp man page:

If a FILE is '-' or missing, read standard input. Exit status is 0 if inputs are the same, 1 if different, 2 if trouble.

So, you could do something like:

STATUS="$(cmp --silent $FILE1 $FILE2; echo $?)"  # "$?" gives exit status for each comparison

if [[ $STATUS -ne 0 ]]; then  # if status isn't equal to 0, then execute code
    DO A COMMAND ON $FILE1
else
    DO SOMETHING ELSE
fi

EDIT: Thanks for the comments everyone! I updated the test syntax here. However, I would suggest you use Vasili's answer if you are looking for something similar to this answer in readability, style, and syntax.

Get file size before uploading

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

Choose folders to be ignored during search in VS Code

I wanted to search for the term "Stripe" in all files except those within a plugin ("plugin" folder) or within the files ending in ".bak", ".bak2" or ".log" (this is within the wp-contents folder structure of a wordpress install).

I just wanted to do this search one time and very quickly, so I didn't want to alter the search settings of my environment. Here's how I did it (note the double asteriks for the folder):

  • Search Term: Stripe
  • Include Files: {blank}
  • Exclude Files: *.bak*, *.log, **/plugins/**

Here's what it looked like

Remove specific commit

So it sounds like the bad commit was incorporated in a merge commit at some point. Has your merge commit been pulled yet? If yes, then you'll want to use git revert; you'll have to grit your teeth and work through the conflicts. If no, then you could conceivably either rebase or revert, but you can do so before the merge commit, then redo the merge.

There's not much help we can give you for the first case, really. After trying the revert, and finding that the automatic one failed, you have to examine the conflicts and fix them appropriately. This is exactly the same process as fixing merge conflicts; you can use git status to see where the conflicts are, edit the unmerged files, find the conflicted hunks, figure out how to resolve them, add the conflicted files, and finally commit. If you use git commit by itself (no -m <message>), the message that pops up in your editor should be the template message created by git revert; you can add a note about how you fixed the conflicts, then save and quit to commit.

For the second case, fixing the problem before your merge, there are two subcases, depending on whether you've done more work since the merge. If you haven't, you can simply git reset --hard HEAD^ to knock off the merge, do the revert, then redo the merge. But I'm guessing you have. So, you'll end up doing something like this:

  • create a temporary branch just before the merge, and check it out
  • do the revert (or use git rebase -i <something before the bad commit> <temporary branch> to remove the bad commit)
  • redo the merge
  • rebase your subsequent work back on: git rebase --onto <temporary branch> <old merge commit> <real branch>
  • remove the temporary branch

How to get first two characters of a string in oracle query?

select substr(orderno,1,2) from shipment;

You may want to have a look at the documentation too.

How to tell if a <script> tag failed to load

This is how I used a promise to detect loading errors that are emited on the window object:

<script type='module'>
window.addEventListener('error', function(error) {
  let url = error.filename
  url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
  url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
  url = url.substring(url.lastIndexOf("/") + 1, url.length);
  window.scriptLoadReject && window.scriptLoadReject[url] && window.scriptLoadReject[url](error);
}, true);
window.boot=function boot() {
  const t=document.createElement('script');
  t.id='index.mjs';
  t.type='module';
  new Promise((resolve, reject) => {
    window.scriptLoadReject = window.scriptLoadReject || {};
    window.scriptLoadReject[t.id] = reject;
    t.addEventListener('error', reject);
    t.addEventListener('load', resolve); // Careful load is sometimes called even if errors prevent your script from running! This promise is only meant to catch errors while loading the file.
  }).catch((value) => {
    document.body.innerHTML='Error loading ' + t.id + '! Please reload this webpage.<br/>If this error persists, please try again later.<div><br/>' + t.id + ':' + value.lineno + ':' + value.colno + '<br/>' + (value && value.message);
  });
  t.src='./index.mjs'+'?'+new Date().getTime();
  document.head.appendChild(t);
};
</script>
<script nomodule>document.body.innerHTML='This website needs ES6 Modules!<br/>Please enable ES6 Modules and then reload this webpage.';</script>
</head>

<body onload="boot()" style="margin: 0;border: 0;padding: 0;text-align: center;">
  <noscript>This website needs JavaScript!<br/>Please enable JavaScript and then reload this webpage.</noscript>

How to set thousands separator in Java?

DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setDecimalSeparator('|');
formatSymbols.setGroupingSeparator(' ');

String strange = "#,##0.###";
DecimalFormat df = new DecimalFormat(strange, formatSymbols);
df.setGroupingSize(4);

String out = df.format(new BigDecimal(300000).doubleValue());

System.out.println(out);

Best Practice: Software Versioning

Yet another example for the A.B.C approach is the Eclipse Bundle Versioning. Eclipse bundles rather have a fourth segment:

In Eclipse, version numbers are composed of four (4) segments: 3 integers and a string respectively named major.minor.service.qualifier. Each segment captures a different intent:

  • the major segment indicates breakage in the API
  • the minor segment indicates "externally visible" changes
  • the service segment indicates bug fixes and the change of development stream
  • the qualifier segment indicates a particular build

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

I ran into the same issue and solved it by downloading api level 20 using sdk manager and changing every string that points to android-L. I did it because I dont have a kitkat device and don't want to use emulator. See the image download the marked one.

Here's my build config:

apply plugin: 'com.android.application'

android {
compileSdkVersion 20//changed this from default
buildToolsVersion "20.0.0"

defaultConfig {
    applicationId "com.example.subash.test"
    minSdkVersion 12//changed this from default
    targetSdkVersion 20//changed this from default
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Set QLineEdit to accept only numbers

The Regex Validator

So far, the other answers provide solutions for only a relatively finite number of digits. However, if you're concerned with an arbitrary or a variable number of digits you can use a QRegExpValidator, passing a regex that only accepts digits (as noted by user2962533's comment). Here's a minimal, complete example:

#include <QApplication>
#include <QLineEdit>
#include <QRegExpValidator>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QLineEdit le;
    le.setValidator(new QRegExpValidator(QRegExp("[0-9]*"), &le));
    le.show();

    return app.exec();
}

The QRegExpValidator has its merits (and that's only an understatement). It allows for a bunch of other useful validations:

QRegExp("[1-9][0-9]*")    //  leading digit must be 1 to 9 (prevents leading zeroes).
QRegExp("\\d*")           //  allows matching for unicode digits (e.g. for 
                          //    Arabic-Indic numerals such as ???).
QRegExp("[0-9]+")         //  input must have at least 1 digit.
QRegExp("[0-9]{8,32}")    //  input must be between 8 to 32 digits (e.g. for some basic
                          //    password/special-code checks).
QRegExp("[0-1]{,4}")      //  matches at most four 0s and 1s.
QRegExp("0x[0-9a-fA-F]")  //  matches a hexadecimal number with one hex digit.
QRegExp("[0-9]{13}")      //  matches exactly 13 digits (e.g. perhaps for ISBN?).
QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
                          //  matches a format similar to an ip address.
                          //    N.B. invalid addresses can still be entered: "999.999.999.999".     

More On Line-edit Behaviour

According to documentation:

Note that if there is a validator set on the line edit, the returnPressed()/editingFinished() signals will only be emitted if the validator returns QValidator::Acceptable.

Thus, the line-edit will allow the user to input digits even if the minimum amount has not yet been reached. For example, even if the user hasn't inputted any text against the regex "[0-9]{3,}" (which requires at least 3 digits), the line-edit still allows the user to type input to reach that minimum requirement. However, if the user finishes editing without satsifying the requirement of "at least 3 digits", the input would be invalid; the signals returnPressed() and editingFinished() won't be emitted.

If the regex had a maximum-bound (e.g. "[0-1]{,4}"), then the line-edit will stop any input past 4 characters. Additionally, for character sets (i.e. [0-9], [0-1], [0-9A-F], etc.) the line-edit only allows characters from that particular set to be inputted.

Note that I've only tested this with Qt 5.11 on a macOS, not on other Qt versions or operating systems. But given Qt's cross-platform schema...

Demo: Regex Validators Showcase

Find html label associated with a given input

$("label[for='inputId']").text()

This helped me to get the label of an input element using its ID.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work