Programs & Examples On #Blat

Blat is a Win32 command line utility that sends eMail using SMTP or post to usenet using NNTP.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Sending email from Command-line via outlook without having to click send

Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:

$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")

You could then launch the script from the command line as per this example:

powershell.exe -noexit c:\scripts\test.ps1

Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage command, making things easier.

Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.

Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:

Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg  = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
        objOutlookRecip.Type = olTo
        ' Set the Subject, Body, and Importance of the message.
        .Subject = "This is an Automation test with Microsoft Outlook"
        .Body = "This is the body of the message." &vbCrLf & vbCrLf
        .Importance = olImportanceHigh  'High importance

        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
        End If

        For Each ObjOutlookRecip In .Recipients
            objOutlookRecip.Resolve
        Next

        .Save
        .Send
    End With
    Set objOutlook = Nothing
End Sub

Then, launch Outlook from the command line with the /autorun parameter, as per this answer (alter path/macroname as necessary):

C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname

Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

JavaScript single line 'if' statement - best syntax, this alternative?

As a lot of people have said, if you're looking for an actual 1 line if then:

    if (Boolean_expression) do.something();

is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):

    (Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();

ALSO:

    var something = (Boolean_expression) ? trueValueHardware : falseATRON;

However, I saw one very cool example. Shouts to @Peter-Oslson for &&

    (Boolean_expression) && do.something();

Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan

Understanding REST: Verbs, error codes, and authentication

Simply put, you are doing this completely backward.

You should not be approaching this from what URLs you should be using. The URLs will effectively come "for free" once you've decided upon what resources are necessary for your system AND how you will represent those resources, and the interactions between the resources and application state.

To quote Roy Fielding

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

Folks always start with the URIs and think this is the solution, and then they tend to miss a key concept in REST architecture, notably, as quoted above, "Failure here implies that out-of-band information is driving interaction instead of hypertext."

To be honest, many see a bunch of URIs and some GETs and PUTs and POSTs and think REST is easy. REST is not easy. RPC over HTTP is easy, moving blobs of data back and forth proxied through HTTP payloads is easy. REST, however, goes beyond that. REST is protocol agnostic. HTTP is just very popular and apt for REST systems.

REST lives in the media types, their definitions, and how the application drives the actions available to those resources via hypertext (links, effectively).

There are different view about media types in REST systems. Some favor application specific payloads, while others like uplifting existing media types in to roles that are appropriate for the application. For example, on the one hand you have specific XML schemas designed suited to your application versus using something like XHTML as your representation, perhaps through microformats and other mechanisms.

Both approaches have their place, I think, the XHTML working very well in scenarios that overlap both the human driven and machine driven web, whereas the former, more specific data types I feel better facilitate machine to machine interactions. I find the uplifting of commodity formats can make content negotiation potentially difficult. "application/xml+yourresource" is much more specific as a media type than "application/xhtml+xml", as the latter can apply to many payloads which may or may not be something a machine client is actually interested in, nor can it determine without introspection.

However, XHTML works very well (obviously) in the human web where web browsers and rendering is very important.

You application will guide you in those kinds of decisions.

Part of the process of designing a REST system is discovering the first class resources in your system, along with the derivative, support resources necessary to support the operations on the primary resources. Once the resources are discovered, then the representation of those resources, as well as the state diagrams showing resource flow via hypertext within the representations because the next challenge.

Recall that each representation of a resource, in a hypertext system, combines both the actual resource representation along with the state transitions available to the resource. Consider each resource a node in a graph, with the links being the lines leaving that node to other states. These links inform clients not only what can be done, but what is required for them to be done (as a good link combines the URI and the media type required).

For example, you may have:

<link href="http://example.com/users" rel="users" type="application/xml+usercollection"/>
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>

Your documentation will talk about the rel field named "users", and the media type of "application/xml+youruser".

These links may seem redundant, they're all talking to the same URI, pretty much. But they're not.

This is because for the "users" relation, that link is talking about the collection of users, and you can use the uniform interface to work with the collection (GET to retrieve all of them, DELETE to delete all of them, etc.)

If you POST to this URL, you will need to pass a "application/xml+usercollection" document, which will probably only contain a single user instance within the document so you can add the user, or not, perhaps, to add several at once. Perhaps your documentation will suggest that you can simply pass a single user type, instead of the collection.

You can see what the application requires in order to perform a search, as defined by the "search" link and it's mediatype. The documentation for the search media type will tell you how this behaves, and what to expect as results.

The takeaway here, though, is the URIs themselves are basically unimportant. The application is in control of the URIs, not the clients. Beyond a few 'entry points', your clients should rely on the URIs provided by the application for its work.

The client needs to know how to manipulate and interpret the media types, but doesn't much need to care where it goes.

These two links are semantically identical in a clients eyes:

<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
<link href="http://example.com/AW163FH87SGV" rel="search" type="application/xml+usersearchcriteria"/>

So, focus on your resources. Focus on their state transitions in the application and how that's best achieved.

Selecting text in an element (akin to highlighting with your mouse)

lepe - That works great for me thanks! I put your code in a plugin file, then used it in conjunction with an each statement so you can have multiple pre tags and multiple "Select all" links on one page and it picks out the correct pre to highlight:

<script type="text/javascript" src="../js/jquery.selecttext.js"></script>
<script type="text/javascript">
  $(document).ready(function() { 
        $(".selectText").each(function(indx) {
                $(this).click(function() {                 
                    $('pre').eq(indx).selText().addClass("selected");
                        return false;               
                    });
        });
  });

What is a typedef enum in Objective-C?

The enum (abbreviation of enumeration) is used to enumerate a set of values (enumerators). A value is an abstract thing represented by a symbol (a word). For example, a basic enum could be

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl };

This enum is called anonymous because you do not have a symbol to name it. But it is still perfectly correct. Just use it like this

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;

Ok. The life is beautiful and everything goes well. But one day you need to reuse this enum to define a new variable to store myGrandFatherPantSize, then you write:

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandFatherPantSize;

But then you have a compiler error "redefinition of enumerator". Actually, the problem is that the compiler is not sure that you first enum and you are second describe the same thing.

Then if you want to reuse the same set of enumerators (here xs...xxxxl) in several places you must tag it with a unique name. The second time you use this set you just have to use the tag. But don't forget that this tag does not replace the enum word but just the set of enumerators. Then take care to use enum as usual. Like this:

// Here the first use of my enum
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize; 
// here the second use of my enum. It works now!
enum sizes myGrandFatherPantSize;

you can use it in a parameter definition as well:

// Observe that here, I still use the enum
- (void) buyANewDressToMyGrandMother:(enum sizes)theSize;

You could say that rewriting enum everywhere is not convenient and makes the code looks a bit strange. You are right. A real type would be better.

This is the final step of our great progression to the summit. By just adding a typedef let's transform our enum in a real type. Oh the last thing, typedef is not allowed within your class. Then define your type just above. Do it like this:

// enum definition
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl };
typedef enum sizes size_type

@interface myClass {
   ...
   size_type myGrandMotherDressSize, myGrandFatherPantSize;
   ...
}

Remember that the tag is optional. Then since here, in that case, we do not tag the enumerators but just to define a new type. Then we don't really need it anymore.

// enum definition
typedef enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } size_type;

@interface myClass : NSObject {
  ...
  size_type myGrandMotherDressSize, myGrandFatherPantSize;
  ...
}
@end

If you are developing in Objective-C with XCode I let you discover some nice macros prefixed with NS_ENUM. That should help you to define good enums easily and moreover will help the static analyzer to do some interesting checks for you before to compile.

Good Enum!

How do you make sure email you send programmatically is not automatically marked as spam?

I would add :

Provide real unsubscription upon click on "Unsubscribe". I've seen real newsletters providing a dummy unsubscription link that upon click shows " has been unsubscribed successfully" but I will still receive further newsletters.

Java: Calling a super method which calls an overridden method

"this" keyword refers to current class reference. That means, when it is used inside the method, the 'current' class is still SubClass and so, the answer is explained.

Capture screenshot of active window?

A little tweak to method static void ImageSave() will grant you the option where to save it. Credit goes to Microsoft (http://msdn.microsoft.com/en-us/library/sfezx97z.aspx)

static void ImageSave(string filename, ImageFormat format, Image image, SaveFileDialog saveFileDialog1)
    { 
        saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
        saveFileDialog1.Title = "Enregistrer un image";
        saveFileDialog1.ShowDialog();

        // If the file name is not an empty string open it for saving.
        if (saveFileDialog1.FileName != "")
        {
            // Saves the Image via a FileStream created by the OpenFile method.
            System.IO.FileStream fs =
               (System.IO.FileStream)saveFileDialog1.OpenFile();
            // Saves the Image in the appropriate ImageFormat based upon the
            // File type selected in the dialog box.
            // NOTE that the FilterIndex property is one-based.
            switch (saveFileDialog1.FilterIndex)
            {
                case 1:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;

                case 2:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Bmp);
                    break;

                case 3:
                    image.Save(fs,
                       System.Drawing.Imaging.ImageFormat.Gif);
                    break;
            }

            fs.Close();
        }



    }

Your button_click event should be coded something like this...

