Programs & Examples On #Member

A member is an element of an object in the object-oriented programming paradigm.

C++ callback using class member

MyClass and YourClass could both be derived from SomeonesClass which has an abstract (virtual) Callback method. Your addHandler would accept objects of type SomeonesClass and MyClass and YourClass can override Callback to provide their specific implementation of callback behavior.

invalid use of non-static member function

You shall pass a this pointer to tell the function which object to work on because it relies on that as opposed to a static member function.

cout is not a member of std

Also remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around

#include <iostream>
#include "stdafx.h"

php static function

In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.

Static nested class in Java, why?

Adavantage of inner class--

  1. one time use
  2. supports and improves encapsulation
  3. readibility
  4. private field access

Without existing of outer class inner class will not exist.

class car{
    class wheel{

    }
}

There are four types of inner class.

  1. normal inner class
  2. Method Local Inner class
  3. Anonymous inner class
  4. static inner class

point ---

  1. from static inner class ,we can only access static member of outer class.
  2. Inside inner class we cananot declare static member .
  3. inorder to invoke normal inner class in static area of outer class.

    Outer 0=new Outer(); Outer.Inner i= O.new Inner();

  4. inorder to invoke normal inner class in instance area of outer class.

    Inner i=new Inner();

  5. inorder to invoke normal inner class in outside of outer class.

    Outer 0=new Outer(); Outer.Inner i= O.new Inner();

  6. inside Inner class This pointer to inner class.

    this.member-current inner class outerclassname.this--outer class

  7. for inner class applicable modifier is -- public,default,

    final,abstract,strictfp,+private,protected,static

  8. outer$inner is the name of inner class name.

  9. inner class inside instance method then we can acess static and instance field of outer class.

10.inner class inside static method then we can access only static field of

outer class.

class outer{

    int x=10;
    static int y-20;

    public void m1() {
        int i=30;
        final j=40;

        class inner{

            public void m2() {
                // have accees x,y and j
            }
        }
    }
}

An object reference is required to access a non-static member

playSound is a static method in your class, but you are referring to members like audioSounds or minTime which are not declared static so they would require a SoundManager sm = new SoundManager(); to operate as sm.audioSounds or sm.minTime respectively

Solution:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

Non-static variable cannot be referenced from a static context

Let's analyze your program first.. In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.

Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing. *Static method calls only the static method and use only the static variable. *Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class) *Because of this you call it as a class variable or a class method. And a lot more is there about the "static" keyword. I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).

And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.

Getting IPV4 address from a sockaddr structure

inet_ntoa() works for IPv4; inet_ntop() works for both IPv4 and IPv6.

Given an input struct sockaddr *res, here are two snippets of code (tested on macOS):

Using inet_ntoa()

#include <arpa/inet.h>

struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
char *s = inet_ntoa(addr_in->sin_addr);
printf("IP address: %s\n", s);

Using inet_ntop()

#include <arpa/inet.h>
#include <stdlib.h>

char *s = NULL;
switch(res->sa_family) {
    case AF_INET: {
        struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
        s = malloc(INET_ADDRSTRLEN);
        inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
        break;
    }
    case AF_INET6: {
        struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res;
        s = malloc(INET6_ADDRSTRLEN);
        inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
        break;
    }
    default:
        break;
}
printf("IP address: %s\n", s);
free(s);

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

After adding php directory in User Settings,

{
    "php.validate.executablePath": "C:/phpdirectory/php7.1.8/php.exe",
    "php.executablePath": "C:/phpdirectory/php7.1.8/php.exe"
}

If you still have this error, please verify you have installed :

To test if you PHP exe is ok, open cmd.exe :

c:/prog/php-7.1.8-Win32-VC14-x64/php.exe --version

If PHP fails, a message will be prompted with the error (missing dll for example).

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Can't include C++ headers like vector in Android NDK

Let me add a little to Sebastian Roth's answer.

Your project can be compiled by using ndk-build in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.

Note that your project must be converted to a C/C++ project.

How to convert a C/C++ project

To fix this issue right-click on your project, click Properties

Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport to Include directories

Click Yes when a dialog shows up.

Dialog

Before

Before

After

After

Update #1

GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.

What is the OAuth 2.0 Bearer Token exactly?

Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".

RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))

The syntax for Bearer credentials is as follows:

     b64token    = 1*( ALPHA / DIGIT /
                       "-" / "." / "_" / "~" / "+" / "/" ) *"="
     credentials = "Bearer" 1*SP b64token

It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.

Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.

This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:

The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:

  • Does the authorizer have a way of inspecting the URL, identifying the operation, and looking up some role-based access control database to see if it is allowed? If yes and the request comes through, the service can assume it is allowed, and does not need to verify.
  • Is the token an all-or-nothing, so if the token is correct, all operations are allowed? Then the service doesn't need to verify.
  • Does the token mean "this request is allowed, but here is the UUID for the role, you check whether the operation is allowed". Then it's up to the service to look up that role, and see if the operation is allowed.

References

Array of arrays (Python/NumPy)

a=np.array([[1,2,3],[4,5,6]])

a.tolist()

tolist method mentioned above will return the nested Python list

Unable to connect PostgreSQL to remote database using pgAdmin

For redhat linux

sudo vi /var/lib/pgsql9/data/postgresql.conf 

pgsql9 is the folder for the postgres version installed, might be different for others

changed listen_addresses = '*' from listen_addresses = ‘localhost’ and then

sudo /etc/init.d/postgresql stop
sudo /etc/init.d/postgresql start

How to fix Ora-01427 single-row subquery returns more than one row in select?

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

How to detect browser using angularjs?

I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.

angular.module('myModule').service('browserDetectionService', function() {

 return {
isCompatible: function () {

  var browserInfo = navigator.userAgent;
  var browserFlags =  {};

  browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
  browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
  browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
  browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
  browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;

  browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
  browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
  browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
  browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
  browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
  browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
  browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here

  browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
  browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
  browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;

  return !browserFlags.ISOLD;
  }
};

});

convert string array to string

A slightly faster option than using the already mentioned use of the Join() method is the Concat() method. It doesn't require an empty delimiter parameter as Join() does. Example:

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";

string result = String.Concat(test);

hence it is likely faster.

filename.whl is not supported wheel on this platform

I had the same problem

I downloaded latest pip from https://pypi.org/project/pip/#files

and then.... pip install << downloaded file location >>

then pygame and kivy installation worked... Thanks...!!

Delete specific values from column with where condition?

Try this SQL statement:

update Table set Column =( Column - your val )

android: how to align image in the horizontal center of an imageview?

Try this code :

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/imgBusiness"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/back_detail" />
</LinearLayout>

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Delete newline in Vim

While on the upper line in normal mode, hit Shift+j.

You can prepend a count too, so 3J on the top line would join all those lines together.

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Run / Open VSCode from Mac Terminal

For Mac you can do : View > Command Palette > Shell command > "install code command in path". I'd assume there would be something similar for other OS's. After I do

which code

and it tells me it put it in /usr/local/bin

How to execute a shell script from C in Linux?

A simple way is.....

#include <stdio.h>
#include <stdlib.h>


#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
{
    puts("Will execute sh with the following script :");
    puts(SHELLSCRIPT);
    puts("Starting now:");
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;
}

Say thanks to
Yoda @http://www.unix.com/programming/216190-putting-bash-script-c-program.html

return string with first match Regex

You could embed the '' default in your regex by adding |$:

>>> re.findall('\d+|$', 'aa33bbb44')[0]
'33'
>>> re.findall('\d+|$', 'aazzzbbb')[0]
''
>>> re.findall('\d+|$', '')[0]
''

Also works with re.search pointed out by others:

>>> re.search('\d+|$', 'aa33bbb44').group()
'33'
>>> re.search('\d+|$', 'aazzzbbb').group()
''
>>> re.search('\d+|$', '').group()
''

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

Refresh/reload the content in Div using jquery/ajax

What you want is to load the data again but not reload the div.

You need to make an Ajax query to get data from the server and fill the DIV.

http://api.jquery.com/jQuery.ajax/

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

Creating a recursive method for Palindrome

Here are three simple implementations, first the oneliner:

public static boolean oneLinerPalin(String str){
    return str.equals(new StringBuffer(str).reverse().toString());
}

This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:

public static boolean isPalindrome(String str){

    if(str.isEmpty()) return true;

    int last = str.length() - 1;        

    for(int i = 0; i <= last / 2;i++)
        if(str.charAt(i) != str.charAt(last - i))
            return false;

    return true;
}

And recursively:

public static boolean recursivePalin(String str){
    return check(str, 0, str.length() - 1);
}

private static boolean check (String str,int start,int stop){
    return stop - start < 2 ||
           str.charAt(start) == str.charAt(stop) &&
           check(str, start + 1, stop - 1);
}

How to resize an Image C#

Use below function with below example for changing image size :

//Example : 
System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg");
System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100);

//image size modification unction   
public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight)
{

    Bitmap outputImage = null;
    Graphics graphics = null;
    try
    {
         outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
         graphics = Graphics.FromImage(outputImage);
         graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
         new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

         return outputImage;
     }
     catch (Exception ex)
     {
           return img;
     }
}

Getting mouse position in c#

System.Windows.Forms.Control.MousePosition

Gets the position of the mouse cursor in screen coordinates. "The Position property is identical to the Control.MousePosition property."

UIButton Image + Text IOS

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";

but following code will show label above and image in background

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:@"your image name here"];
button.titleLabel.text = @"your text here";

There is no need to use label and button in same control because UIButton has UILabel and UIimageview properties.

SQL, Postgres OIDs, What are they and why are they useful?

OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.

The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.

Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.

See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F

Data truncation: Data too long for column 'logo' at row 1

Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:

jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false

If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.

EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

Adding a module (Specifically pymorph) to Spyder (Python IDE)

just use '!' before the pip command in spyder terminal and it will be fine

Eg:

!pip install imutils

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

Return 0 if field is null in MySQL

None of the above answers were complete for me. If your field is named field, so the selector should be the following one:

IFNULL(`field`,0) AS field

For example in a SELECT query:

SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`

Hope this can help someone to not waste time.

Finding the length of an integer in C

keep dividing by ten until you get zero, then just output the number of divisions.

int intLen(int x)
{
  if(!x) return 1;
  int i;
  for(i=0; x!=0; ++i)
  {
    x /= 10;
  }
  return i;
}

Regex match text between tags

Use match instead, and the g flag.

str.match(/<b>(.*?)<\/b>/g);

How to apply multiple transforms in CSS?

Some time in the future, we can write it like this:

li:nth-child(2) {
    rotate: 15deg;
    translate:-20px 0px;        
}

This will become especially useful when applying individual classes on an element:

<div class="teaser important"></div>

.teaser{rotate:10deg;}
.important{scale:1.5 1.5;}

This syntax is defined in the in-progress CSS Transforms Level 2 specification, but can't find anything about current browser support other then chrome canary. Hope some day i'll come back and update browser support here ;)

Found the info in this article which you might want to check out regarding workarounds for current browsers.

How to extract URL parameters from a URL with Ruby or Rails?

Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
uri.query_values['param1']
=> 'value1'

(It also apparently handles param encoding/decoding, unlike URI)

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

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

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

you have to tell angular that you updated the content after ngAfterContentChecked you can import ChangeDetectorRef from @angular/core and call detectChanges

import {ChangeDetectorRef } from '@angular/core';

constructor( private cdref: ChangeDetectorRef ) {}


ngAfterContentChecked() {

this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
this.cdref.detectChanges();

 }

CSS Pseudo-classes with inline styles

or you can simply try this in inline css

<textarea style="::placeholder{color:white}"/>

Absolute vs relative URLs

Should I use absolute or relative URLs?

If by absolute URLs you mean URLs including scheme (e.g. http / https) and the hostname (e.g. yourdomain.com) don't ever do that (for local resources) because it will be terrible to maintain and debug.

Let's say you have used absolute URL everywhere in your code like <img src="http://yourdomain.com/images/example.png">. Now what will happen when you are going to:

  • switch to another scheme (e.g. http -> https)
  • switch domain names (test.yourdomain.com -> yourdomain.com)

In the first example what will happen is that you will get warnings about unsafe content being requested on the page. Because all your URLs are hardcoded to use http(://yourdomain.com/images/example.png). And when running your pages over https the browser expects all resources to be loaded over https to prevent leaking of information.

In the second example when putting your site live from the test environment it would mean all resources are still pointing to your test domain instead of your live domain.

So to answer your question about whether to use absolute or relative URLs: always use relative URLs (for local resources).

What are the differences between the different URLs?

First lets have a look at the different types of urls that we can use:

  • http://yourdomain.com/images/example.png
  • //yourdomain.com/images/example.png
  • /images/example.png
  • images/example.png

What resources do these URLs try to access on the server?

In the examples below I assume the website is running from the following location on the server /var/www/mywebsite.

http://yourdomain.com/images/example.png

The above (absolute) URL tries to access the resource /var/www/website/images/example.png. This type of URL is something you would always want to avoid for requesting resources from your own website for reason outlined above. However it does have its place. For example if you have a website http://yourdomain.com and you want to request a resource from an external domain over https you should use this. E.g. https://externalsite.com/path/to/image.png.

//yourdomain.com/images/example.png

This URL is relative based on the current scheme used and should almost always be used when including external resources (images, javascripts etc).

What this type of URL does is use the current scheme of the page it is on. This means that you are on the page http://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in http://yourdomain.com/images/example.png.
When you would have been on the page http**s**://yourdomain.com and on that page is an image tag <img src="//yourdomain.com/images/example.png"> the URL of the image would resolve in https://yourdomain.com/images/example.png.

This prevent loading resources over https when it is not needed and automatically makes sure the resource is requested over https when it is needed.

The above URL resolves in the same manner on the server side as the previous URL:

The above (absolute) URL tries to access the resource /var/www/website/images/example.png.

/images/example.png

For local resources this is the prefered way of referencing them. This is a relative URL based on the document root (/var/www/mywebsite) of your website. This means when you have <img src="/images/example.png"> it will always resolve to /var/www/mywebsite/images/example.png.

If at some point you decide to switch domain it will still work because it is relative.

images/example.png

This is also a relative URL although a bit different than the previous one. This URL is relative to the current path. What this means is that it will resolve to different paths depending on where you are in the site.

For example when you are on the page http://yourdomain.com and you use <img src="images/example.png"> it would resolve on the server to /var/www/mywebsite/images/example.png as expected, however when your are on the page http://yourdomain.com/some/path and you use the exact same image tag it suddenly will resolve to /var/www/mywebsite/some/path/images/example.png.

When to use what?

When requesting external resources you most likely want to use an URL relative to the scheme (unless you want to force a different scheme) and when dealing with local resources you want to use relative URLs based on the document root.

An example document:

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
        <link href='//fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700' rel='stylesheet' type='text/css'>
        <link href="/style/style.css" rel="stylesheet" type="text/css" media="screen"></style>
    </head>
    <body>
        <img src="/images/some/localimage.png" alt="">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    </body>
</html>

Some (kinda) duplicates

C# 4.0: Convert pdf to byte[] and vice versa

Easiest way:

byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

Or something along these lines...

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

The simple solution to this would be to find phpmyadmin.conf file and then find below code inside it,

<Directory "c:/wamp/apps/phpmyadmin3.5.1/">

Options Indexes FollowSymLinks MultiViews

AllowOverride all

    Order Deny,Allow

Deny from all

Allow from 127.0.0.1

</Directory>

Change "Deny from all" to "Allow from all".

OR

Follow below link to get better understanding on how to do it,

WAMP says Forbidden You don't have permission to access /phpmyadmin/ on this server Windows 7 or 8

Enjoy :)

In Visual Studio Code How do I merge between two local branches?

You can do it without using plugins.

In the latest version of vscode that I'm using (1.17.0) you can simply open the branch that you want (from the bottom left menu) then press ctrl+shift+p and type Git: Merge branch and then choose the other branch that you want to merge from (to the current one)

PHP ini file_get_contents external url

Add:

allow_url_fopen=1

in your php.ini file. If you are using shared hosting, create one first.

Where is Maven's settings.xml located on Mac OS?

found it under /Users/username/apache-maven-3.3.9/conf

PHP calculate age

It is a problem when you use strtotime with DD/MM/YYYY. You cant use that format. Instead of it you can use MM/DD/YYYY (or many others like YYYYMMDD or YYYY-MM-DD) and it should work properly.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How do I apply the for-each loop to every character in a String?

Another useful solution, you can work with this string as array of String

for (String s : "xyz".split("")) {
    System.out.println(s);
}

How to display Woocommerce Category image?

You may also used foreach loop for display category image and etc from parent category given by parent id.

for example, i am giving 74 id of parent category, then i will display the image from child category and its slug also.

**<?php
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'child_of'=>'74'));
foreach($catTerms as $catTerm) : ?>
<?php $thumbnail_id = get_woocommerce_term_meta( $catTerm->term_id, 'thumbnail_id', true ); 

// get the image URL
$image = wp_get_attachment_url( $thumbnail_id );  ?>
<li><img src="<?php echo $image; ?>" width="152" height="245"/><span><?php echo $catTerm->name; ?></span></li>
<?php endforeach; ?>** 

(13: Permission denied) while connecting to upstream:[nginx]

Disclaimer

Make sure there are no security implications for your use-case before running this.

Answer

I had a similar issue getting Fedora 20, Nginx, Node.js, and Ghost (blog) to work. It turns out my issue was due to SELinux.

This should solve the problem:

setsebool -P httpd_can_network_connect 1

Details

I checked for errors in the SELinux logs:

sudo cat /var/log/audit/audit.log | grep nginx | grep denied

And found that running the following commands fixed my issue:

sudo cat /var/log/audit/audit.log | grep nginx | grep denied | audit2allow -M mynginx
sudo semodule -i mynginx.pp

Option #2 (untested, but probably more secure)

setsebool -P httpd_can_network_relay 1

https://security.stackexchange.com/questions/152358/difference-between-selinux-booleans-httpd-can-network-relay-and-httpd-can-net

References

http://blog.frag-gustav.de/2013/07/21/nginx-selinux-me-mad/
https://wiki.gentoo.org/wiki/SELinux/Tutorials/Where_to_find_SELinux_permission_denial_details
http://wiki.gentoo.org/wiki/SELinux/Tutorials/Managing_network_port_labels
http://www.linuxproblems.org/wiki/Selinux

Converting stream of int's to char's in java

If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String constructor and provide a Charset, or use InputStreamReader with the appropriate Charset instead.

Simply casting from int to char only works if you want ISO-8859-1, if you're reading bytes from a stream directly.

EDIT: If you are already using a Reader, then casting the return value of read() to char is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int) to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.

How do you reset the stored credentials in 'git credential-osxkeychain'?

I'm not sure how to erase through the command line, but it's fairly easily to do it through the Keychain Access app. Just go to Applications -> Utilties -> Keychain Access, then enter "github.com". You can either delete the invalid item or update the password from with the app.

Set up DNS based URL forwarding in Amazon Route53

I was running into the exact same problem that Saurav described, but I really needed to find a solution that did not require anything other than Route 53 and S3. I created a how-to guide for my blog detailing what I did.

Here is what I came up with.


Objective

Using only the tools available in Amazon S3 and Amazon Route 53, create a URL Redirect that automatically forwards http://url-redirect-example.vivekmchawla.com to the AWS Console sign-in page aliased to "MyAccount", located at https://myaccount.signin.aws.amazon.com/console/ .

This guide will teach you set up URL forwarding to any URL, not just ones from Amazon. You will learn how to set up forwarding to specific folders (like "/console" in my example), and how to change the protocol of the redirect from HTTP to HTTPS (or vice versa).


Step One: Create Your S3 Bucket

Open the S3 Management Console and click "Create Bucket"

Open the S3 management console and click "Create Bucket".


Step Two: Name Your S3 Bucket

Name your S3 Bucket

  1. Choose a Bucket Name. This step is really important! You must name the bucket EXACTLY the same as the URL you want to set up for forwarding. For this guide, I'll use the name "url-redirect-example.vivekmchawla.com".

  2. Select whatever region works best for you. If you don't know, keep the default.

  3. Don't worry about setting up logging. Just click the "Create" button when you're ready.


Step 3: Enable Static Website Hosting and Specify Routing Rules

Enable Static Website Hosting and Specify Routing Rules

  1. In the properties window, open the settings for "Static Website Hosting".
  2. Select the option to "Enable website hosting".
  3. Enter a value for the "Index Document". This object (document) will never be served by S3, and you never have to upload it. Just use any name you want.
  4. Open the settings for "Edit Redirection Rules".
  5. Paste the following XML snippet in it's entirety.

    <RoutingRules>
      <RoutingRule>
        <Redirect>
          <Protocol>https</Protocol>
          <HostName>myaccount.signin.aws.amazon.com</HostName>
          <ReplaceKeyPrefixWith>console/</ReplaceKeyPrefixWith>
          <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
      </RoutingRule>
    </RoutingRules>
    

If you're curious about what the above XML is doing, visit the AWM Documentation for "Syntax for Specifying Routing Rules". A bonus technique (not covered here) is forwarding to specific pages at the destination host, for example http://redirect-destination.com/console/special-page.html. Read about the <ReplaceKeyWith> element if you need this functionality.


Step 4: Make Note of Your Redirect Bucket's "Endpoint"

Make a note of your Redirect Bucket's Endpoint

Make note of the Static Website Hosting "endpoint" that Amazon automatically created for this bucket. You'll need this for later, so highlight the entire URL, then copy and paste it to notepad.

CAUTION! At this point you can actually click this link to check to see if your Redirection Rules were entered correctly, but be careful! Here's why...

Let's say you entered the wrong value inside the <Hostname> tags in your Redirection Rules. Maybe you accidentally typed myaccount.amazon.com, instead of myaccount.signin.aws.amazon.com. If you click the link to test the Endpoint URL, AWS will happily redirect your browser to the wrong address!

After noticing your mistake, you will probably edit the <Hostname> in your Redirection Rules to fix the error. Unfortunately, when you try to click the link again, you'll most likely end up being redirected back to the wrong address! Even though you fixed the <Hostname> entry, your browser is caching the previous (incorrect!) entry. This happens because we're using an HTTP 301 (permanent) redirect, which browsers like Chrome and Firefox will cache by default.

If you copy and paste the Endpoint URL to a different browser (or clear the cache in your current one), you'll get another chance to see if your updated <Hostname> entry is finally the correct one.

To be safe, if you want to test your Endpoint URL and Redirect Rules, you should open a private browsing session, like "Incognito Mode" in Chrome. Copy, paste, and test the Endpoint URL in Incognito Mode and anything cached will go away once you close the session.


Step 5: Open the Route53 Management Console and Go To the Record Sets for Your Hosted Zone (Domain Name)

Open the Route 53 Management Console to Add Record Sets to your Hosted Zone

  1. Select the Hosted Zone (domain name) that you used when you created your bucket. Since I named my bucket "url-redirect-example.vivekmchawla.com", I'm going to select the vivekmchawla.com Hosted Zone.
  2. Click on the "Go to Record Sets" button.

Step 6: Click the "Create Record Set" Button

Click the Create Record Set button

Clicking "Create Record Set" will open up the Create Record Set window on the right side of the Route53 Management Console.


Step 7: Create a CNAME Record Set

Create a CNAME Record Set

  1. In the Name field, enter the hostname portion of the URL that you used when naming your S3 bucket. The "hostname portion" of the URL is everything to the LEFT of your Hosted Zone's name. I named my S3 bucket "url-redirect-example.vivekmchawla.com", and my Hosted Zone is "vivekmchawla.com", so the hostname portion I need to enter is "url-redirect-example".

  2. Select "CNAME - Canonical name" for the Type of this Record Set.

  3. For the Value, paste in the Endpoint URL of the S3 bucket we created back in Step 3.

  4. Click the "Create Record Set" button. Assuming there are no errors, you'll now be able to see a new CNAME record in your Hosted Zone's list of Record Sets.


Step 8: Test Your New URL Redirect

Open up a new browser tab and type in the URL that we just set up. For me, that's http://url-redirect-example.vivekmchawla.com. If everything worked right, you should be sent directly to an AWS sign-in page.

Because we used the myaccount.signin.aws.amazon.com alias as our redirect's destination URL, Amazon knows exactly which account we're trying to access, and takes us directly there. This can be very handy if you want to give a short, clean, branded AWS login link to employees or contractors.

All done! Your URL forwarding should take you to the AWS sign-in page.


Conclusions

I personally love the various AWS services, but if you've decided to migrate DNS management to Amazon Route 53, the lack of easy URL forwarding can be frustrating. I hope this guide helped make setting up URL forwarding for your Hosted Zones a bit easier.

If you'd like to learn more, please take a look at the following pages from the AWS Documentation site.

Cheers!

SyntaxError: Unexpected token o in JSON at position 1

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.

If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.

I faced similar( although in different context), I solved the following error by removing JSON Producer.

    @POST
    @Produces({ **MediaType.APPLICATION_JSON**})
    public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
      return Response.status(200).entity("OK").build();

  }

The response contains "OK" string return. The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.

Removing @Produces({ MediaType.APPLICATION_JSON}) works fine. Output : OK

Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'

O is the first letter of the string

JSON.parse(object) compares with jQuery.parseJSON(object);

JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

Peak-finding algorithm for Python/SciPy

The function scipy.signal.find_peaks, as its name suggests, is useful for this. But it's important to understand well its parameters width, threshold, distance and above all prominence to get a good peak extraction.

According to my tests and the documentation, the concept of prominence is "the useful concept" to keep the good peaks, and discard the noisy peaks.

What is (topographic) prominence? It is "the minimum height necessary to descend to get from the summit to any higher terrain", as it can be seen here:

enter image description here

The idea is:

The higher the prominence, the more "important" the peak is.

Test:

enter image description here

I used a (noisy) frequency-varying sinusoid on purpose because it shows many difficulties. We can see that the width parameter is not very useful here because if you set a minimum width too high, then it won't be able to track very close peaks in the high frequency part. If you set width too low, you would have many unwanted peaks in the left part of the signal. Same problem with distance. threshold only compares with the direct neighbours, which is not useful here. prominence is the one that gives the best solution. Note that you can combine many of these parameters!

Code:

import numpy as np
import matplotlib.pyplot as plt 
from scipy.signal import find_peaks

x = np.sin(2*np.pi*(2**np.linspace(2,10,1000))*np.arange(1000)/48000) + np.random.normal(0, 1, 1000) * 0.15
peaks, _ = find_peaks(x, distance=20)
peaks2, _ = find_peaks(x, prominence=1)      # BEST!
peaks3, _ = find_peaks(x, width=20)
peaks4, _ = find_peaks(x, threshold=0.4)     # Required vertical distance to its direct neighbouring samples, pretty useless
plt.subplot(2, 2, 1)
plt.plot(peaks, x[peaks], "xr"); plt.plot(x); plt.legend(['distance'])
plt.subplot(2, 2, 2)
plt.plot(peaks2, x[peaks2], "ob"); plt.plot(x); plt.legend(['prominence'])
plt.subplot(2, 2, 3)
plt.plot(peaks3, x[peaks3], "vg"); plt.plot(x); plt.legend(['width'])
plt.subplot(2, 2, 4)
plt.plot(peaks4, x[peaks4], "xk"); plt.plot(x); plt.legend(['threshold'])
plt.show()

HTML Code for text checkbox '?'

As this has already been properly answered, I'd just add the following site as a reference:

Unicode Table

You can search for "check", for example.

window.open target _self v window.location.href?

Hopefully someone else is saved by reading this.

We encountered an issue with webkit based browsers doing:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This is old post and I am sorry but even installing of KB2999226 will not help if you don't have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) update package. Without it the installation of KB2999226 returns error "The update is not applicable to your computer". Typically you will get this problem if you have some offline envinroment for example dev virtual machines without access to the WSUS or Windows Update services and old ISO images of Windows 8.1, Server 2012 R2.

How to get JSON response from http.Get

The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target structure.

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

Example use:

type Foo struct {
    Bar string
}

func main() {
    foo1 := new(Foo) // or &Foo{}
    getJson("http://example.com", foo1)
    println(foo1.Bar)

    // alternately:

    foo2 := Foo{}
    getJson("http://example.com", &foo2)
    println(foo2.Bar)
}

You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm

Dynamically update values of a chartjs chart

You also can use destroy() function. Like this

 if( window.myBar!==undefined)
     window.myBar.destroy();
 var ctx = document.getElementById("canvas").getContext("2d");
 window.myBar = new Chart(ctx).Bar(barChartData, {
     responsive : true,
 });

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Don't forget to add sudo otherwise you will get postman.tar.gz: Permission denied error. And unlink postman if you get error like failed to create symbolic link /usr/bin/postman: File exists. So below is the full code:

sudo wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
sudo rm postman.tar.gz

sudo unlink /usr/bin/postman
sudo ln -s /opt/Postman/Postman /usr/bin/postman

Then just run postman in the terminal.

Update multiple rows using select statement

You can use alias to improve the query:

UPDATE t1
   SET t1.Value = t2.Value
  FROM table1 AS t1
         INNER JOIN 
       table2 AS t2
         ON t1.ID = t2.ID

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

What is the difference between --save and --save-dev?

You generally don't want to bloat production package with things that you only intend to use for Development purposes.

Use --save-dev (or -D) option to separate packages such as Unit Test frameworks (jest, jasmine, mocha, chai, etc.)

Any other packages that your app needs for Production, should be installed using --save (or -S).

npm install --save lodash       //prod dependency
npm install -S moment           // "       "
npm install -S opentracing      // "       "

npm install -D jest                 //dev only dependency
npm install --save-dev typescript   //dev only dependency

If you open the package.json file then you will see these entries listed under two different sections:

"dependencies": {
  "lodash": "4.x",
  "moment": "2.x",
  "opentracing": "^0.14.1"
},

"devDependencies": {
    "jest": "22.x",
    "typescript": "^2.8.3"
},

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Downloading jQuery UI CSS from Google's CDN

As Obama says "Yes We Can". Here is the link to it. developers.google.com/#jquery

You need to use

Google

ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/jquery-ui.min.js
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

jQuery CDN

code.jquery.com/ui/[VERSION NO]/jquery-ui.min.js
code.jquery.com/ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

Microsoft

ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/jquery-ui.min.js
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css

Find theme names here http://jqueryui.com/themeroller/ in gallery subtab

.

But i would not recommend you hosting from cdn for the following reasons

  1. Although your chance of hit rate is good in case of Google CDN compared to others but it's still abysmally low.(any cdn not just google).
  2. Loading via cdn you will have 3 requests one for jQuery.js, one for jQueryUI.js and one for your code. You might as will compress it on your local and load it as one single resource.

http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns

Printing out a linked list using toString

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

Clicking the back button twice to exit an activity

@Override public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_MAIN);
   intent.addCategory(Intent.CATEGORY_HOME);

   startActivity(intent);
}

localhost refused to connect Error in visual studio

In my case, Visual Studio 2017 > Tools > Options

In Debugging menu in the side list find Edit and Continue

Uncheck the Enable Edit and Continue check box

This resolves my problem.

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Failed to find target with hash string 'android-25'

the default gradle version 3.3 may have some bugs, I switched to gradle 3.5 and everything got ok

What is the difference between MVC and MVVM?

MVC is a controlled environment and MVVM is a reactive environment.

In a controlled environment you should have less code and a common source of logic; which should always live within the controller. However; in the web world MVC easily gets divided into view creation logic and view dynamic logic. Creation lives on the server and dynamic lives on the client. You see this a lot with ASP.NET MVC combined with AngularJS whereas the server will create a View and pass in a Model and send it to the client. The client will then interact with the View in which case AngularJS steps in to as a local controller. Once submitted the Model or a new Model is passed back to the server controller and handled. (Thus the cycle continues and there are a lot of other translations of this handling when working with sockets or AJAX etc but over all the architecture is identical.)

MVVM is a reactive environment meaning you typically write code (such as triggers) that will activate based on some event. In XAML, where MVVM thrives, this is all easily done with the built in databinding framework BUT as mentioned this will work on any system in any View with any programming language. It is not MS specific. The ViewModel fires (usually a property changed event) and the View reacts to it based on whatever triggers you create. This can get technical but the bottom line is the View is stateless and without logic. It simply changes state based on values. Furthermore, ViewModels are stateless with very little logic, and Models are the State with essentially Zero logic as they should only maintain state. I describe this as application state (Model), state translator (ViewModel), and then the visual state / interaction (View).

In an MVC desktop or client side application you should have a Model, and the Model should be used by the Controller. Based on the Model the controller will modify the View. Views are usually tied to Controllers with Interfaces so that the Controller can work with a variety of Views. In ASP.NET the logic for MVC is slightly backwards on the server as the Controller manages the Models and passes the Models to a selected View. The View is then filled with data based on the model and has it's own logic (usually another MVC set such as done with AngularJS). People will argue and get this confused with application MVC and try to do both at which point maintaining the project will eventually become a disaster. ALWAYS put the logic and control in one location when using MVC. DO NOT write View logic in the code behind of the View (or in the View via JS for web) to accommodate Controller or Model data. Let the Controller change the View. The ONLY logic that should live in a View is whatever it takes to create and run via the Interface it's using. An example of this is submitting a username and password. Whether desktop or web page (on client) the Controller should handle the submit process whenever the View fires the Submit action. If done correctly you can always find your way around an MVC web or local app easily.

MVVM is personally my favorite as it's completely reactive. If a Model changes state the ViewModel listens and translates that state and that's it!!! The View is then listening to the ViewModel for state change and it also updates based on the translation from the ViewModel. Some people call it pure MVVM but there's really only one and I don't care how you argue it and it's always Pure MVVM where the View contains absolutely no logic.

Here's a slight example: Let's say the you want to have a menu slide in on a button press. In MVC you will have a MenuPressed action in your interface. The Controller will know when you click the Menu button and then tell the View to slide in the Menu based on another Interface method such as SlideMenuIn. A round trip for what reason? Incase the Controller decides you can't or wants to do something else instead that's why. The Controller should be in charge of the View with the View doing nothing unless the Controller says so. HOWEVER; in MVVM the slide menu in animation should be built in and generic and instead of being told to slide it in will do so based on some value. So it listens to the ViewModel and when the ViewModel says, IsMenuActive = true (or however) the animation for that takes place. Now, with that said I want to make another point REALLY CLEAR and PLEASE pay attention. IsMenuActive is probably BAD MVVM or ViewModel design. When designing a ViewModel you should never assume a View will have any features at all and just pass translated model state. That way if you decide to change your View to remove the Menu and just show the data / options another way, the ViewModel doesn't care. So how would you manage the Menu? When the data makes sense that's how. So, one way to do this is to give the Menu a list of options (probably an array of inner ViewModels). If that list has data, the Menu then knows to open via the trigger, if not then it knows to hide via the trigger. You simply have data for the menu or not in the ViewModel. DO NOT decide to show / hide that data in the ViewModel.. simply translate the state of the Model. This way the View is completely reactive and generic and can be used in many different situations.

All of this probably makes absolutely no sense if you're not already at least slightly familiar with the architecture of each and learning it can be very confusing as you'll find ALOT OF BAD information on the net.

So... things to keep in mind to get this right. Decide up front how to design your application and STICK TO IT.

If you do MVC, which is great, then make sure you Controller is manageable and in full control of your View. If you have a large View consider adding controls to the View that have different Controllers. JUST DON'T cascade those controllers to different controllers. Very frustrating to maintain. Take a moment and design things separately in a way that will work as separate components... And always let the Controller tell the Model to commit or persist storage. The ideal dependency setup for MVC in is View ? Controller ? Model or with ASP.NET (don't get me started) Model ? View ? Controller ? Model (where Model can be the same or a totally different Model from Controller to View) ...of course the only need to know of Controller in View at this point is mostly for endpoint reference to know where back to pass a Model.

If you do MVVM, I bless your kind soul, but take the time to do it RIGHT! Do not use interfaces for one. Let your View decide how it's going to look based on values. Play with the View with Mock data. If you end up having a View that is showing you a Menu (as per the example) even though you didn't want it at the time then GOOD. You're view is working as it should and reacting based on the values as it should. Just add a few more requirements to your trigger to make sure this doesn't happen when the ViewModel is in a particular translated state or command the ViewModel to empty this state. In your ViewModel DO NOT remove this with internal logic either as if you're deciding from there whether or not the View should see it. Remember you can't assume there is a menu or not in the ViewModel. And finally, the Model should just allow you to change and most likely store state. This is where validation and all will occur; for example, if the Model can't modify the state then it will simply flag itself as dirty or something. When the ViewModel realizes this it will translate what's dirty, and the View will then realize this and show some information via another trigger. All data in the View can be binded to the ViewModel so everything can be dynamic only the Model and ViewModel has absolutely no idea about how the View will react to the binding. As a matter of fact the Model has no idea of a ViewModel either. When setting up dependencies they should point like so and only like so View ? ViewModel ? Model (and a side note here... and this will probably get argued as well but I don't care... DO NOT PASS THE MODEL to the VIEW unless that MODEL is immutable; otherwise wrap it with a proper ViewModel. The View should not see a model period. I give a rats crack what demo you've seen or how you've done it, that's wrong.)

Here's my final tip... Look at a well designed, yet very simple, MVC application and do the same for an MVVM application. One will have more control with limited to zero flexibility while the other will have no control and unlimited flexibility.

A controlled environment is good for managing the entire application from a set of controllers or (a single source) while a reactive environment can be broken up into separate repositories with absolutely no idea of what the rest of the application is doing. Micro managing vs free management.

If I haven't confused you enough try contacting me... I don't mind going over this in full detail with illustration and examples.

At the end of the day we're all programmers and with that anarchy lives within us when coding... So rules will be broken, theories will change, and all of this will end up hog wash... But when working on large projects and on large teams, it really helps to agree on a design pattern and enforce it. One day it will make the small extra steps taken in the beginning become leaps and bounds of savings later.

Adding null values to arraylist

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

Output :

2
null value
5

SQL Query for Student mark functionality

You just have to partition the problem into some bite-sized steps and solve each one by one

First, get the maximum score in each subject:

select SubjectID, max(MarkRate)
from Mark
group by SubjectID;

Then query who are those that has SubjectID with max MarkRate:

select SubjectID, MarkRate, StudentID
from Mark
where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )
order by SubjectID, StudentID;

Then obtain the Student's name, instead of displaying just the StudentID:

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)
where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )
order by SubjectName, StudentName

Database vendors' artificial differences aside with regards to joining and correlating results, the basic step is the same; first, partition the problem in a bite-sized parts, and then integrate them as you solved each one of them, so it won't be as confusing.


Sample data:

CREATE TABLE Student
    (StudentID int, StudentName varchar(6), Details varchar(1));    
INSERT INTO Student
    (StudentID, StudentName, Details)
VALUES
    (1, 'John', 'X'),
    (2, 'Paul', 'X'),
    (3, 'George', 'X'),
    (4, 'Paul', 'X');

CREATE TABLE Subject
    (SubjectID varchar(1), SubjectName varchar(7));    
INSERT INTO Subject
    (SubjectID, SubjectName)
VALUES
    ('M', 'Math'),
    ('E', 'English'),
    ('H', 'History');

CREATE TABLE Mark
    (StudentID int, SubjectID varchar(1), MarkRate int);    
INSERT INTO Mark
    (StudentID, SubjectID, MarkRate)
VALUES
    (1, 'M', 90),
    (1, 'E', 100),
    (2, 'M', 95),
    (2, 'E', 70),
    (3, 'E', 95),
    (3, 'H', 98),
    (4, 'H', 90),
    (4, 'E', 100);

Live test here: http://www.sqlfiddle.com/#!1/08728/3


IN tuple test is still a join by any other name:

Convert this..

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)

where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )

order by SubjectName, StudentName

..to JOIN:

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)

join
  (
  select SubjectID, max(MarkRate) as MarkRate
  from Mark
  group by SubjectID
  ) as x using(SubjectID,MarkRate)

order by SubjectName, StudentName

Contrast this code with the code immediate it. See how JOIN on independent query look like an IN construct? They almost look the same, and IN was just replaced with JOIN keyword; and the replaced IN keyword with JOIN is in fact longer, you need to alias the independent query's column result(max(MarkRate) AS MarkRate) and also the subquery itself (as x). Anyway, this are just matter of style, I prefer IN clause, as the intent is clearer. Using JOINs merely to reflect the data relationship.

Anyway, here's the query that works on all databases that doesn't support tuple test(IN):

select sb.SubjectName, m.MarkRate, st.StudentName
from Mark as m
join Student as st on st.StudentID = m.StudentID
join Subject as sb on sb.SubjectID = m.SubjectID

join
  (
  select SubjectID, max(MarkRate) as MaxMarkRate
  from Mark
  group by SubjectID
  ) as x on m.SubjectID = x.SubjectID AND m.MarkRate = x.MaxMarkRate

order by sb.SubjectName, st.StudentName

Live test: http://www.sqlfiddle.com/#!1/08728/4

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__)) or #pragma pack(1), what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.

Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align option, it isn't enabled by default nor with -Wall or -Wextra. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.

Consider the following:

struct  __attribute__((__packed__)) my_struct {
    char c;
    int i;
};

struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;

Here, the type of a is a packed struct (as defined above). Similarly, b is a pointer to a packed struct. The type of of the expression a.i is (basically) an int l-value with 1 byte alignment. c and d are both normal ints. When reading a.i, the compiler generates code for unaligned access. When you read b->i, b's type still knows it's packed, so no problem their either. e is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall or -Wextra).

How to persist a property of type List<String> in JPA?

Here is the solution for storing a Set using @Converter and StringTokenizer. A bit more checks against @jonck-van-der-kogel solution.

In your Entity class:

@Convert(converter = StringSetConverter.class)
@Column
private Set<String> washSaleTickers;

StringSetConverter:

package com.model.domain.converters;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

@Converter
public class StringSetConverter implements AttributeConverter<Set<String>, String> {
    private final String GROUP_DELIMITER = "=IWILLNEVERHAPPEN=";

    @Override
    public String convertToDatabaseColumn(Set<String> stringList) {
        if (stringList == null) {
            return new String();
        }
        return String.join(GROUP_DELIMITER, stringList);
    }

    @Override
    public Set<String> convertToEntityAttribute(String string) {
        Set<String> resultingSet = new HashSet<>();
        StringTokenizer st = new StringTokenizer(string, GROUP_DELIMITER);
        while (st.hasMoreTokens())
            resultingSet.add(st.nextToken());
        return resultingSet;
    }
}

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

Add a column to existing table and uniquely number them on MS SQL Server

Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick

Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to tell if a file is git tracked (by shell exit code)?

try:

git ls-files --error-unmatch <file name>

will exit with 1 if file is not tracked

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.


Input image:

Detected text object

Top-down view of text document

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None

for c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        displayCnt = approx
        break

# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

How do I use a Boolean in Python?

checker = None 

if some_decision:
    checker = True

if checker:
    # some stuff

[Edit]

For more information: http://docs.python.org/library/functions.html#bool

Your code works too, since 1 is converted to True when necessary. Actually Python didn't have a boolean type for a long time (as in old C), and some programmers still use integers instead of booleans.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Repeat table headers in print mode

Chrome and Opera browsers do not support thead {display: table-header-group;} but rest of others support properly..

What is the best method of handling currency/money?

I am using it on this way:

number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")

Of course that the currency symbol, precision, format and so on depends on each currency.

How to properly export an ES6 class in Node 4?

Several of the other answers come close, but honestly, I think you're better off going with the cleanest, simplest syntax. The OP requested a means of exporting a class in ES6 / ES2015. I don't think you can get much cleaner than this:

'use strict';

export default class ClassName {
  constructor () {
  }
}

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

top -c command in linux to filter processes listed based on processname

In htop, you can simply search with

/process-name

List files recursively in Linux CLI with path relative to the current directory

Find the file called "filename" on your filesystem starting the search from the root directory "/". The "filename"

find / -name "filename" 

How to get current screen width in CSS?

Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

Please refer to the below example. I'm here showing only one component.

login.component.html

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {

      cssProperty:any;
      constructor(private sanitizer: DomSanitizer) { 
        console.log(window.innerWidth);
        console.log(window.innerHeight);
        this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
        this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
      }

    ngOnInit() {

      }

    }

login.component.ts

<div class="home">
    <div class="container" [style]="cssProperty">
        <div class="card">
            <div class="card-header">Login</div>
            <div class="card-body">Please login</div>
            <div class="card-footer">Login</div>
        </div>
    </div>
</div>

login.component.css

.card {
    max-width: 400px;
}
.card .card-body {
    min-height: 150px;
}
.home {
    background-color: rgba(171, 172, 173, 0.575);
}

initialize a numpy array

Whenever you are in the following situation:

a = []
for i in range(5):
    a.append(i)

and you want something similar in numpy, several previous answers have pointed out ways to do it, but as @katrielalex pointed out these methods are not efficient. The efficient way to do this is to build a long list and then reshape it the way you want after you have a long list. For example, let's say I am reading some lines from a file and each row has a list of numbers and I want to build a numpy array of shape (number of lines read, length of vector in each row). Here is how I would do it more efficiently:

long_list = []
counter = 0
with open('filename', 'r') as f:
    for row in f:
        row_list = row.split()
        long_list.extend(row_list)
        counter++
#  now we have a long list and we are ready to reshape
result = np.array(long_list).reshape(counter, len(row_list)) #  desired numpy array

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

What is SOA "in plain english"?

what tends to happen in large organizations is that over time everything is either monolithic or disparate systems everywhere or a little of both. Someone eventually comes in and says we've got a mess. Now, you want to re-design (money to someone) everything to be oriented in a sort of monotlithic depends on who you pay paradigm but at the same time be able to add pieces and parts independently of the master/monolith.

So you buy Oracle's SOA and Oracle becomes the boss of all your parts. All the other players coming in have to work with SOA via a service (web service or whatever it has.) The Oracle monolith takes care of everything (monolith is not meant derogatory). Oh yeah, you got ASP.NET MVC on the front or something else.

main thing is moving things in and out of they system without impact and keeping the vendor Oracle SOA, Microsoft WCF, as the brains of it all. everything's all oop/ood like, fluid, things moving in and out with little to no impact, even human services, not just computers.

To me it just means a bunch of web services (or whatever we call them in the future) with a good front end. And if you own the database just hit the database and stop worrying about buzzwords. it's okay.

Still Reachable Leak detected by Valgrind

For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.

MySQL: How to copy rows, but change a few fields?

INSERT INTO Table
          ( Event_ID
          , col2
           ...
          )
     SELECT "155"
          , col2
           ...
      FROM Table WHERE Event_ID = "120"

Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

The NoSuchMethodError javadoc says this:

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

In your case, this Error is a strong indication that your webapp is using the wrong version of the JAR defining the org.objectweb.asm.* classes.

$(document).on("click"... not working?

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

It's probably not working due to one of:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

For example:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

JSFiddle with jQuery 1.9.1

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

Also had this issue with a Qt .pro generated project. It turned out I forgot to set an environment variable which determines the properties/general/Output Directory. Trivial one, and one to look at in the first place, but sometimes we miss the obvious.

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

$('#embeded_calendar').datepicker({
               minDate: date,
                localToday:datePlusOne,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');

                    deactivateDates(selectedDate);
                   }

           });


              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                setTimeout(function(){ 
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
                       });

                       excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
                   }, 10);
            }

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;
            });
            }

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 
                });
             }

How to delete or change directory of a cloned git repository on a local computer

  1. Go to working directory where you project folder (cloned folder) is placed.
  2. Now delete the folder.
  3. in windows just right click and do delete.
  4. in command line use rm -r "folder name"
  5. this worked for me

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Using the data.table package, which is fast (useful for larger datasets)

https://github.com/Rdatatable/data.table/wiki

library(data.table)
df2 <- setDT(df1)[, lapply(.SD, sum), by=.(year, month), .SDcols=c("x1","x2")]
setDF(df2) # convert back to dataframe

Using the plyr package

require(plyr)
df2 <- ddply(df1, c("year", "month"), function(x) colSums(x[c("x1", "x2")]))

Using summarize() from the Hmisc package (column headings are messy in my example though)

# need to detach plyr because plyr and Hmisc both have a summarize()
detach(package:plyr)
require(Hmisc)
df2 <- with(df1, summarize( cbind(x1, x2), by=llist(year, month), FUN=colSums))

Alter table to modify default value of column

ALTER TABLE {TABLE NAME}
ALTER COLUMN {COLUMN NAME} SET DEFAULT '{DEFAULT VALUES}'

example :

ALTER TABLE RESULT
ALTER COLUMN STATUS SET DEFAULT 'FAIL'

How to position a div in bottom right corner of a browser?

This snippet works in IE7 at least

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
  #foo {
    position: fixed;
    bottom: 0;
    right: 0;
  }
</style>
</head>
<body>
  <div id="foo">Hello World</div>
</body>
</html>

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

In my case, for some reason, vendor folder was disabled on VS Code settings:

    "intelephense.files.exclude": [
        "**/.git/**",
        "**/.svn/**",
        "**/.hg/**",
        "**/CVS/**",
        "**/.DS_Store/**",
        "**/node_modules/**",
        "**/bower_components/**",
        "**/vendor/**", <-- remove this line!
        "**/resources/views/**"
    ],

By removing the line containing vendor folder it works ok on version Intelephense 1.5.4

top nav bar blocking top content of the page

you can set margin based on screen resolution

@media screen and (min-width:768px) and (max-width:991px) {
body {
    margin-top:100px;
}

@media screen and (min-width:992px) and (max-width:1199px) {
  body {
    margin-top:50px;
  }
}

body{
  padding-top: 10%;
}

#nav{
   position: fixed;
   background-color: #8b0000;
   width: 100%;
   top:0;
}

Facebook Graph API error code list

I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):

/**
  * (Date: 30.01.2013)
  *
  * case 1: - "An error occured while creating the share (publishing to wall)"
  *         - "An unknown error has occurred."
  * case 2:    "An unexpected error has occurred. Please retry your request later."
  * case 3:    App must be on whitelist        
  * case 4:    Application request limit reached
  * case 5:    Unauthorized source IP address        
  * case 200:  Requires extended permissions
  * case 240:  Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
  * case 1500: The url you supplied is invalid
  * case 200:
  * case 210:  - Subject must be a page
  *            - User not visible
  */

 /**
  * Error Code 100 several issus:
  * - "Specifying multiple ids with a post method is not supported" (http status 400)
  * - "Error finding the requested story" but it is available via GET
  * - "Invalid post_id"
  * - "Code was invalid or expired. Session is invalid."
  * 
  * Error Code 2: 
  * - Service temporarily unavailable
  */

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

MSVCP140.dll missing

Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.

In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation on runtime library choose /MTd for debug mode and /MT for release mode.

This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.

python 2 instead of python 3 as the (temporary) default python?

You don't want a "temporary default Python"

You want the 2.7 scripts to start with

/usr/bin/env python2.7

And you want the 3.2 scripts to begin with

/usr/bin/env python3.2

There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.

Remember.

Explicit is better than Implicit.

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Regex using javascript to return just numbers

Everything that other solutions have, but with a little validation

// value = '675-805-714'
const validateNumberInput = (value) => { 
    let numberPattern = /\d+/g 
    let numbers = value.match(numberPattern)

    if (numbers === null) {
        return 0
    }  

    return parseInt(numbers.join([]))
}
// 675805714

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

I have fixed a few things here, the "DB_HOST" defined here should be also DB_HOST down there, and the "DB_USER" is called "DB_USER" down there too, check the code always that those are the same.

<?php
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "");

    $db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

This could be due to the service endpoint binding not using the HTTP protocol

In my instance, the error was generated because one of my complex types had a property with no set method.

The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.

Best way to find out why this is happening (in my opinion) is to enable trace logging.

I achieved this by adding the following section to my web.config:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
    <source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
  </sources>
  <trace autoflush="true" />
</system.diagnostics>

Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.

Laravel form html with PUT method for PUT routes

Just use like this somewhere inside the form

@method('PUT')

Output PowerShell variables to a text file

The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.

$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

This creates an array of three items.

$computer,$Speed,$Regcheck
FYKJ
100
YES

vs. concatenation of three items separated by commas.

$computer + "," + $Speed + "," + $Regcheck
FYKJ,100,YES

'tsc command not found' in compiling typescript

A few tips in order

  • restart the terminal
  • restart the machine
  • reinstall nodejs + then run npm install typescript -g

If it still doesn't work run npm config get prefix to see where npm install -g is putting files (append bin to the output) and make sure that they are in the path (the node js setup does this. Maybe you forgot to tick that option).

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

CSS: 100% font size - 100% of what?

Relative to the default size defined to that font.

If someone opens your page on a web browser, there's a default font and font size it uses.

IntelliJ show JavaDocs tooltip on mouse over

IntelliJ IDEA 14.0.3 Ultimate:

Press Ctrl+Alt+S, then choose Editor\General choose Show quick domentation on mouse move

enter image description here

Tips: Look at the top right conner (gear icon) at JavaDoc pop-up window, You can choose:
- Show Toolbar
- Pinded Mode
- Docked Mode
- Floatting Mode
- Split Mode

enter image description here

Animate element to auto height with jQuery

You can always wrap the child elements of #first and save height height of the wrapper as a variable. This might not be the prettiest or most efficient answer, but it does the trick.

Here's a fiddle where I included a reset.

but for your purposes, here's the meat & potatoes:

$(function(){
//wrap everything inside #first
$('#first').children().wrapAll('<div class="wrapper"></div>');
//get the height of the wrapper 
var expandedHeight = $('.wrapper').height();
//get the height of first (set to 200px however you choose)
var collapsedHeight = $('#first').height();
//when you click the element of your choice (a button in my case) #first will animate to height auto
$('button').click(function(){
    $("#first").animate({
        height: expandedHeight            
    })
});
});?

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

ListAGG in SQLSERVER

Starting in SQL Server 2017 the STRING_AGG function is available which simplifies the logic considerably:

select FieldA, string_agg(FieldB, '') as data
from yourtable
group by FieldA

See SQL Fiddle with Demo

In SQL Server you can use FOR XML PATH to get the result:

select distinct t1.FieldA,
  STUFF((SELECT distinct '' + t2.FieldB
         from yourtable t2
         where t1.FieldA = t2.FieldA
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,0,'') data
from yourtable t1;

See SQL Fiddle with Demo

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

How to restore the dump into your running mongodb

For mongoDB database restore use this command here . First go to your mongodb database location such as For Example : cd Downloads/blank_db/v34000 After that Enter mongorestore -d v34000 ./

How can I send a file document to the printer and have it print?

This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

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

Either pass in a Context (so you can access resources), or make the helper methods static.

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

Check whether a value exists in JSON object

Why not JSON.stringify and .includes()?

You can easily check if a JSON object includes a value by turning it into a string and checking the string.

console.log(JSON.stringify(JSONObject).includes("dog"))
--> true

Edit: make sure to check browser compatibility for .includes()

Count frequency of words in a list and sort by frequency

You can use

from collections import Counter

It supports Python 2.7,read more information here

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

use dict

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

But, You have to read the file first, and converted to dict.

2. it's the python docs example,use re and Counter

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

Set active tab style with AngularJS

I recommend using the state.ui module which not only support multiple and nested views but also make this kind of work very easy (code below quoted) :

<ul class="nav">
    <li ng-class="{ active: $state.includes('contacts') }"><a href="#{{$state.href('contacts')}}">Contacts</a></li>
    <li ng-class="{ active: $state.includes('about') }"><a href="#{{$state.href('about')}}">About</a></li>
</ul>

Worth reading.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I tried all existing fixes and not working for me

I re-install python 2.7 (will also install pip) by downloading .pkg at https://www.python.org/downloads/mac-osx/

works for me after installation downloaded pkg

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

java.lang.NoClassDefFoundError: Could not initialize class XXX

NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:

static {
  try {

    ... your init code here

  } catch (Throwable t) {
    LOG.error("Failure during static initialization", t);
    throw t;
  }
}

How to call getClass() from a static method in Java?

I had the same problem ! but to solve it just modify your code as following.

public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}

this worked fine with me hope it will also work fine with you.

Restricting JTextField input to Integers

Here's one approach that uses a keylistener,but uses the keyChar (instead of the keyCode):

http://edenti.deis.unibo.it/utils/Java-tips/Validating%20numerical%20input%20in%20a%20JTextField.txt

 keyText.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE))) {
        getToolkit().beep();
        e.consume();
      }
    }
  });

Another approach (which personally I find almost as over-complicated as Swing's JTree model) is to use Formatted Text Fields:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

Go Back to Previous Page

I think button onclick="history.back();" is one way to solve the problem. But it might not work in the following cases.

  1. If the page gets refreshed or reloaded.

  2. If the user opens the link in a new page.

To overcome these, the following code could be used if you know which page you have to return to. E.g. If you have a no of links on one page and the back button is to be used to return to that page.

<input type="button" onclick="document.location.href='filename';" value="Back" name="button" class="btn">

How to declare an ArrayList with values?

The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.

Example:

ArrayList<String> list = newArrayList("a", "b", "c");

(This assumes import static com.google.common.collect.Lists.newArrayList;)

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

Android soft keyboard covers EditText field

The above solution work perfectly but if you are using Fullscreen activity(translucent status bar) then these solutions might not work. so for fullscreen use this code inside your onCreate function on your Activity.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow();
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN , WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN );
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.TYPE_STATUS_BAR);
    }

Example:

  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow();
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN , WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN );
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.TYPE_STATUS_BAR);
    }
    
    super.onCreate(savedInstanceState);

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Here is an effective solution from didi to solve this problem, Since this bug is very common and difficult to find the cause, It looks more like a system problem, Why can't we ignore it directly?Of course we can ignore it, Here is the sample code:

final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = 
        Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (t.getName().equals("FinalizerWatchdogDaemon") && e instanceof TimeoutException) {
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        }
    }
});

By setting a special default uncaught exception handler, application can change the way in which uncaught exceptions are handled for those threads that would already accept whatever default behavior the system provided. When an uncaught TimeoutException is thrown from a thread named FinalizerWatchdogDaemon, this special handler will block the handler chain, the system handler will not be called, so crash will be avoided.

Through practice, no other bad effects were found. The GC system is still working, timeouts are alleviated as CPU usage decreases.

For more details see: https://mp.weixin.qq.com/s/uFcFYO2GtWWiblotem2bGg

How do I get into a Docker container's shell?

To bash into a running container, type this:

docker exec -t -i container_name /bin/bash

or

docker exec -ti container_name /bin/bash

or

docker exec -ti container_name sh

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

How to change the buttons text using javascript

I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.

1- innerHTML

document.getElementById("ShowButton").innerHTML = 'Show Filter';

You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.

2- innerText

document.getElementById("ShowButton").innerText = 'Show Filter';

This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here

3- textContent

document.getElementById("ShowButton").textContent = 'Show Filter';

This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.

So if a text has to be added like above, then its better to use textContent.

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

How can I create a progress bar in Excel VBA?

I'm loving all the solutions posted here, but I solved this using Conditional Formatting as a percentage-based Data Bar.

Conditional Formatting

This is applied to a row of cells as shown below. The cells that include 0% and 100% are normally hidden, because they're just there to give the "ScanProgress" named range (Left) context.

Scan progress

In the code I'm looping through a table doing some stuff.

For intRow = 1 To shData.Range("tblData").Rows.Count

    shData.Range("ScanProgress").Value = intRow / shData.Range("tblData").Rows.Count
    DoEvents

    ' Other processing

Next intRow

Minimal code, looks decent.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You could unregister the control with

regsvr32 /u badboy.ocx

at the command line. Though i would suggest testing these things in a vmware.

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

You can also add -oHostKeyAlgorithms=+ssh-dss in your ssh line:

ssh -oHostKeyAlgorithms=+ssh-dss user@host

What is the Gradle artifact dependency graph command?

gradlew -q :app:dependencies > dependencies.txt

Will write all dependencies to the file dependencies.txt

Android ListView with onClick items

for what kind of Hell implementing Parcelable ?

he is passing to adapter String[] so

  • get item(String) at position
  • create intent
  • put it as extra
  • start activity
  • in activity get extra

to store product list you can use here HashMap (for example as STATIC object)

example class describing product:

public class Product {
    private String _name;
    private String _description;
    private int _id

    public Product(String name, String description,int id) {
        _name = name;
        _desctription = description;
        _id = id;
    }

    public String getName() {
        return _name;
    }

    public String getDescription() {
        return _description;
    }
}

Product dell = new Product("dell","this is dell",1);

HashMap<String,Product> _hashMap = new HashMap<>();
_hashMap.put(dell.getName(),dell);

then u pass to adapter set of keys as:

String[] productNames =  _hashMap.keySet().toArray(new String[_hashMap.size()]);

when in adapter u return view u set listener like this for example:

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

     Context context = parent.getContext(); 

     String itemName = getItem(position)

     someView.setOnClikListener(new MyOnClickListener(context, itemName));

 }


 private class MyOnClickListener implements View.OnClickListener { 

     private  String _itemName; 
     private  Context _context

     public MyOnClickListener(Context context, String itemName) {
         _context = context;
         _itemName = itemName; 
     }

     @Override 
     public void onClick(View view) {
         //------listener onClick example method body ------
         Intent intent = new Intent(_context, SomeClassToHandleData.class);
         intent.putExtra(key_to_product_name,_itemName);
         _context.startActivity(intent);
     }
 }

then in other activity:

@Override 
public void onCreate(Bundle) {

    String productName = getIntent().getExtra(key_to_product_name);
    Product product = _hashMap.get(productName);

}

*key_to_product_name is a public static String to serve as key for extra

ps. sorry for typo i was in hurry :) ps2. this shoud give you a idea how to do it ps3. when i will have more time i I'll add a detailed description

MY COMMENT:

  • DO NOT USE ANY SWITCH STATEMENT
  • DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)

Creating a ZIP archive in memory using System.IO.Compression

Just another version of zipping without writing any file.

string fileName = "export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
byte[] fileBytes = here is your file in bytes
byte[] compressedBytes;
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";

using (var outStream = new MemoryStream())
{
    using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
    {
        var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
        using (var entryStream = fileInArchive.Open())
        using (var fileToCompressStream = new MemoryStream(fileBytes))
        {
            fileToCompressStream.CopyTo(entryStream);
        }
    }
    compressedBytes = outStream.ToArray();
}

Syncing Android Studio project with Gradle files

I am using Android Studio 4 developing a Fluter/Dart application. There does not seem to be a Sync project with gradle button or file menu item, there is no clean or rebuild either.

I fixed the problem by removing the .idea folder. The suggestion included removing .gradle as well, but it did not exist.

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

jQuery processes the data attribute and converts the values into strings.

Adding processData: false to your options object fixes the error, but I'm not sure if it fixes the problem.

Demo: http://jsfiddle.net/eHmSr/1/

android set button background programmatically

For not changing the size of button on setting the background color:

button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

this didn't change the size of the button and works with the old android versions too.

Get week day name from a given month, day and year individually in SQL Server

You need to construct a date string. You're using / or - operators which do MATH/numeric operations on the numeric return values of DATEPART. Then DATENAME is taking that numeric value and interpreting it as a date.

You need to convert it to a string. For example:

SELECT (
  DATENAME(dw, 
  CAST(DATEPART(m, GETDATE()) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(d, myDateCol1) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(yy, getdate()) AS VARCHAR))
  )

How to sort multidimensional array by column?

below solution worked for me in case of required number is float. Solution:

table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
    Ntable.add_row(row)

'

Fill an array with random numbers

You can simply solve it with a for-loop

private static double[] anArray;

public static void main(String args[]) {
    anArray = new double[10]; // create the Array with 10 slots
    Random rand = new Random(); // create a local variable for Random
    for (int i = 0; i < 10; i++) // create a loop that executes 10 times
    {
        anArray[i] = rand.nextInt(); // each execution through the loop
                                        // generates a new random number and
                                        // stores it in the array at the
                                        // position i of the for-loop
    }
    printArray(); // print the result
}

private static void printArray() {
    for (int i = 0; i < 10; i++) {
        System.out.println(anArray[i]);
    }
}

Next time, please use the search of this site, because this is a very common question on this site, and you can find a lot of solutions on google as well.

Rails 3 migrations: Adding reference column?

Please note that you will most likely need an index on that column too.

class AddUserReferenceToTester < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
    add_index  :testers, :user_id
  end
end

Check if item is in an array / list

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

MongoDB/Mongoose querying at a specific date?

Yeah, Date object complects date and time, so comparing it with just date value does not work.

You can simply use the $where operator to express more complex condition with Javascript boolean expression :)

db.posts.find({ '$where': 'this.created_on.toJSON().slice(0, 10) == "2012-07-14"' })

created_on is the datetime field and 2012-07-14 is the specified date.

Date should be exactly in YYYY-MM-DD format.

Note: Use $where sparingly, it has performance implications.

Adding blank spaces to layout

If you don't need the gap to be exactly 2 lines high, you can add an empty view like this:

    <View
        android:layout_width="fill_parent"
        android:layout_height="30dp">
    </View>

Unable to generate an explicit migration in entity framework

That was happened when i suddenly renamed class of old migration that already exist in db. I checked VCS history, determined that and renamed back. All worked afterwards.

What is the difference between a string and a byte string?

Let's have a simple one-character string 'š' and encode it into a sequence of bytes:

>>> 'š'.encode('utf-8')
b'\xc5\xa1'

For the purpose of this example let's display the sequence of bytes in its binary form:

>>> bin(int(b'\xc5\xa1'.hex(), 16))
'0b1100010110100001'

Now it is generally not possible to decode the information back without knowing how it was encoded. Only if you know that the utf-8 text encoding was used, you can follow the algorithm for decoding utf-8 and acquire the original string:

11000101 10100001
   ^^^^^   ^^^^^^
   00101   100001

You can display the binary number 101100001 back as a string:

>>> chr(int('101100001', 2))
'š'

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

Warning: comparison with string literals results in unspecified behaviour

  1. clang has advantages in error reporting & recovery.

    $ clang errors.c
    errors.c:36:21: warning: result of comparison against a string literal is unspecified (use strcmp instead)
            if (args[i] == "&") //WARNING HERE
                        ^~ ~~~
                strcmp( ,     ) == 0
    errors.c:38:26: warning: result of comparison against a string literal is unspecified (use strcmp instead)
            else if (args[i] == "<") //WARNING HERE
                             ^~ ~~~
                     strcmp( ,     ) == 0
    errors.c:44:26: warning: result of comparison against a string literal is unspecified (use strcmp instead)
            else if (args[i] == ">") //WARNING HERE
                             ^~ ~~~
                     strcmp( ,     ) == 0
    

    It suggests to replace x == y by strcmp(x,y) == 0.

  2. gengetopt writes command-line option parser for you.

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

How to refresh or show immediately in datagridview after inserting?

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

Configure Flask dev server to be visible across the network

go to project path set FLASK_APP=ABC.py SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app "expirement.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Default parameters with C++ constructors

One more thing to consider is whether or not the class could be used in an array:

foo bar[400];

In this scenario, there is no advantage to using the default parameter.

This would certainly NOT work:

foo bar("david", 34)[400]; // NOPE

How can I get the data type of a variable in C#?

GetType() method

int n=34;
Console.WriteLine(n.GetType());
string name="Smome";
Console.WriteLine(name.GetType());

JDK was not found on the computer for NetBeans 6.5

I got this Error today while installing latest Java 10.0.1 ( downloaded JDK in official oracle website) and also downloaded NetBeans version 8.2.

My JDK installation went as smooth as Cake.

But the problem is in Netbeans installation. When I tried to install Netbeans, the error message showed was: "JDK was not installed on your system. Try using Javahome installer argument". But nothing helped me.

Solution:

  • Download JRE alone from their website.
  • Move your NetBeans installer to local drives other than c.
  • Install JRE by clicking the exe file.
  • Set JAVA_HOME, PATH in environment variables.
  • Install NetBeans now.

Stop floating divs from wrapping

The only way I've managed to do this is by using overflow: visible; and width: 20000px; on the parent element. There is no way to do this with CSS level 1 that I'm aware of and I refused to think I'd have to go all gung-ho with CSS level 3. The example below has 18 menus that extend beyond my 1920x1200 resolution LCD, if your screen is larger just duplicate the first tier menu elements or just resize the browser. Alternatively and with slightly lower levels of browser compatibility you could use CSS3 media queries.

Here is a full copy/paste example demonstration...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML5 Menu Demonstration</title>
<style type="text/css">
* {border: 0; box-sizing: content-box; color: #f0f; font-size: 10px; margin: 0; padding: 0; transition-property: background-color, background-image, border, box-shadow, color, float, opacity, text-align, text-shadow; transition-duration: 0.5s; white-space: nowrap;}
a:link {color: #79b; text-decoration: none;}
a:visited {color: #579;}
a:focus, a:hover {color: #fff; text-decoration: underline;}
body {background-color: #444; overflow-x: hidden;}
body > header {background-color: #000; height: 64px; left: 0; position: absolute; right: 0; z-index: 2;}
body > header > nav {height: 32px; margin-left: 16px;}
body > header > nav a {font-size: 24px;}
main {border-color: transparent; border-style: solid; border-width: 64px 0 0; bottom: 0px; left: 0; overflow-x: hidden !important; overflow-y: auto; position: absolute; right: 0; top: 0; z-index: 1;}
main > * > * {background-color: #000;}
main > section {float: left; margin-top: 16px; width: 100%;}
nav[id='menu'] {overflow: visible; width: 20000px;}
nav[id='menu'] > ul {height: 32px;}
nav[id='menu'] > ul > li {float: left; width: 140px;}
nav[id='menu'] > ul > li > ul {background-color: rgba(0, 0, 0, 0.8); display: none; margin-left: -50px; width: 240px;}
nav[id='menu'] a {display: block; height: 32px; line-height: 32px; text-align: center; white-space: nowrap;}
nav[id='menu'] > ul {float: left; list-style:none;}
nav[id='menu'] ul li:hover ul {display: block;}
p, p *, span, span * {color: #fff;}
p {font-size: 20px; margin: 0 14px 0 14px; padding-bottom: 14px; text-indent: 1.5em;}
.hidden {display: none;}
.width_100 {width: 100%;}
</style>
</head>

<body>

<main>
<section style="height: 2000px;"><p>Hover the first menu at the top-left.</p></section>
</main>

<header>
<nav id="location"><a href="">Example</a><span> - </span><a href="">Blog</a><span> - </span><a href="">Browser Market Share</a></nav>
<nav id="menu">
<ul>
<li><a href="" tabindex="2">Menu 1 - Hover</a>
<ul>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
</ul>
</li>
<li><a href="" tabindex="2">Menu 2</a></li>
<li><a href="" tabindex="2">Menu 3</a></li>
<li><a href="" tabindex="2">Menu 4</a></li>
<li><a href="" tabindex="2">Menu 5</a></li>
<li><a href="" tabindex="2">Menu 6</a></li>
<li><a href="" tabindex="2">Menu 7</a></li>
<li><a href="" tabindex="2">Menu 8</a></li>
<li><a href="" tabindex="2">Menu 9</a></li>
<li><a href="" tabindex="2">Menu 10</a></li>
<li><a href="" tabindex="2">Menu 11</a></li>
<li><a href="" tabindex="2">Menu 12</a></li>
<li><a href="" tabindex="2">Menu 13</a></li>
<li><a href="" tabindex="2">Menu 14</a></li>
<li><a href="" tabindex="2">Menu 15</a></li>
<li><a href="" tabindex="2">Menu 16</a></li>
<li><a href="" tabindex="2">Menu 17</a></li>
<li><a href="" tabindex="2">Menu 18</a></li>
</ul>
</nav>
</header>

</body>
</html>

Killing a process using Java

AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))

You can use system-dependant commands like

 Runtime rt = Runtime.getRuntime();
  if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) 
     rt.exec("taskkill " +....);
   else
     rt.exec("kill -9 " +....);

How to print in C

The first argument to printf() is always a string value, known as a format control string. This string may be regular text, such as

printf("Hello, World\n"); // \n indicates a newline character

or

char greeting[] = "Hello, World\n";
printf(greeting);

This string may also contain one or more conversion specifiers; these conversion specifiers indicate that additional arguments have been passed to printf(), and they specify how to format those arguments for output. For example, I can change the above to

char greeting[] = "Hello, World";
printf("%s\n", greeting);

The "%s" conversion specifier expects a pointer to a 0-terminated string, and formats it as text.

For signed decimal integer output, use either the "%d" or "%i" conversion specifiers, such as

printf("%d\n", addNumber(a,b));

You can mix regular text with conversion specifiers, like so:

printf("The result of addNumber(%d, %d) is %d\n", a, b, addNumber(a,b));

Note that the conversion specifiers in the control string indicate the number and types of additional parameters. If the number or types of additional arguments passed to printf() don't match the conversion specifiers in the format string then the behavior is undefined. For example:

printf("The result of addNumber(%d, %d) is %d\n", addNumber(a,b));

will result in anything from garbled output to an outright crash.

There are a number of additional flags for conversion specifiers that control field width, precision, padding, justification, and types. Check your handy C reference manual for a complete listing.

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

fetch(request, {mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request failed', error)  
});

Error:(23, 17) Failed to resolve: junit:junit:4.12

Here is what I did to solve the same problem. I am behind a firewall, which is same issue as yours I suppose. So I had tried removing the

testCompile 'junit:junit:4.12' line 

but that didnt work for me. I tried adding below lines of code:

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
}

Even that did not work for me.

I tried removing (-) and readding (+) Junit4.12 from the library dependencies under Module Settings. Still that did not work for me.

Tried syncing and rebuilding project several times. Still did not work for me.

Finally what I did was to manually download the Junit4.12.jar file from mvnrepository website. I put this jar file in the Androids Workspace under the Project folder inside libs folder. Then go to Module Settings > Dependencies Tab > (+) > File Dependency > under Sleect path window, expand the 'libs' folder and you will find the Jar file you copied inside there. Select the File and click 'OK' Now remove the previous version of junit4.12 from the list of dependencies.

You should have one entry "libs\junit-4.12.jar" in the Dependencies list. Now click 'OK'.

Now Gradle will rebuild the project and you should be good to go.

Hope this helps!

How to get a key in a JavaScript object by its value?

ES6+ One Liners

let key = Object.keys(obj).find(k=>obj[k]===value);

Return all keys with the value:

let keys = Object.keys(obj).filter(k=>obj[k]===value);

Static vs class functions/variables in Swift classes?

Adding to above answers static methods are static dispatch means the compiler know which method will be executed at runtime as the static method can not be overridden while the class method can be a dynamic dispatch as subclass can override these.

Is optimisation level -O3 dangerous in g++?

-O3 option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels ‘-O2’ and ‘-O1’. The ‘-O3’ optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

JavaScript: How to find out if the user browser is Chrome?

Works for me on Chrome on Mac. Seems to be or simpler or more reliable (in case userAgent string tested) than all above.

        var isChrome = false;
        if (window.chrome && !window.opr){
            isChrome = true;
        }
        console.log(isChrome);

Compiling Java 7 code via Maven

You have to check Maven version:

mvn -version

You will find the Java version which Maven uses for compilation. You may need to reset JAVA_HOME if needed.

"Fatal error: Unable to find local grunt." when running "grunt" command

I had this issue on my Windows grunt because I installed the 32 bit version of Node on a 64 bit Windows OS. When I installed the 64bit version specifically, it started working.