private void btnScreenShot_Click(object sender, EventArgs e)
    {

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();


        ScreenCapturer.CaptureAndSave(filename, mode, format, saveFileDialog1);

    }//

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

On Windows use:

C:\PostgreSQL\pg10\bin>createuser -U postgres --pwprompt <USER>

Add --superuser or --createdb as appropriate.

See https://www.postgresql.org/docs/current/static/app-createuser.html for further options.

Removing address bar from browser (to view on Android)

I found that if you add the command to unload, he keeps down the page, ie the page that move! Hope it works with you too!

window.addEventListener("load", function() { window.scrollTo(0, 1); });
window.addEventListener("unload", function() { window.scrollTo(0, 1); });

Using a 7-inch tablet with android, www.kupsoft.com visit my website and check how it behaves page, I use this command in my portal.

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

CodeIgniter: How to use WHERE clause and OR clause

Active record method or_where is to be used:

$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);

Is it possible to add an HTML link in the body of a MAILTO link

Add the full link, with:

 "http://"

to the beginning of a line, and most decent email clients will auto-link it either before sending, or at the other end when receiving.

For really long urls that will likely wrap due to all the parameters, wrap the link in a less than/greater than symbol. This tells the email client not to wrap the url.

e.g.

  <http://www.example.com/foo.php?this=a&really=long&url=with&lots=and&lots=and&lots=of&prameters=on_it>

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Happened to me when switching flavors.

Now you can also use the google-services.json with different flavors.

See https://stackoverflow.com/a/34364376/570168

malloc an array of struct pointers

I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.

The code uses the ms visual studio leak detector so you can experiment with the potential leaks.

#include "stdafx.h"

#include <string.h>
#include "msc-lzw.h"

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h> 



// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
    return (key + try_num) % max;  // the hash fun returns a number bounded by the number of slots.
}


// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
    int key; // use this field as the key
    char *pValue;  // use this field to store a variable length string
};


struct hash_table {
    int max;
    int number_of_elements;
    struct key_value_pair **elements;  // This is an array of pointers to mystruct objects
};


int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {

    int try_num, hash;
    int max_number_of_retries = hash_table->max;


    if (hash_table->number_of_elements >= hash_table->max) {
        return 0; // FULL
    }

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(data->key, try_num, hash_table->max);

        if (NULL == hash_table->elements[hash]) { // an unallocated slot
            hash_table->elements[hash] = data;
            hash_table->number_of_elements++;
            return RC_OK;
        }
    }
    return RC_ERROR;
}


// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {

    unsigned int try_num, hash;
    unsigned int max_number_of_retries = hash_table->max;

    for (try_num = 0; try_num < max_number_of_retries; try_num++) {

        hash = hash_fun(key, try_num, hash_table->max);

        if (hash_table->elements[hash] == 0) {
            return NULL; // Nothing found
        }

        if (hash_table->elements[hash]->key == key) {
            return hash_table->elements[hash];
        }
    }
    return NULL;
}


// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter.  It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {

    int num_keys = 0;

    *ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );

    for (int i = 0; i < pHashTable->max; i++) {
        if (NULL != pHashTable->elements[i]) {
            (*ppKeys)[num_keys] = pHashTable->elements[i]->key;
            num_keys++;
        }
    }
    return num_keys;
}

// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {


    // Allocate the hash table slots
    pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair));  // allocate max number of key_value_pair entries
    for (int i = 0; i < pHashTable->max; i++) {
        pHashTable->elements[i] = NULL;
    }



    // alloc all the slots
    //struct key_value_pair *pa_slot;
    //for (int i = 0; i < pHashTable->max; i++) {
    //  // all that he could see was babylon
    //  pa_slot = (struct key_value_pair *)  malloc(sizeof(struct key_value_pair));
    //  if (NULL == pa_slot) {
    //      printf("alloc of slot failed\n");
    //      while (1);
    //  }
    //  pHashTable->elements[i] = pa_slot;
    //  pHashTable->elements[i]->key = 0;
    //}

    return RC_OK;
}


// This will make a dictionary entry where
//   o  key is an int
//   o  value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {

    // determine the len of the buffer assuming it is a string
    int len = strlen(buffer);

    // alloc the buffer to hold the string
    pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
    if (NULL == pMyStruct->pValue) {
        printf("Failed to allocate the buffer for the dictionary string value.");
        return RC_ERROR;
    }
    strcpy(pMyStruct->pValue, buffer);
    pMyStruct->key = a_key;

    return RC_OK;
}


// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {

    int rc;
    struct key_value_pair *pKeyValuePair;

    if (NULL == pHashTable) {
        printf("Hash table is null.\n");
        return RC_ERROR;
    }

    // Allocate the dictionary key value pair struct
    pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
    if (NULL == pKeyValuePair) {
        printf("Failed to allocate key value pair struct.\n");
        return RC_ERROR;
    }


    rc = make_dict_entry(key, pBuff, pKeyValuePair);  // a_hash_table[1221] = "abba"
    if (RC_ERROR == rc) {
        printf("Failed to add buff to key value pair struct.\n");
        return RC_ERROR;
    }


    rc = hash_insert(pKeyValuePair, pHashTable);
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }

    return RC_OK;
}


void dump_hash_table(struct hash_table *pHashTable) {

    // Iterate the dictionary by keys
    char * pValue;
    struct key_value_pair *pMyStruct;
    int *pKeyList;
    int num_keys;

    printf("i\tKey\tValue\n");
    printf("-----------------------------\n");
    num_keys = keys(pHashTable, &pKeyList);
    for (int i = 0; i < num_keys; i++) {
        pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
        pValue = pMyStruct->pValue;
        printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
    }

    // Free the key list
    free(pKeyList);

}

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

    int rc;
    int i;


    struct hash_table a_hash_table;
    a_hash_table.max = 20;   // The dictionary can hold at most 20 entries.
    a_hash_table.number_of_elements = 0;  // The intial dictionary has 0 entries.
    allocate_the_dictionary(&a_hash_table);

    rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }
    rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
    if (RC_ERROR == rc) {
        printf("insert has failed!\n");
        return RC_ERROR;
    }



    // Iterate the dictionary by keys
    dump_hash_table(&a_hash_table);

    // Free the individual slots
    for (i = 0; i < a_hash_table.max; i++) {
        // all that he could see was babylon
        if (NULL != a_hash_table.elements[i]) {
            free(a_hash_table.elements[i]->pValue);  // free the buffer in the struct
            free(a_hash_table.elements[i]);  // free the key_value_pair entry
            a_hash_table.elements[i] = NULL;
        }
    }


    // Free the overall dictionary
    free(a_hash_table.elements);


    _CrtDumpMemoryLeaks();
    return 0;
}

How to create an empty array in Swift?

Here you go:

var yourArray = [String]()

The above also works for other types and not just strings. It's just an example.

Adding Values to It

I presume you'll eventually want to add a value to it!

yourArray.append("String Value")

Or

let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)

Add by Inserting

Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):

yourArray.insert("Hey, I'm first!", atIndex: 0)

Or you can use variables to make your insert more flexible:

let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)

You May Eventually Want to Remove Some Stuff

var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)

The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.

Removing Values Without Knowing the Index

But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?

if let indexValue = yourOtherArray.index(of: "RemoveMe") {
    yourOtherArray.remove(at: indexValue)
}

This should get you started!

How to read line by line of a text area HTML tag

This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.

var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
    if (parseInt($(this) != 'NaN')
        lines[] = parseInt($(this));
}

How can I set Image source with base64

img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

I have the same problem with spring 3.0.2 and spring-beans-3.0.xsd.

My solution:

Create a file META-INF/spring.schemas in the source folder and copy all necesary definitions. Create spring.handlers too.

I think that the class PluggableSchemaResolver is not working correctly.

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/xml/PluggableSchemaResolver.html

from the javadoc:

"By default, this class will look for mapping files in the classpath using the pattern: META-INF/spring.schemas allowing for multiple files to exist on the classpath at any one time."

but in my case, this class only read the first spring.schemas finded.

Grettings. pacovr

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Couldn't you just do this?

var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });

...and mark your action with

[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}

How to iterate object in JavaScript?

There's this way too (new to EcmaScript5):

dictionary.data.forEach(function(item){
    console.log(item.name + ' ' + item.id);
});

Same approach for images

Better/Faster to Loop through set or list?

For simplicity's sake: newList = list(set(oldList))

But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark

SVN Error - Not a working copy

svn: The repository at 'svn://repourl/reponame/foldername' has uuid 'm/reponame', but the WC has 'b5b39681-0ff6-784b-ad26-2846b9ea8e7d'

Every subversion repo has a unique identifier (uuid). Subversion uses this to make sure that the repo is actually the same when doing things like switching. You should probably change the uuid on the server to be the same as before.

SQL query, store result of SELECT in local variable

Isn't this a much simpler solution, if I correctly understand the question, of course.

I want to load email addresses that are in a table called "spam" into a variable.

select email from spam

produces the following list, say:

.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu

To load into the variable @list:

declare @list as varchar(8000)
set @list += @list (select email from spam)

@list may now be INSERTed into a table, etc.

I hope this helps.

To use it for a .csv file or in VB, spike the code:

declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list

and it produces ready-made code to use elsewhere:

".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"

One can be very creative.

Thanks

Nico

How to count number of records per day?

If your timestamp includes time, not only date, use:

SELECT DATE_FORMAT('timestamp', '%Y-%m-%d') AS date, COUNT(id) AS count FROM table GROUP BY DATE_FORMAT('timestamp', '%Y-%m-%d')

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

rand() returns the same number each time the program is run

You need to "seed" the generator. Check out this short video, it will clear things up.

https://www.thenewboston.com/videos.php?cat=16&video=17503

How do I store data in local storage using Angularjs?

Follow the steps to store data in Angular - local storage:

  1. Add 'ngStorage.js' in your folder.
  2. Inject 'ngStorage' in your angular.module

        eg: angular.module("app", [ 'ngStorage']);
    
  3. Add $localStorage in your app.controller function

4.You can use $localStorage inside your controller

Eg: $localstorage.login= true;

The above will store the localstorage in your browser application

Switch case on type c#

The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()).

public static void TestTypeSwitch()
{
    var ts = new TypeSwitch()
        .Case((int x) => Console.WriteLine("int"))
        .Case((bool x) => Console.WriteLine("bool"))
        .Case((string x) => Console.WriteLine("string"));

    ts.Switch(42);     
    ts.Switch(false);  
    ts.Switch("hello"); 
}

Here is the machinery required to make it work.

public class TypeSwitch
{
    Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
    public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; } 
    public void Switch(object x) { matches[x.GetType()](x); }
}

How do I add all new files to SVN

The solution

svn status | grep ^? | sed 's/?    //' | xargs svn add

does not work with whitespaces. Instead one can use

svn status | grep ^? | sed 's/^?       //' | xargs -I fn svn add "fn"

(seems like the number of leading blanks is different on my system -- just adjust it).

Differences between strong and weak in Objective-C

strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable

weak: will assign the incoming value to it without retaining it.

So the basic difference is the retaining of the new variable. Generaly you want to retain it but there are situations where you don't want to have it otherwise you will get a retain cycle and can not free the memory the objects. Eg. obj1 retains obj2 and obj2 retains obj1. To solve this kind of situation you use weak references.

Android: No Activity found to handle Intent error? How it will resolve

if (intent.resolveActivity(getPackageManager()) == null) {
    Utils.showToast(activity, no_app_available_to_complete_this_task);
} else {
    startActivityForResult(intent, 1);
}

Center image using text-align center?

You can do:

<center><img src="..." /></center>

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I would go with the solution provided by kcrumley Just modify it slightly to handle NULLs

create function dbo.HigherArgumentOrNull(@val1 int, @val2 int)
returns int
as
begin
  if @val1 >= @val2
    return @val1
  if @val1 < @val2
    return @val2

 return NULL
end

EDIT Modified after comment from Mark. As he correctly pointed out in 3 valued logic x > NULL or x < NULL should always return NULL. In other words unknown result.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

From Oracle 11gR2, the LISTAGG clause should do the trick:

SELECT question_id,
       LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;

Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

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

enter image description here

  1. click on three dots in the top right ->
  2. click on "Undock into separate window" icon

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.


To address the questions/concerns in the comments:

The enum's "builtin" (implicitly declared) valueOf(String name) method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:

  1. Forget about the naming conventions for a bit and just name your constants as it makes most sense: enum PropName { contents, columnHeadings, ...}. This is obviously the most convenient.
  2. Convert your camelCase input into UPPER_SNAKE_CASE before calling valueOf, if you're really fond of naming conventions.
  3. Implement your own lookup method instead of the builtin valueOf to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.

Is there a way to create interfaces in ES6 / Node 4?

Interfaces are not part of the ES6 but classes are.

If you really need them, you should look at TypeScript which support them.

Using an IF Statement in a MySQL SELECT query

try this code worked for me

SELECT user_display_image AS user_image,
       user_display_name AS user_name,
       invitee_phone,
       (CASE WHEN invitee_status = 1 THEN "attending"
             WHEN invitee_status = 2 THEN "unsure"
             WHEN invitee_status = 3 THEN "declined"
             WHEN invitee_status = 0 THEN "notreviwed"
       END) AS invitee_status
  FROM your_table

How to use java.net.URLConnection to fire and handle HTTP requests?

Update

The new HTTP Client shipped with Java 9 but as part of an Incubator module named jdk.incubator.httpclient. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.

In Java 9, you can send a GET request like:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

Then you can examine the returned HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

Since this new HTTP Client is in java.httpclient jdk.incubator.httpclient module, you should declare this dependency in your module-info.java file:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

How to make custom error pages work in ASP.NET MVC 4

In web.config add this under system.webserver tag as below,

<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <remove statusCode="500"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
  <error statusCode="500" responseMode="ExecuteURL"path="/Error/ErrorPage"/>
</httpErrors>

and add a controller as,

public class ErrorController : Controller
{
    //
    // GET: /Error/
    [GET("/Error/NotFound")]
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;

        return View();
    }

    [GET("/Error/ErrorPage")]
    public ActionResult ErrorPage()
    {
        Response.StatusCode = 500;

        return View();
    }
}

and add their respected views, this will work definitely I guess for all.

This solution I found it from: Neptune Century

How can you use optional parameters in C#?

The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.

Convert bytes to bits in python

What about something like this?

>>> bin(int('ff', base=16))
'0b11111111'

This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.

As pointed out by a comment, if you need to get rid of the 0b prefix, you can do it this way:

>>> bin(int('ff', base=16)).lstrip('0b')
'11111111'

or this way:

>>> bin(int('ff', base=16))[2:]
'11111111'

No input file specified

Citing http://support.statamic.com/kb/hosting-servers/running-on-godaddy :

If you want to use GoDaddy as a host and you find yourself getting "No input file specified" errors in the control panel, you'll need to create a php5.ini file in your weboot with the following rule:

cgi.fix_pathinfo = 1

best easy answer just one line change and you are all set.

recommended for godaddy hosting.

How to read and write INI file with Python3?

ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:

  • Nested sections (subsections), to any level
  • List values
  • Multiple line values
  • String interpolation (substitution)
  • Integrated with a powerful validation system including automatic type checking/conversion repeated sections and allowing default values
  • When writing out config files, ConfigObj preserves all comments and the order of members and sections
  • Many useful methods and options for working with configuration files (like the 'reload' method)
  • Full Unicode support

It has some draw backs:

  • You cannot set the delimiter, it has to be =… (pull request)
  • You cannot have empty values, well you can but they look liked: fuabr = instead of just fubar which looks weird and wrong.

What is the difference between atan and atan2 in C++?

Mehrwolf below is correct, but here is a heuristic which may help:

If you are working in a 2-dimensional coordinate system, which is often the case for programming the inverse tangent, you should use definitely use atan2. It will give the full 2 pi range of angles and take care of zeros in the x coordinate for you.

Another way of saying this is that atan(y/x) is virtually always wrong. Only use atan if the argument cannot be thought of as y/x.

Changing the git user inside Visual Studio Code

Press Ctrl + Shift + G in Visual Studio Code and go to more and select Show git output. Click Terminal and type git remote -v and verify that the origin branch has latest username in it like:

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (fetch)

origin [email protected]:DroidPulkit/Facebook-Chat-Bot.git (push)

Here DroidPulkit is my username.

If the username is not what you wanted it to be then change it with:

git add remote origin [email protected]:newUserName/RepoName.git

'sudo gem install' or 'gem install' and gem locations

You can also install gems in your local environment (without sudo) with

gem install --user-install <gemname>

I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.

You can check where the gems go by looking at gempaths with gem environment. In my case it's "~/.gem/ruby/1.8".

If you need some binaries from local installs added to your path, you can add something to your bashrc like:

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

(from http://guides.rubygems.org/faqs/#user-install)

How do I decompile a .NET EXE into readable C# source code?

When Red Gate said there would no longer be a free version of .Net Reflector, I started using ILSpy and Telerik's JustDecompile. I have found ILSpy to decompile more accurately than JustDecompile (which is still in Beta). Red Gate has changed their decision and still have a free version of .Net Reflector, but now I like ILSpy.

From the ILSpy website (https://github.com/icsharpcode/ILSpy/):

ILSpy is the open-source .NET assembly browser and decompiler.

ILSpy Features

  • Assembly browsing
  • IL Disassembly
  • Decompilation to C#
  • Supports lambdas and 'yield return'
  • Shows XML documentation
  • Saving of resources
  • Search for types/methods/properties (substring)
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation history
  • BAML to XAML decompiler
  • Save Assembly as C# Project
  • Find usage of field/method
  • Extensible via plugins (MEF)

Update:

April 15, 2012, ILSpy 2.0 was released. New features compared with version 1.0:

  • Assembly Lists
  • Support for decompiling Expression trees
  • Support for lifted operatores on nullables
  • Decompile to Visual Basic
  • Search for multiple strings separated by space (searching for "Assembly manager" in ILSpy.exe would find AssemblyListManager)
  • Clicking on a local variable will highlight all other occurrences of that variable
  • Ctrl+F can be used to search within the decompiled code view

Update:

  • ILSpy 2.1 supports async/await decompilation

How to trigger SIGUSR1 and SIGUSR2?

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

#include <signal.h>

kill(pid, SIGUSR1);

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

#include <signal.h>

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

signal(SIGUSR1, my_handler);

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

Loading .sql files from within PHP

Just to restate the problem for everyone:

PHP's mysql_query, automatically end-delimits each SQL commands, and additionally is very vague about doing so in its manual. Everything beyond one command will yield an error.

On the other mysql_query is fine with a string containing SQL-style comments, \n, \r..

The limitation of mysql_query reveals itself in that the SQL parser reports the problem to be directly at the next command e.g.

 You have an error in your SQL syntax; check the manual that corresponds to your
 MySQL server version for the right syntax to use near 'INSERT INTO `outputdb:`
 (`intid`, `entry_id`, `definition`) VALUES...

Here is a quick solution: (assuming well formatted SQL;

$sqlCmds = preg_split("/[\n|\t]*;[\n|\t]*[\n|\r]$/", $sqlDump);

How do I parse a string with a decimal point to a double?

I couldn't write a comment, so I write here:

double.Parse("3.5", CultureInfo.InvariantCulture) is not a good idea, because in Canada we write 3,5 instead of 3.5 and this function gives us 35 as a result.

I tested both on my computer:

double.Parse("3.5", CultureInfo.InvariantCulture) --> 3.5 OK
double.Parse("3,5", CultureInfo.InvariantCulture) --> 35 not OK

This is a correct way that Pierre-Alain Vigeant mentioned

public static double GetDouble(string value, double defaultValue)
{
    double result;

    // Try parsing in the current culture
    if (!double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
        // Then try in US english
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
        // Then in neutral language
        !double.TryParse(value, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out result))
    {
        result = defaultValue;
    }
    return result;
}

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

jquery clear input default value

Unless you're really worried about older browsers, you could just use the new html5 placeholder attribute like so:

<input type="text" name="email" placeholder="Email address" class="input" />

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

openssl s_client using a proxy

since openssl v1.1.0

C:\openssl>openssl version
OpenSSL 1.1.0g  2 Nov 2017
C:\openssl>openssl s_client -proxy 192.168.103.115:3128 -connect www.google.com -CAfile C:\TEMP\internalCA.crt
CONNECTED(00000088)
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = www.google.com
verify return:1
---
Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
   i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
 1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
   i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkTCCAnmgAwIBAgIJAIv4/hQAAAAAMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
BAYTAkZSMQ4wDAYDVQQHEwVDUk9JWDETMBEGA1UEAxMKc3Zwcm94eXNnMTEeMBwG

How can I programmatically determine if my app is running in the iphone simulator?

With Swift 4.2 (Xcode 10), we can do this

#if targetEnvironment(simulator)
  //simulator code
#else 
  #warning("Not compiling for simulator")
#endif

How to send parameters from a notification-click to an activity?

I tried everything but nothing worked.

eventually came up with following solution.

1- in manifest add for the activity android:launchMode="singleTop"

2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()

                    Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);

                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
                    bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
                    bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());

                    notificationIntent.putExtras(bundle);

                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                            Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
                            new Random().nextInt(), notificationIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT); 

How do I determine file encoding in OS X?

Which LaTeX are you using? When I was using teTeX, I had to manually download the unicode package and add this to my .tex files:

% UTF-8 stuff
\usepackage[notipa]{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

Now, I've switched over to XeTeX from the TeXlive 2008 package (here), it is even more simple:

% UTF-8 stuff
\usepackage{fontspec}
\usepackage{xunicode}

As for detection of a file's encoding, you could play with file(1) (but it is rather limited) but like someone else said, it is difficult.

Javascript : array.length returns undefined

It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.

As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:

json_encode($something) 

with something like:

json_encode(array_values($something))

But don't ignore the other answers here about Object.keys. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.

How to insert a SQLite record with a datetime set to 'now' in Android application?

There are a couple options you can use:

  1. You could try using the string "(DATETIME('now'))" instead.
  2. Insert the datetime yourself, ie with System.currentTimeMillis()
  3. When creating the SQLite table, specify a default value for the created_date column as the current date time.
  4. Use SQLiteDatabase.execSQL to insert directly.

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

SelectedValue vs SelectedItem.Value of DropDownList

In droupDown list there are two item add property.

1) Text 2) value

If you want to get text property then u use selecteditem.text

and If you want to select value property then use selectedvalue property

In your case i thing both value and text property are the same so no matter if u use selectedvalue or selecteditem.text

If both are different then they give us different results

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How to get autocomplete in jupyter notebook without using tab?

Without doing this %config IPCompleter.greedy=True after you import a package like numpy or pandas in this way; import numpy as np import pandas as pd.

Then you type in pd. then tap the tab button it brings out all the possible methods to use very easy and straight forward.

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

Dynamic creation of table with DOM

You can create a dynamic table rows as below:

var tbl = document.createElement('table');
tbl.style.width = '100%';

for (var i = 0; i < files.length; i++) {

        tr = document.createElement('tr');

        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');

        ::::: // As many <td> you want

        td1.appendChild(document.createTextNode());
        td2.appendChild(document.createTextNode());
        td3.appendChild(document.createTextNode();

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbl.appendChild(tr);
}

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

How to skip the first n rows in sql query

try below query it's work

SELECT * FROM `my_table` WHERE id != (SELECT id From my_table LIMIT 1)

Hope this will help

Options for HTML scraping?

Regular expressions work pretty well for HTML scraping as well ;-) Though after looking at Beautiful Soup, I can see why this would be a valuable tool.

How can I force WebKit to redraw/repaint to propagate style changes?

I found that just adding a content style to the element forced it to repaint, this should be a different value every time you want it to redraw and doesn't need to be on a pseudo element.

.selector {
    content: '1'
}

What is the difference between HTML tags and elements?

http://html.net/tutorials/html/lesson3.php

Tags are labels you use to mark up the begining and end of an element.

All tags have the same format: they begin with a less-than sign "<" and end with a greater-than sign ">".

Generally speaking, there are two kinds of tags - opening tags: <html> and closing tags: </html>. The only difference between an opening tag and a closing tag is the forward slash "/". You label content by putting it between an opening tag and a closing tag.

HTML is all about elements. To learn HTML is to learn and use different tags.

For example:

<h1></h1>

Where as elements are something that consists of start tag and end tag as shown:

<h1>Heading</h1>

After installation of Gulp: “no command 'gulp' found”

Tried with sudo and it worked !!

sudo npm install --global gulp-cli

How do I output lists as a table in Jupyter notebook?

tabletext fit this well

import tabletext

data = [[1,2,30],
        [4,23125,6],
        [7,8,999],
        ]

print tabletext.to_text(data)

result:

+-----------------+
¦ 1 ¦     2 ¦  30 ¦
+---+-------+-----¦
¦ 4 ¦ 23125 ¦   6 ¦
+---+-------+-----¦
¦ 7 ¦     8 ¦ 999 ¦
+-----------------+

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

How do I divide so I get a decimal value?

You can do like,

int a = 3;
int b = 2;
int quotient = a / b;
int remainder = a % b;

To get quotient in real numbers

System.out.println((double) a / b);

To get quotient in integer numbers

System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);

To get quotient in real number such that one number after decimal

System.out.println(a / b + "." + a % b * 10 / b);

Note: In the last method it will not round the number up after the decimal.

jquery - fastest way to remove all rows from a very large table

if you want to remove only fast.. you can do like below..

$( "#tableId tbody tr" ).each( function(){
  this.parentNode.removeChild( this ); 
});

but, there can be some event-binded elements in table,

in that case,

above code is not prevent memory leak in IE... T-T and not fast in FF...

sorry....

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

Check if list is empty in C#

var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

Ambiguous overload call to abs(double)

Use fabs() instead of abs(), it's the same but for floats instead of integers.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

For those using a fresh install of Ubuntu, or another Linux distro, make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.

At Terminal, type:

sudo apt-get install build-essential

It should be enough to compile and run your apps.

Of course, you can also perform full g++ install, using:

sudo apt-get install g++

How can I see if a Perl hash already has a certain key?

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

Activity has leaked window that was originally added

Not only try to show an alert but it can also be invoked when you finish a particular instance of activity and try to start new activity/service or try to stop it.

Example:

OldActivity instance;

    oncreate() {
       instance=this;
    }
    instance.finish();
    instance.startActivity(new Intent(ACTION_MAIN).setClass(instance, NewActivity.class));

Echo off but messages are displayed

"echo off" is not ignored. "echo off" means that you do not want the commands echoed, it does not say anything about the errors produced by the commands.

The lines you showed us look okay, so the problem is probably not there. So, please show us more lines. Also, please show us the exact value of INSTALL_PATH.

Format a datetime into a string with milliseconds

With Python 3.6 you can use:

from datetime import datetime
datetime.utcnow().isoformat(sep=' ', timespec='milliseconds')

Output:

'2019-05-10 09:08:53.155'

More info here: https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat

How to access session variables from any class in ASP.NET?

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA

Git - Ignore node_modules folder everywhere

it will automatically create a .gitignore file if not then create a file name .gitignore and add copy & paste the below code

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

these below are all unnecessary files

See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

and save the .gitignore file and you can upload

Parse RSS with jQuery

jFeed is easy and has an example for you to test. But if you're parsing a feed from another server, you'll need to allow Cross Origin Resource Sharing (CORS) on the feed's server. You'll also need to check browser support.

I uploaded the sample but still did not get support from IE in any version when I changed the url in the example to something like example.com/feed.rss via the http protocol. CORS should be supported for IE 8 and above but the jFeed example did not render the feed.

Your best bet is to use Google's API:
https://developers.google.com/feed/v1/devguide

See:
https://github.com/jfhovinne/jFeed
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
http://en.wikipedia.org/wiki/Same_origin_policy
http://caniuse.com/cors

MySQL Database won't start in XAMPP Manager-osx

You seem to have found a work-around by killing the process, but make sure you check for free space on your MySQL partition. If your logs or db files are consuming all your drive space, mysqld will not start.

Does C have a string type?

C does not support a first class string type.

C++ has std::string

java.text.ParseException: Unparseable date

Your pattern does not correspond to the input string at all... It is not surprising that it does not work. This would probably work better:

SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
                                            Locale.ENGLISH);

Then to print with your required format you need a second SimpleDateFormat:

Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));

Notes:

  • you should include the locale as if your locale is not English, the day name might not be recognised
  • IST is ambiguous and can lead to problems so you should use the proper time zone name if possible in your input.

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

printf %f with only 2 numbers after the decimal point?

You can try printf("%.2f", [double]);

Tomcat 7: How to set initial heap size correctly?

Take care with change in Debian distributions! I tried to change CATALINA_OPTS in my Debian 7 and the results where that tomcat didn't start anymore. Thus I solved this issue by changing the property JAVA_OPTS in place of CATALINA_OPTS, like this

export JAVA_OPTS="-Xms512M -Xmx1024M"

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

How do I select an element with its name attribute in jQuery?

You could always do $('input[name="somename"]')

how to get the last part of a string before a certain character?

Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.

x = 'http://test.com/lalala-134-431'

a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"

and partition will divide the string with only first delimiter and will only return 3 values in list

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"

so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"

Express-js can't GET my static files, why?

default.css should be available at http://localhost:3001/default.css

The styles in app.use(express.static(__dirname + '/styles')); just tells express to look in the styles directory for a static file to serve. It doesn't (confusingly) then form part of the path it is available on.

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try the following commands in terminal, this will work better:

apt-get install curl

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

How do I look inside a Python object?

I'm surprised no one's mentioned help yet!

In [1]: def foo():
   ...:     "foo!"
   ...:

In [2]: help(foo)
Help on function foo in module __main__:

foo()
    foo!

Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.

Retrofit 2.0 how to get deserialised error response.body

val error = JSONObject(callApi.errorBody()?.string() as String)
            CustomResult.OnError(CustomNotFoundError(userMessage = error["userMessage"] as String))

open class CustomError (
    val traceId: String? = null,
    val errorCode: String? = null,
    val systemMessage: String? = null,
    val userMessage: String? = null,
    val cause: Throwable? = null
)

open class ErrorThrowable(
    private val traceId: String? = null,
    private val errorCode: String? = null,
    private val systemMessage: String? = null,
    private val userMessage: String? = null,
    override val cause: Throwable? = null
) : Throwable(userMessage, cause) {
    fun toError(): CustomError = CustomError(traceId, errorCode, systemMessage, userMessage, cause)
}


class NetworkError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Usted no tiene conexión a internet, active los datos", cause)

class HttpError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage, cause)

class UnknownError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Unknown error", cause)

class CustomNotFoundError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Data not found", cause)`

How to efficiently remove duplicates from an array without using Set

For a sorted Array, just check the next index:

//sorted data!
public static int[] distinct(int[] arr) {
    int[] temp = new int[arr.length];

    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        int current = arr[i];

        if(count > 0 )
            if(temp[count - 1] == current)
                continue;

        temp[count] = current;
        count++;
    }

    int[] whitelist = new int[count];
    System.arraycopy(temp, 0, whitelist, 0, count);

    return whitelist;
}

Copy multiple files in Python

You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.

The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).

import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
    full_file_name = os.path.join(src, file_name)
    if os.path.isfile(full_file_name):
        shutil.copy(full_file_name, dest)

send checkbox value in PHP form

Here's how it should look like in order to return a simple Yes when it's checked.

<input type="checkbox" id="newsletter" name="newsletter" value="Yes" checked>
<label for="newsletter">i want to sign up for newsletter</label>

I also added the text as a label, it means you can click the text as well to check the box. Small but, personally I hate when sites make me aim my mouse at this tiny little check box.

When the form is submitted if the check box is checked $_POST['newsletter'] will equal Yes. Just how you are checking to see if $_POST['name'],$_POST['email'], and $_POST['tel'] are empty you could do the same.

Here is an example of how you would add this into your email on the php side:

Underneath your existing code:

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];

Add:

$newsletter = $_POST['newsletter'];
if ($newsletter != 'Yes') {
    $newsletter = 'No';
}

If the check box is checked it will add Yes in your email if it was not checked it will add No.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

How to resolve "gpg: command not found" error during RVM installation?

On Mac OSX 10.15, Even after installing gpg, i was getting gpg2 command not found

$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`

$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found

Instead, this worked for me

$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Calculate the center point of multiple latitude/longitude coordinate pairs

If you wish to take into account the ellipsoid being used you can find the formulae here http://www.ordnancesurvey.co.uk/oswebsite/gps/docs/A_Guide_to_Coordinate_Systems_in_Great_Britain.pdf

see Annexe B

The document contains lots of other useful stuff

B

how to open *.sdf files?

It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.

Visual Studio can also open the files directly if was created with the right version of SQL Compact.

There are also some third-party tools for manipulating them.

Create Hyperlink in Slack

In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:

  1. Copy a URL to the clipboard
  2. Select the text in a slack message you are writing that you want to be a link
  3. Press ?V on Mac or CtrlV

I couldn't find it documented anywhere, but it works, and seems very handy.

How do I specify the exit code of a console application in .NET?

In addition to the answers covering the return int's... a plea for sanity. Please, please define your exit codes in an enum, with Flags if appropriate. It makes debugging and maintenance so much easier (and, as a bonus, you can easily print out the exit codes on your help screen - you do have one of those, right?).

enum ExitCode : int {
  Success = 0,
  InvalidLogin = 1,
  InvalidFilename = 2,
  UnknownError = 10
}

int Main(string[] args) {
   return (int)ExitCode.Success;
}

Encrypt and decrypt a string in C#?

AES Algorithm:

public static class CryptographyProvider
    {
        public static string EncryptString(string plainText, out string Key)
        {
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");

            using (Aes _aesAlg = Aes.Create())
            {
                Key = Convert.ToBase64String(_aesAlg.Key);
                ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);

                using (MemoryStream _memoryStream = new MemoryStream())
                {
                    _memoryStream.Write(_aesAlg.IV, 0, 16);
                    using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))
                        {
                            _streamWriter.Write(plainText);
                        }
                        return Convert.ToBase64String(_memoryStream.ToArray());
                    }
                }
            }
        }
        public static string DecryptString(string cipherText, string Key)
        {

            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(Key))
                throw new ArgumentNullException("Key");

            string plaintext = null;

            byte[] _initialVector = new byte[16];
            byte[] _Key = Convert.FromBase64String(Key);
            byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);
            byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];

            Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);
            Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);

            using (Aes _aesAlg = Aes.Create())
            {
                _aesAlg.Key = _Key;
                _aesAlg.IV = _initialVector;
                ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);

                using (MemoryStream _memoryStream = new MemoryStream(_originalString))
                {
                    using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader _streamReader = new StreamReader(_cryptoStream))
                        {
                            plaintext = _streamReader.ReadToEnd();
                        }
                    }
                }
            }
            return plaintext;
        }
    }

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

The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.

https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.

Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.

The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.

One side effect of this limitation is that some file extensions, such as .gif match their Mime Type, image/gif, while others are compromised. This includes image/jpeg whose extension is shortened to .jpg. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.

Given that that:

  1. File Extensions are not File Types
  2. Historically, some operating systems had serious file name limitations
  3. Some operating systems will just go ahead and make up their own rules

The short answer is:

  • Technically, there is no such thing as image/jpg, so the answer is that it is not the same as image/jpeg
  • That won’t stop some operating systems and software from treating it as if it is the same

While we’re at it …

Legacy versions of Internet Explorer took the liberty of uploading jpeg files with the Mime Type of image/pjpeg, which, of course, just means more work for everybody else. They also uploaded png files as image/x-png.

How to add headers to OkHttp request interceptor?

you can do it this way

private String GET(String url, Map<String, String> header) throws IOException {
        Headers headerbuild = Headers.of(header);
        Request request = new Request.Builder().url(url).headers(headerbuild).
                        build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

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

This works in Hibernate 4(Tested).

String hql="select count(*) from  Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;

Where getCurrentSession() is:

@Autowired
private SessionFactory sessionFactory;


private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Setting environment variables on OS X

My personal practice is .bash_profile. I'm adding paths there and append to Path variable,

GOPATH=/usr/local/go/bin/
MYSQLPATH=/usr/local/opt/[email protected]/bin

PATH=$PATH:$GOPATH:$MYSQLPATH

After then I can have individual Path by echo $GOPATH, echo$MYSQLPATH or all by echo $PATH.

PHP error: "The zip extension and unzip command are both missing, skipping."

If you are using Ubuntu and PHP 7.2, use this...

sudo apt-get update
sudo apt-get install zip unzip php7.2-zip

How can I get LINQ to return the object which has the max value for a given property?

In LINQ you can solve it the following way:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

How do I find out my root MySQL password?

I'm going to make a bit of an assumption here because I'm not sure. I don't think my MySQL (running on latest 20.04 upgraded) even has a root. I have tried setting one and I remember having problems. I suspect there is not a root user and it will automatically log you in as the MySQL root user if you're logged in as root.

Why do I think this? Because when I do MySQL -u root -p, it will accept any password and log me in as the MySQL root user when I am logged in as root.

I have confirmed that trying that on a non root user doesn't work.

I like this model.

EDIT 2020.12.19: It is no longer a mystery to me why if you are logged in as the root user you get logged into MySQL as the root user. It has to do with the authentication type. Later versions of MySQL are configured with the MySQL plugin 'auth_socket' (maybe you've noticed the /run/mysqld/mysqld.sock file on your system and wondered about it). The plugin uses the SO_PEERCRED option provided by the library auth_socket.so.

You can revert back to password authentication if desired simply by create/update of the password. Showing both ways and options below to make clear.

CREATE USER 'valerie'@'localhost' IDENTIFIED WITH auth_socket;
CREATE USER 'valerie'@'localhost' IDENTIFIED BY 'password';

Use :hover to modify the css of another class?

You can do this.
When hovering to the .item1, it will change the .item2 element.

.item1 {
  size:100%;
}

.item1:hover
{
   .item2 {
     border:none;
   }
}

.item2{
  border: solid 1px blue;
}

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

How to verify CuDNN installation?

When installing on ubuntu via .deb you can use sudo apt search cudnn | grep installed

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

ansible : how to pass multiple commands

I faced the same issue. In my case, part of my variables were in a dictionary i.e. with_dict variable (looping) and I had to run 3 commands on each item.key. This solution is more relevant where you have to use with_dict dictionary with running multiple commands (without requiring with_items)

Using with_dict and with_items in one task didn't help as it was not resolving the variables.

My task was like:

- name: Make install git source
  command: "{{ item }}"
  with_items:
    - cd {{ tools_dir }}/{{ item.value.artifact_dir }}
    - make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
    - make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
  with_dict: "{{ git_versions }}"

roles/git/defaults/main.yml was:

---
tool: git
default_git: git_2_6_3

git_versions:
  git_2_6_3:
    git_tar_name: git-2.6.3.tar.gz
    git_tar_dir: git-2.6.3
    git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz

The above resulted in an error similar to the following for each {{ item }} (for 3 commands as mentioned above). As you see, the values of tools_dir is not populated (tools_dir is a variable which is defined in a common role's defaults/main.yml and also item.value.git_tar_dir value was not populated/resolved).

failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory

Solution was easy. Instead of using "COMMAND" module in Ansible, I used "Shell" module and created a a variable in roles/git/defaults/main.yml

So, now roles/git/defaults/main.yml looks like:

---
tool: git
default_git: git_2_6_3

git_versions:
  git_2_6_3:
    git_tar_name: git-2.6.3.tar.gz
    git_tar_dir: git-2.6.3
    git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz

#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"

#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"

#or use this if you want git installation to use the default prefix during make 
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"

and the task roles/git/tasks/main.yml looks like:

- name: Make install from git source
  shell: "{{ git_pre_requisites_install_cmds }}"
  become_user: "{{ build_user }}"
  with_dict: "{{ git_versions }}"
  tags:
    - koba

This time, the values got successfully substituted as the module was "SHELL" and ansible output echoed the correct values. This didn't require with_items: loop.

"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",

How do I lock the orientation to portrait mode in a iPhone Web Application?

I came up with this CSS only method of rotating the screen using media queries. The queries are based on screen sizes that I found here. 480px seemed to be a good as no/few devices had more than 480px width or less than 480px height.

@media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { 
    html{
        -webkit-transform: rotate(-90deg);
           -moz-transform: rotate(-90deg);
            -ms-transform: rotate(-90deg);
             -o-transform: rotate(-90deg);
                transform: rotate(-90deg);
        -webkit-transform-origin: left top;
           -moz-transform-origin: left top;
            -ms-transform-origin: left top;
             -o-transform-origin: left top;
                transform-origin: left top;
        width: 320px; /*this is the iPhone screen width.*/
        position: absolute;
        top: 100%;
            left: 0
    }
}

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Retrieve column values of the selected row of a multicolumn Access listbox

Use listboxControl.Column(intColumn,intRow). Both Column and Row are zero-based.

Extract a part of the filepath (a directory) in Python

First, see if you have splitunc() as an available function within os.path. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os and try to use it.

Otherwise, one semi-ugly way that gets the job done is to use:

>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'

which shows retrieving the directory just above the file, and the directory just above that.

Add all files to a commit except a single file?

You can try this: git add * && git reset main/dontcheckmein.txt

Show week number with Javascript?

I was coding in the dark (a challenge) and couldn't lookup or test my code.

I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code.

_x000D_
_x000D_
var elm = document.createElement('input')_x000D_
elm.type = 'week'_x000D_
elm.valueAsDate = new Date()_x000D_
var week = elm.value.split('W').pop()_x000D_
_x000D_
console.log(week)
_x000D_
_x000D_
_x000D_ Just a proof of concept of how you can get the week in any other way

But still i recommend any other solution that isn't required by the DOM.

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I am using wildfly 10 for javaee container . I had experienced "Target Unreachable, 'entity' returned null" issue. Thanks for suggestions by BalusC but the my issue out of the solutions explained. Accidentally using "import com.sun.istack.logging.Logger;" instead of "import org.jboss.logging.Logger;" caused CDI implemented JSF EL. Hope it helps to improve solution .

What is the "__v" field in Mongoose

For remove in NestJS need to add option to Shema() decorator

@Schema({ versionKey: false })

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Moment.js get day name from date

code

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

mydate is the input date. The variable weekDayName get the name of the day. Here the output is

Output

Wednesday

_x000D_
_x000D_
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

get the value of DisplayName attribute

Try this code:

EnumEntity.item.GetType().GetFields()[(int)EnumEntity.item].CustomAttributes.ToArray()[0].NamedArguments[0].TypedValue.ToString()

It will give you the value of data attribute Name.

Socket.io + Node.js Cross-Origin Request Blocked

I just wanted to say that after trying a bunch of things, what fixed my CORS problem was simply using an older version of socket.io (version 2.2.0). My package.json file now looks like this:

{
  "name": "current-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "socket.io": "^2.2.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.0"
  }
}


If you execute npm install with this, you may find that the CORS problem goes away when trying to use socket.io. At least it worked for me.

SQL Server copy all rows from one table into another i.e duplicate table

Duplicate your table into a table to be archived:

SELECT * INTO ArchiveTable FROM MyTable

Delete all entries in your table:

DELETE * FROM MyTable

Copy folder recursively, excluding some folders

EXCLUDE="foo bar blah jah"                                                                             
DEST=$1

for i in *
do
    for x in $EXCLUDE
    do  
        if [ $x != $i ]; then
            cp -a $i $DEST
        fi  
    done
done

Untested...

Insert auto increment primary key to existing table

The easiest and quickest I find is this

ALTER TABLE mydb.mytable 
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);

Android: combining text & image on a Button or ImageButton

just replace

android:background="@drawable/icon"

with

android:background="@android:color/transparent"
android:drawableTop="@drawable/[your background image here]"

izz a pretty good trick.. ;)

Common CSS Media Queries Break Points

Rather than try to target @media rules at specific devices, it is arguably more practical to base them on your particular layout instead. That is, gradually narrow your desktop browser window and observe the natural breakpoints for your content. It's different for every site. As long as the design flows well at each browser width, it should work pretty reliably on any screen size (and there are lots and lots of them out there.)

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

Counting the number of option tags in a select tag in jQuery

$('#input1 option').length;

This will produce 2.

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

Python: access class property from string

A picture's worth a thousand words:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

For those using Telerik as mentioned by Ovar, make sure you wrap your javascript in

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Since Telerik doesn't recognize <%# %> when looking for an element and <%= %> will give you an error if your javascript code isn't wrapped.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Make function wait until element exists

Is better to relay in requestAnimationFrame than in a setTimeout. this is my solution in es6 modules and using Promises.

es6, modules and promises:

// onElementReady.js
const onElementReady = $element => (
  new Promise((resolve) => {
    const waitForElement = () => {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
);

export default onElementReady;

// in your app
import onElementReady from './onElementReady';

const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  }

plain js and promises:

var onElementReady = function($element) {
  return new Promise((resolve) => {
    var waitForElement = function() {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
};

var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  });

How to get selected value of a html select with asp.net

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">    
<head>
    <title> HtmlSelect Example </title>
    <script runat="server">
      void Button_Click (Object sender, EventArgs e)
      {
         Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
                       + ", value: " + Select1.Value;    
      }    
   </script>    
</head>    
<body>    
   <form id="form1" runat="server">

      Select an item: 

      <select id="Select1" runat="server">    
         <option value="Text for Item 1" selected="selected"> Item 1 </option>
         <option value="Text for Item 2"> Item 2 </option>
         <option value="Text for Item 3"> Item 3 </option>
         <option value="Text for Item 4"> Item 4 </option>
      </select>

      <button onserverclick="Button_Click" runat="server" Text="Submit"/>

      <asp:Label id="Label1" runat="server"/>    
   </form>
</body>
</html>

Source from Microsoft. Hope this is helpful!

How to redirect siteA to siteB with A or CNAME records

Try changing it to "subdomain -> subdomain.hosttwo.com"

The CNAME is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the CNAME alias.

As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

In general you want to program against an interface. This allows you to exchange the implementation at any time. This is very useful especially when you get passed an implementation you don't know.

However, there are certain situations where you prefer to use the concrete implementation. For example when serialize in GWT.

How to "log in" to a website using Python's Requests module?

The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

import requests
from bs4 import BeautifulSoup

payload = {
    'email': '[email protected]',
    'password': 'passw0rd'
}     

with requests.Session() as sess:
    res = sess.get(server_name + '/signin')
    signin = BeautifulSoup(res._content, 'html.parser')
    payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
    res = sess.post(server_name + '/auth/login', data=payload)

MetadataException: Unable to load the specified metadata resource

Another cause for this exception is when you include a related table in an ObjectQuery, but type in the wrong navigation property name.

Example:

var query = (from x in myDbObjectContext.Table1.Include("FKTableSpelledWrong") select x);

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

I've gotten this error because the user trying to login was lacking permissions.

I don't recommend doing this, but I fixed it by granting the user db_owner globally. It was a local instance, so not a huge security concern.

How to timeout a thread

One thing that I've not seen mentioned is that killing threads is generally a Bad Idea. There are techniques for making threaded methods cleanly abortable, but that's different to just killing a thread after a timeout.

The risk with what you're suggesting is that you probably don't know what state the thread will be in when you kill it - so you risk introducing instability. A better solution is to make sure your threaded code either doesn't hang itself, or will respond nicely to an abort request.

How do I get the classes of all columns in a data frame?

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

Bootstrap 3 Carousel Not Working

Here is the changes you need to be done

just replace the carousel div with the below code

You have missed the '#' for data-target and add active class for the first item

<div id="carousel" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators">
                <li data-target="#carousel" data-slide-to="0"></li>
                <li data-target="#carousel" data-slide-to="1"></li>
                <li data-target="#carousel" data-slide-to="2"></li>
            </ol>
            <div class="carousel-inner">
                <div class="item active">
                    <img src="img/slide_1.png" alt="Slide 1">
                </div>
                <div class="item">
                    <img src="img/slide_2.png" alt="Slide 2">
                </div>
                <div class="item">
                    <img src="img/slide_3.png" alt="Slide 3">
                </div>
            </div>
            <a href="#carousel" class="left carousel-control" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left"></span>
            </a>
            <a href="#carousel" class="right carousel-control" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right"></span>
            </a>
        </div>

jQuery Ajax calls and the Html.AntiForgeryToken()

Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.

$(document).ready(function () {
    var securityToken = $('@Html.AntiForgeryToken()').attr('value');
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

No resource found - Theme.AppCompat.Light.DarkActionBar

Using Visual Studio 2015 (Windows7) + Xamarin had this error and after trying multiple things (installing packages, download android_m2repository_r10.zip...) ended removing the full Xamarin folder inside

C:\Users\<my user>\AppData\Local

After that, Rebuild the application in VS and errors disappeared.

how to clear JTable

You must remove the data from the TableModel used for the table.

If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

If you are using other TableModel, please check the documentation.

How to get the first word in the string

Use this regex

^\w+

\w+ matches 1 to many characters.

\w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don't want the space

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Java naming convention for static final variables

The dialog on this seems to be the antithesis of the conversation on naming interface and abstract classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final.

Abstract and Interface

When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class or interface with any identifying information that would indicate it is anything other than a class.

public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}

The developer is said not to need to know that the above classes are abstract or an interface.

Static Final

My personal preference and belief is that we should follow similar logic when referring to static final variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.

Question of Intention

We should ask ourselves what is the function of static final in our own context. Here are three examples of how static final may be used in different contexts:

public class ChatMessage {
    //Used like a private variable
    private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);

    //Used like an Enum
    public class Error {
        public static final int Success = 0;
        public static final int TooLong = 1;
        public static final int IllegalCharacters = 2;
    }

    //Used to define some static, constant, publicly visible property
    public static final int MAX_SIZE = Integer.MAX_VALUE;
}

Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.


Purpose: Private Variable

In the case of the Logger example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected or package visibility, its usage is the same:

public void send(final String message) {
    logger.info("Sending the following message: '" + message + "'.");
    //Send the message
}

Here, we don't care that logger is a static final member variable. It could simply be a final instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.

public class ChatMessage {
    private final Logger logger = LoggerFactory.getLogger(getClass());
}

You wouldn't name it LOGGER in this scenario, so why should you name it all uppercase if it was static final? Its context, or intention, is the same in both circumstances.

Note: I reversed my position on package visibility because it is more like a form of public access, restricted to package level.


Purpose: Enum

Now you might say, why are you using static final integers as an enum? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);

    private final int value;

    private Error(final int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Error fromValue(final int value) {
        switch (value) {
        case 0:
            return Error.Success;
        case 1:
            return Error.TooLong;
        case 2:
            return Error.IllegalCharacters;
        default:
            throw new IllegalArgumentException("Unknown Error value.");
        }
    }
}

There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int and int->enum. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int, short, or byte could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum vs static final int involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.

The bottom line is this, sometimes static final int will be used as an enum style structure.

If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum, the accepted style says that we don't do the following:

public enum Error {
    SUCCESS(0),
    TOOLONG(1),
    ILLEGALCHARACTERS(2);
}

Instead, we do the following:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);
}

If your static final block of integers serves as a loose enum, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.


Purpose: Static, Constant, Public Property

This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof(), but there are times when it is important to know how many bytes a data structure will occupy.

For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:

File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]

This file contains a list of MyObject objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject objects, but without knowing the size of each MyObject you have no way of knowing which bytes belong to each MyObject. So, you define the size of MyObject on MyObject:

public class MyObject {
    private final long id; //It has a 64bit identifier (+8 bytes)
    private final int value; //It has a 32bit integer value (+4 bytes)
    private final boolean special; //Is it special? (+1 byte)

    public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}

The MyObject data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject objects follow in the file:

int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;

This seems to be the typical usage case and argument for all uppercase static final constants, and I agree that in this context, all uppercase makes sense. Here's why:

Java doesn't have a struct class like the C language, but a struct is simply a class with all public members and no constructor. It's simply a data structure. So, you can declare a class in struct like fashion:

public class MyFile {
    public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!

    //The struct
    public static class MyFileHeader {
        public int fileType = MYFM;
        public int version = 0;
        public int dataSize = 0;
        public int checksumSize = 0;
    }
}

Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer or all 4 variables as constructor arguments. That said, accessing (setting in this case) this structs members would look something like:

MyFileHeader header = new MyFileHeader();
header.fileType     = buffer.getInt();
header.version      = buffer.getInt();
header.dataSize     = buffer.getInt();
header.checksumSize = buffer.getInt();

These aren't static or final, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.

Note: Even in this case, if a developer attempted to set a final variable, they would be met with either an IDE or compiler error.


Summary

In conclusion, the convention you choose for static final variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:

Methodology 1: Evaluate Context and Intention [highly subjective; logical]

  • If it's a private variable that should be indistinguishable from a private instance variable, then name them the same. all lowercase
  • If it's intention is to serve as a type of loose enum style block of static values, then name it as you would an enum. pascal case: initial-cap each word
  • If it's intention is to define some publicly accessible, constant, and static property, then let it stand out by making it all uppercase

Methodology 2: Private vs Public [objective; logical]

Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.

  • If it's private or protected then it should be all lowercase.
  • If it's public or package then it should be all uppercase.

Conclusion

This is how I view the naming convention of static final variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.

However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.

(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)

Switch android x86 screen resolution

In VirtualBox you should add custom resolution via the command:

VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"

instead of editing a .vbox file.

This solution works fine for me!

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

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

I think an enum can't be final, because under the hood compiler generates subclasses for each enum entry.

More information From source

How to trigger event when a variable's value is changed?

you can use generic class:

class Wrapped<T>  {
    private T _value;

    public Action ValueChanged;

    public T Value
    {
        get => _value;

        set
        {
            _value = value;
            OnValueChanged();
        }
    }

    protected virtual void OnValueChanged() => ValueChanged?.Invoke() ;
}

and will be able to do the following:

var i = new Wrapped<int>();

i.ValueChanged += () => { Console.WriteLine("changed!"); };

i.Value = 10;
i.Value = 10;
i.Value = 10;
i.Value = 10;

Console.ReadKey();

result:

changed!
changed!
changed!
changed!
changed!
changed!
changed!

What is the proper REST response code for a valid request but an empty data?

After looking in question, you should not use 404 why?

Based on RFC 7231 the correct status code is 204

In the anwsers above I noticed 1 small missunderstanding:

1.- the resource is: /users

2.- /users/8 is not the resource, this is: the resource /users with route parameter 8, consumer maybe cannot notice it and does not know the difference, but publisher does and must know this!... so he must return an accurate response for consumers. period.

so:

Based on the RFC: 404 is incorrect because the resources /users is found, but the logic executed using the parameter 8 did not found any content to return as a response, so the correct answer is: 204

The main point here is: 404 not even the resource was found to process the internal logic

204 is a: I found the resource, the logic was executed but I did not found any data using your criteria given in the route parameter so I cant return anything to you. Im sorry, verify your criteria and call me again.

200: ok i found the resource, the logic was executed (even when Im not forced to return anything) take this and use it at your will.

205: (the best option of a GET response) I found the resource, the logic was executed, I have some content for you, use it well, oh by the way if your are going to share this in a view please refresh the view to display it.

Hope it helps.

How can I change the user on Git Bash?

For any OS

This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1
   
# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "[email protected]"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Add HttpClientModule in your app.module.ts and try, it will work so sure. for example

import { HttpModule } from '@angular/http

Phone mask with jQuery and Masked Input Plugin

You need a jQuery plugin for the mask works as well.

-- HTML --

<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">

-- JAVASCRIPT --

<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
    $("#phone").mask("(99) 9999-9999"); 
    $("#telf1").mask("(99) 9999*-9999");    
    $("#telf2").mask("(99) 9999?-9999"); 
});
</script>

scale Image in an UIButton to AspectFit?

Expanding on Dave's answer, you can set the contentMode of the button's imageView all in IB, without any code, using Runtime Attributes:

enter image description here

  • 1 means UIViewContentModeScaleAspectFit,
  • 2 would mean UIViewContentModeScaleAspectFill.

Which terminal command to get just IP address and nothing else?

When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me eg:

$ curl ifconfig.me/ip

Over the years I have seen many of these sites come and go, I find this DNS based method more robust:

$ dig +short myip.opendns.com @resolver1.opendns.com

I have this handy alias in my ~/.bashrc:

alias wip='dig +short myip.opendns.com @resolver1.opendns.com'

Access is denied when attaching a database

With me - Running on window 8 - RIght click SQL Server Manager Studio -> Run with admin. -> attach no problems

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

If anyone is getting this error after a Phpmyadmin export, using the custom options and adding the "drop tables" statements cleared this right up.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

most collections have a useful toString() in java these days (Java7/8). So there is no need to do stream operations to concatenate what you need, just override toString of your value class in the collection and you get what you need.

both AbstractMap and AbstractCollection implement toString() by calling toString per element.

below is a testclass to show behaviour.

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class ToString {
  static class Foo {
    int i;
    public Foo(int i) { this.i=i; }
    @Override
    public String toString() {
        return "{ i: " + i + " }";
    }
  }
  public static void main(String[] args) {
    List<Foo> foo = new ArrayList<>();
    foo.add(new Foo(10));
    foo.add(new Foo(12));
    foo.add(new Foo(13));
    foo.add(new Foo(14));
    System.out.println(foo.toString());
    // prints: [{ i: 10 }, { i: 12 }, { i: 13 }, { i: 14 }]

    Map<Integer, Foo> foo2 = new HashMap<>();
    foo2.put(10, new Foo(10));
    foo2.put(12, new Foo(12));
    foo2.put(13, new Foo(13));
    foo2.put(14, new Foo(14));
    System.out.println(foo2.toString());
    // prints: {10={ i: 10 }, 12={ i: 12 }, 13={ i: 13 }, 14={ i: 14 }}
  }
}

Update Java 14 (Mar 2020)

Records are now a preview feature not requiring you to override toString() if your class only holds data. Records implement a data contract, giving public readonly access to it's fields and implementing default functions for your convience, like comparison, toString and hashcode.

so once could implement Foo as follows with the behavior:

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class ToString {
  static record Foo(int i) { }
  
  public static void main(String[] args) {
    Foo f = new Foo(10);
    System.out.println(f.toString());
    // prints: Foo[i=10]

    List<Foo> foo = new ArrayList<>();
    foo.add(new Foo(10));
    foo.add(new Foo(12));
    foo.add(new Foo(13));
    foo.add(new Foo(14));
    System.out.println(foo.toString());
    // prints: [Foo[i=10], Foo[i=12], Foo[i=13], Foo[i=14]]

    Map<Integer, Foo> foo2 = new HashMap<>();
    foo2.put(10, new Foo(10));
    foo2.put(12, new Foo(12));
    foo2.put(13, new Foo(13));
    foo2.put(14, new Foo(14));
    System.out.println(foo2.toString());
    // prints: {10=Foo[i=10], 12=Foo[i=12], 13=Foo[i=13], 14=Foo[i=14]}
  }
}

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

What port is a given program using?

You can use the 'netstat' command for this. There's a description of doing this sort of thing here.

Removing legend on charts with chart.js v2

You can change default options by using Chart.defaults.global in your javascript file. So you want to change legend and tooltip options.

Remove legend

Chart.defaults.global.legend.display = false;

Remove Tooltip

Chart.defaults.global.tooltips.enabled = false;

Here is a working fiddler.

How to change font-color for disabled input?

It seems nobody found a solution for this. I don't have one based on only css neither but by using this JavaScript trick I usually can handle disabled input fields.

Remember that disabled fields always follow the style that they got before becoming disabled. So the trick would be 1- Enabling them 2-Change the class 3- Disable them again. Since this happens very fast user cannot understand what happened.

A simple JavaScript code would be something like:

function changeDisabledClass (id, disabledClass){
var myInput=document.getElementById(id);
myInput.disabled=false;             //First make sure it is not disabled
myInput.className=disabledClass;    //change the class
myInput.disabled=true;             //Re-disable it
}

How to programmatically send a 404 response with Express/Node?

Since Express 4.0, there's a dedicated sendStatus function:

res.sendStatus(404);

If you're using an earlier version of Express, use the status function instead.

res.status(404).send('Not found');

Adding :default => true to boolean in existing Rails column

As a variation on the accepted answer you could also use the change_column_default method in your migrations:

def up
  change_column_default :profiles, :show_attribute, true
end

def down
  change_column_default :profiles, :show_attribute, nil
end

Rails API-docs

How to get jQuery dropdown value onchange event

$('#drop').change(
    function() {
        var val1 = $('#pick option:selected').val();
        var val2 = $('#drop option:selected').val();

        // Do something with val1 and val2 ...
    }
);

AngularJS For Loop with Numbers & Ranges

I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)

Directive

app.directive 'times', ->
  link: (scope, element, attrs) ->
    repeater = element.html()
    scope.$watch attrs.times, (value) ->
      element.html ''
      return unless value?
      element.html Array(value + 1).join(repeater)

To use:

HTML

<div times="customer.conversations_count">
  <i class="icon-picture></i>
</div>

Can this get any simpler?

I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.

This directive will even watch for changes in your model, and update the element accordingly.

&& (AND) and || (OR) in IF statements

Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.

An interesting fact is that Java also uses the & and | as logic operands (they are overloaded, with int types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.

How to exit in Node.js

If you're in a Unix terminal or Windows command line and want to exit the Node REPL, either...

  • Press Ctrl + C twice, or
  • type .exit and press Enter, or
  • press Ctrl + D at the start of a line (Unix only)

Get the string within brackets in Python

You can also use

re.findall(r"\[([A-Za-z0-9_]+)\]", string)

if there are many occurrences that you would like to find.

See also for more info: How can I find all matches to a regular expression in Python?

Is it possible to apply CSS to half of a character?

Example


JSFiddle DEMO

We'll do it using just CSS pseudo selectors!

This technique will work with dynamically generated content and different font sizes and widths.

HTML:

<div class='split-color'>Two is better than one.</div>

CSS:

.split-color > span {
    white-space: pre-line;
    position: relative;
    color: #409FBF;
}

.split-color > span:before {
    content: attr(data-content);
    pointer-events: none;  /* Prevents events from targeting pseudo-element */
    position: absolute;
    overflow: hidden;
    color: #264A73;
    width: 50%;
    z-index: 1;
}

To wrap the dynamically generated string, you could use a function like this:

// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function wrapString(str) {
  var output = [];
  str.split('').forEach(function(letter) {
    var wrapper = document.createElement('span');
    wrapper.dataset.content = wrapper.innerHTML = letter;

    output.push(wrapper.outerHTML);
  });

  return output.join('');
}

// Replace the original text with the split-color text
window.onload = function() {
    var el  = document.querySelector('.split-color'),
        txt = el.innerHTML;
    
    el.innerHTML = wrapString(txt);
}