Programs & Examples On #Didselectrowatindexpath

iOS - didSelectRowAtIndexPath: is a UITableView delegate method which is called when the user selects a row on a table view. Navigation logic goes here.

-didSelectRowAtIndexPath: not being called

Check if -heightForRowAtIndexPath doesnt return 0.

How to correctly use "section" tag in HTML5?

My understanding is that SECTION holds a section with a heading which is an important part of the "flow" of the page (not an aside). SECTIONs would be chapters, numbered parts of documents and so on.

ARTICLE is for syndicated content -- e.g. posts, news stories etc. ARTICLE and SECTION are completely separate -- you can have one without the other as they are very different use cases.

Another thing about SECTION is that you shouldn't use it if your page has only the one section. Also, each section must have a heading (H1-6, HGROUP, HEADING). Headings are "scoped" withing the SECTION, so e.g. if you use a H1 in the main page (outside a SECTION) and then a H1 inside the section, the latter will be treated as an H2.

The examples in the spec are pretty good at time of writing.

So in your first example would be correct if you had several sections of content which couldn't be described as ARTICLEs. (With a minor point that you wouldn't need the #primary DIV unless you wanted it for a style hook - P tags would be better).

The second example would be correct if you removed all the SECTION tags -- the data in that document would be articles, posts or something like this.

SECTIONs should not be used as containers -- DIV is still the correct use for that, and any other custom box you might come up with.

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Magento addFieldToFilter: Two fields, match as OR, not AND

public function testAction()
{
        $filter_a = array('like'=>'a%');
        $filter_b = array('like'=>'b%');
        echo(
        (string) 
        Mage::getModel('catalog/product')
        ->getCollection()
        ->addFieldToFilter('sku',array($filter_a,$filter_b))
        ->getSelect()
        );
}

Result:

WHERE (((e.sku like 'a%') or (e.sku like 'b%')))

Source: http://alanstorm.com/magento_collections

When should I use the new keyword in C++?

Method 1 (using new)

  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

Method 2 (not using new)

  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Some easy cases:

  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

Having Django serve downloadable files

I did a project on this. You can look at my github repo:

https://github.com/nishant-boro/django-rest-framework-download-expert

This module provides a simple way to serve files for download in django rest framework using Apache module Xsendfile. It also has an additional feature of serving downloads only to users belonging to a particular group

How do I fix MSB3073 error in my post-build event?

Playing around with different project properties, I found that the project build order was the problem. The project that generated the files I wanted to copy was built second, but the project that was running the batch file as a post-build event was built first, so I simply attached the build event to the second project instead, and it works just fine. Thanks for your help, everyone, though.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Please refer the below-detailed explanation.

I have used Built-in data frame in R, called mtcars.

> mtcars 
               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ... 
           ............

The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.

single square bracket "[]" operator

To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.

Eg 1:- Here is the cell value from the first row, second column of mtcars.

> mtcars[1, 2] 
[1] 6

Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.

> mtcars["Mazda RX4", "cyl"] 
[1] 6 

Double square bracket "[[]]" operator

We reference a data frame column with the double square bracket "[[]]" operator.

Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].

mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

Eg 2:- We can retrieve the same column vector by its name.

mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

How do I access an access array item by index in handlebars?

While you are looping in an array with each and if you want to access another array in the context of the current item you do it like this.

Here is the example data.


[
  {
    name: 'foo',
    attr: [ 'boo', 'zoo' ]
  },
  {
    name: 'bar',
    attr: [ 'far', 'zar' ]
  }
]

Here is the handlebars to get the first item in attr array.

{{#each player}}
  <p> {{this.name}} </p>

  {{#with this.attr}}
    <p> {{this.[0]}} </p>
  {{/with}}

{{/each}}

This will output

<p> foo </p>
<p> boo </p>

<p> bar </p>
<p> far </p>

Excel tab sheet names vs. Visual Basic sheet names

I have had to resort to this, but this has issues with upkeep.

Function sheet_match(rng As Range) As String  ' Converts Excel TAB names to the required VSB Sheetx names.
  TABname = rng.Worksheet.Name                ' Excel sheet TAB name, not VSB Sheetx name. Thanks, Bill Gates.
' Next, match this Excel sheet TAB name to the VSB Sheetx name:
   Select Case TABname 'sheet_match
      Case Is = "Sheet1": sheet_match = "Sheet1"  ' You supply these relationships
      Case Is = "Sheet2": sheet_match = "Sheet2"
      Case Is = "TABnamed": sheet_match = "Sheet3" 'Re-named TAB
      Case Is = "Sheet4": sheet_match = "Sheet4"
      Case Is = "Sheet5": sheet_match = "Sheet5"
      Case Is = "Sheet6": sheet_match = "Sheet6"
      Case Is = "Sheet7": sheet_match = "Sheet7"
      Case Is = "Sheet8": sheet_match = "Sheet8"
   End Select
End Function

Is it possible to style a select box?

You can style to some degree with CSS by itself

select {
    background: red;
    border: 2px solid pink;
}

But this is entirely up to the browser. Some browsers are stubborn.

However, this will only get you so far, and it doesn't always look very good. For complete control, you'll need to replace a select via jQuery with a widget of your own that emulates the functionality of a select box. Ensure that when JS is disabled, a normal select box is in its place. This allows more users to use your form, and it helps with accessibility.

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I had this error that wasn't solved by brew update && brew upgrade. For some reason I needed to install it from scratch:

$ brew install libpng

Removing double quotes from variables in batch file creates problems with CMD environment

Your conclusion (1) sounds wrong. There must be some other factor at play.

The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.

E.g.:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.

If you could post your entire batch code, maybe more specific answer could be made.

Set default time in bootstrap-datetimepicker

Momentjs.com has good documentation on how to manipulate the date/time in relation to the current moment. Since Momentjs is required for the Datetimepicker, might as well use it.

var startDefault = moment().startof('day').add(1, 'minutes');
$('#startdatetime-from').datetimepicker({
    defaultDate: startDefault,
    language: 'en',
    format: 'yyyy-MM-dd hh:mm'
});

Total memory used by Python process?

For Unix systems command time (/usr/bin/time) gives you that info if you pass -v. See Maximum resident set size below, which is the maximum (peak) real (not virtual) memory that was used during program execution:

$ /usr/bin/time -v ls /

    Command being timed: "ls /"
    User time (seconds): 0.00
    System time (seconds): 0.01
    Percent of CPU this job got: 250%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 0
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 315
    Voluntary context switches: 2
    Involuntary context switches: 0
    Swaps: 0
    File system inputs: 0
    File system outputs: 0
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

How to scroll to an element inside a div?

There are two facts :

1) Component scrollIntoView is not supported by safari.

2) JS framework jQuery can do the job like this:

parent = 'some parent div has css position==="fixed"' || 'html, body';

$(parent).animate({scrollTop: $(child).offset().top}, duration)

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

IntelliJ Organize Imports

In IntelliJ 14, the path to the settings for Auto Import has changed. The path is

IntelliJ IDEA->Preferences->Editor->General->Auto Import

then follow the instructions above, clicking Add unambiguous imports on the fly

I can't imagine why this wouldn't be set by default.

how to set auto increment column with sql developer

Unfortunately oracle doesnot support auto_increment like mysql does. You need to put a little extra effort to get that.

say this is your table -

CREATE TABLE MYTABLE (
  ID NUMBER NOT NULL,
  NAME VARCHAR2(100)
  CONSTRAINT "PK1" PRIMARY KEY (ID)
);

You will need to create a sequence -

CREATE SEQUENCE S_MYTABLE
START WITH 1
INCREMENT BY 1
CACHE 10;

and a trigger -

CREATE OR REPLACE TRIGGER T_MYTABLE_ID
BEFORE INSERT
ON MYTABLE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
  if(:new.ID is null) then
  SELECT S_MYTABLE.nextval
  INTO :new.ID
  FROM dual;
  end if;
END;
/

ALTER TRIGGER "T_MYTABLE_ID" ENABLE;

Start index for iterating Python list

You can always loop using an index counter the conventional C style looping:

for i in range(len(l)-1):
    print l[i+1]

It is always better to follow the "loop on every element" style because that's the normal thing to do, but if it gets in your way, just remember the conventional style is also supported, always.

LPCSTR, LPCTSTR and LPTSTR

The short answer to 2nd part of the question is simply that CString class doesn't provide a direct typecast conversion by design and what you are doing is kind of cheat.

A longer answer is the following:

The reason you can typcast CString to LPCTSTR is because CString provides this facility by overriding operator=. By design it provides conversion to only LPCTSTR pointer so the string value can't be modified with this pointer.

In other words, it simply doesn't provide an overload operator= to convert the CString into LPSTR for the same reason as above. They don't want to allow altering the string value this way.

So essentially, the trick is to use the operator CString provide and get this:

LPTSTR lptstr = (LPCTSTR) string; // CString provide this operator overload

Now LPTSTR can be further type casted to LPSTR :)

dispinfo.item.pszText = LPTSTR( lpfzfd); // accomplish the cheat :P

The correct way to get LPTSTR from 'CString' is this though (complete example):

CString str = _T("Hello");
LPTSTR lpstr = str.GetBuffer(str.GetAllocLength());
str.ReleaseBuffer(); // you must call this function if you change the string above with the pointer

Again because the GetBuffer() returns LPTSTR for that reason that now you can modify :)

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

Link a photo with the cell in excel

Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

Format the picture and in the Properties tab select "Move but don't size with cells"

Now you can sort the data table by any column and the pictures will stay with the respective data.

This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

jQuery hover and class selector

I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.

You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.

.menuItem
{
    display: inline;
    background-color: #000;

    /* width and height should not work on inline elements */
    /* if this works, your browser is doing the rendering  */
    /* in quirks mode which will not be compatible with    */
    /* other browsers - but this will not work on touch mobile devices like android */

}
.menuItem a:hover 
{
    background-color:#F00;
}

Change the background color of a row in a JTable

The call to getTableCellRendererComponent(...) includes the value of the cell for which a renderer is sought.

You can use that value to compute a color. If you're also using an AbstractTableModel, you can provide a value of arbitrary type to your renderer.

Once you have a color, you can setBackground() on the component that you're returning.

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

How to get the list of all database users

Go for this:

 SELECT name,type_desc FROM sys.sql_logins

Change tab bar tint color on iOS 7

After trying out all the suggested solutions, I couldn't find any very helpful.

I finally tried the following:

[self.tabBar setTintColor:[UIColor orangeColor]];

which worked out perfectly.

I only provided one image for every TabBarItem. Didn't even need a selectedImage.

I even used it inside the Child-ViewControllers to set different TintColors:

UIColor *theColorYouWish = ...;
if ([[self.parentViewController class] isSubclassOfClass:[UITabBarController class]]){
    UITabBarController *tbc = (UITabBarController *) self.parentViewController;
    [tbc.tabBar setTintColor:theColorYouWish];
}

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

vuejs update parent data from child component

I don't know why, but I just successfully updated parent data with using data as object, :set & computed

Parent.vue

<!-- check inventory status - component -->
    <CheckInventory :inventory="inventory"></CheckInventory>

data() {
            return {
                inventory: {
                    status: null
                },
            }
        },

Child.vue

<div :set="checkInventory">

props: ['inventory'],

computed: {
            checkInventory() {

                this.inventory.status = "Out of stock";
                return this.inventory.status;

            },
        }

Virtual member call in a constructor

Beware of blindly following Resharper's advice and making the class sealed! If it's a model in EF Code First it will remove the virtual keyword and that would disable lazy loading of it's relationships.

    public **virtual** User User{ get; set; }

How to position text over an image in css

Why not set sample.png as background image of text or h2 css class? This will give effect as you have written over an image.

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

What are examples of TCP and UDP in real life?

UDP is applied a lot in games or other Peer-to-peer setups because it's faster and most of the time you don't need the protocol itself to make sure everything gets to the destination in the original order (UDP does not garantee packet delivery or delivery order).

Web traffic on the other hand is over TCP. (I'm not sure here but I think it has to do with the way the HTTP protocol is built)

Edited because I failed at UDP.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best collation to use for MySQL with PHP?

The accepted answer fairly definitively suggests using utf8_unicode_ci, and whilst for new projects that's great, I wanted to relate my recent contrary experience just in case it saves anyone some time.

Because utf8_general_ci is the default collation for Unicode in MySQL, if you want to use utf8_unicode_ci then you end up having to specify it in a lot of places.

For example, all client connections not only have a default charset (makes sense to me) but also a default collation (i.e. the collation will always default to utf8_general_ci for unicode).

Likely, if you use utf8_unicode_ci for your fields, your scripts that connect to the database will need to be updated to mention the desired collation explicitly -- otherwise queries using text strings can fail when your connection is using the default collation.

The upshot is that when converting an existing system of any size to Unicode/utf8, you may end up being forced to use utf8_general_ci because of the way MySQL handles defaults.

What is the easiest way to remove the first character from a string?

For example : a = "One Two Three"

1.9.2-p290 > a = "One Two Three"
 => "One Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "ne Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "e Two Three" 

1.9.2-p290 > a = a[1..-1]
 => " Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "Two Three" 

1.9.2-p290 > a = a[1..-1]
 => "wo Three" 

In this way you can remove one by one first character of the string.

What is the best way to dump entire objects to a log in C#?

You could use Visual Studio Immediate Window

Just paste this (change actual to your object name obviously):

Newtonsoft.Json.JsonConvert.SerializeObject(actual);

It should print object in JSON enter image description here

You should be able to copy it over textmechanic text tool or notepad++ and replace escaped quotes (\") with " and newlines (\r\n) with empty space, then remove double quotes (") from beginning and end and paste it to jsbeautifier to make it more readable.

UPDATE to OP's comment

public static class Dumper
{
    public static void Dump(this object obj)
    {
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); // your logger
    }
}

this should allow you to dump any object.

Hope this saves you some time.

Android Studio doesn't recognize my device

I am sorry that i bothered you all. The problem was my device is cloned in different places in device manager. It was gone when I tried to update driver for my phone in "Other devices" list, and before i have been updating it in wrong sections. Thank you all.

How do you completely remove Ionic and Cordova installation from mac?

1) first remove cordova cmd

npm uninstall -g cordova

2) After that remove ionic

npm uninstall -g ionic

Change a Git remote HEAD to point to something besides master

See: http://www.kernel.org/pub/software/scm/git/docs/git-symbolic-ref.html

This sets the default branch in the git repository. You can run this in bare or mirrored repositories.

Usage:

$ git symbolic-ref HEAD refs/heads/<branch name>

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

How can I make my website's background transparent without making the content (images & text) transparent too?

Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...

Is there a typical state machine implementation pattern?

I prefer to use a table driven approach for most state machines:

typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;
typedef struct instance_data instance_data_t;
typedef state_t state_func_t( instance_data_t *data );

state_t do_state_initial( instance_data_t *data );
state_t do_state_foo( instance_data_t *data );
state_t do_state_bar( instance_data_t *data );

state_func_t* const state_table[ NUM_STATES ] = {
    do_state_initial, do_state_foo, do_state_bar
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
    return state_table[ cur_state ]( data );
};

int main( void ) {
    state_t cur_state = STATE_INITIAL;
    instance_data_t data;

    while ( 1 ) {
        cur_state = run_state( cur_state, &data );

        // do other program logic, run other state machines, etc
    }
}

This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well:

typedef void transition_func_t( instance_data_t *data );

void do_initial_to_foo( instance_data_t *data );
void do_foo_to_bar( instance_data_t *data );
void do_bar_to_initial( instance_data_t *data );
void do_bar_to_foo( instance_data_t *data );
void do_bar_to_bar( instance_data_t *data );

transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = {
    { NULL,              do_initial_to_foo, NULL },
    { NULL,              NULL,              do_foo_to_bar },
    { do_bar_to_initial, do_bar_to_foo,     do_bar_to_bar }
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
    state_t new_state = state_table[ cur_state ]( data );
    transition_func_t *transition =
               transition_table[ cur_state ][ new_state ];

    if ( transition ) {
        transition( data );
    }

    return new_state;
};

The table driven approach is easier to maintain and extend and simpler to map to state diagrams.

Set a DateTime database field to "Now"

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

What does cmd /C mean?

CMD.exe

Start a new CMD shell

Syntax
      CMD [charset] [options] [My_Command] 

Options       

**/C     Carries out My_Command and then
terminates**

From the help.

How to put a new line into a wpf TextBlock control?

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details : http://msdn.microsoft.com/en-us/library/ms788746.aspx

How to delete a cookie?

You can do this by setting the date of expiry to yesterday.

Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

Documentation for parseDouble() says "Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.", so they should be identical.

How to select a value in dropdown javascript?

easiest way is to just use this

document.getElementById("mySelect").value = "banana";

myselect is name of your dropdown banana is just one of items in your dropdown list

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

"commence before first target. Stop." error

This could also caused by mismatching brace/parenthesis.

$(TARGET}:
    do_something

Just use parenthesises and you'll be fine.

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

SQL Server IF EXISTS THEN 1 ELSE 2

What the output that you need, select or print or .. so on.

so use the following code:

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2

builder for HashMap

There is no such thing for HashMaps, but you can create an ImmutableMap with a builder:

final Map<String, Integer> m = ImmutableMap.<String, Integer>builder().
      put("a", 1).
      put("b", 2).
      build();

And if you need a mutable map, you can just feed that to the HashMap constructor.

final Map<String, Integer> m = Maps.newHashMap(
    ImmutableMap.<String, Integer>builder().
        put("a", 1).
        put("b", 2).
        build());

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

How can you search Google Programmatically Java API

In light of those TOS alterations last year we built an API that gives access to Google's search. It was for our own use only but after some requests we decided to open it up. We're planning to add additional search engines in the future!

Should anyone be looking for an easy way to implement / acquire search results you are free to sign up and give the REST API a try: https://searchapi.io

It returns JSON results and should be easy enough to implement with the detailed docs.

It's a shame that Bing and Yahoo are miles ahead on Google in this regard. Their APIs aren't cheap, but at least available.

How do I revert my changes to a git submodule?

my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):

git submodule foreach 'git checkout master && git reset --hard $sha1'

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Does height and width not apply to span?

Span takes width and height only when we make it block element.

span {display:block;}

Close iOS Keyboard by touching anywhere using Swift

You can call

resignFirstResponder()

on any instance of a UIResponder, such as a UITextField. If you call it on the view that is currently causing the keyboard to be displayed then the keyboard will dismiss.

How to add an image to the emulator gallery in android studio?

Copy a file to the emulator:

Open emulator and File Explorer (Finder in Mac) side by side. Choose the file you want to copy then Drag and Drop the file onto the emulator. The selected file will be copied to the Downloads folder of the emulator.

How to view files in Android Studio:

Android Studio has Device Explorer to explore emulator content (Earlier we used to have DDMS, which is deprecated in Studio 3+). Goto View -> Tools Window -> Device File Explorer and you can see the explorer window. Goto Storage -> emulated -> 0 ->Download, if you don't see the file here, please restart the emulator and that's it.

Note: You don't see Device Explorer if you have opened a Flutter project.

You can also view the image files in Android Studio by double-clicking the file in the emulator.

See image below

Navigation bar show/hide

To hide Navigation bar :

[self.navigationController setNavigationBarHidden:YES animated:YES];

To show Navigation bar :

[self.navigationController setNavigationBarHidden:NO animated:YES];

Regular expression for first and last name

Don't forget about names like:

  • Mathias d'Arras
  • Martin Luther King, Jr.
  • Hector Sausage-Hausen

This should do the trick for most things:

/^[a-z ,.'-]+$/i

OR Support international names with super sweet unicode:

/^[a-zA-ZàáâäãåacceèéêëeiìíîïlnòóôöõøùúûüuuÿýzzñçcšžÀÁÂÄÃÅACCEEÈÉÊËÌÍÎÏILNÒÓÔÖÕØÙÚÛÜUUŸÝZZÑßÇŒÆCŠŽ?ð ,.'-]+$/u

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

A Space between Inline-Block List Items

Actually, this is not specific to display:inline-block, but also applies to display:inline. Thus, in addition to David Horák's solution, this also works:

ul {
    font-size: 0;
}
ul li {
    font-size: 14px;
    display: inline;
}

Fetch first element which matches criteria

When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));

is incorrect syntax; but

this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));

is correct. Or:

this.stops.stream().filter(s -> s.getStation().getName().equals(name));

is also correct if the compiler has enough information to figure out the types.

How to connect to MongoDB in Windows?

  1. As Admin, create directory:

    mkdir c:\mongo\data\db
    
  2. As Admin, install service:

    .\mongod.exe --install --logpath c:\mongo\logs --logappend --bind_ip 127.0.0.1 --dbpath c:\mongo\data\db --directoryperdb
    
  3. Start MongoDB:

    net start MongoDB
    
  4. Start Mongo Shell:

    c:\mongo\bin\mongo.exe
    

What should be in my .gitignore for an Android Studio project?

.gitignore from AndroidRate library

# Copyright 2017 - 2018 Vorlonsoft LLC
#
# Licensed under The MIT License (MIT)

# Built application files
*.ap_
*.apk

# Built library files
*.aar
*.jar

# Built native files
*.o
*.so

# Files for the Dalvik/Android Runtime (ART)
*.dex
*.odex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk/ndk path, etc)
local.properties

# Windows thumbnail cache
Thumbs.db

# macOS
.DS_Store/

# Log Files
*.log

# Android Studio
.navigation/
captures/
output.json

# NDK
.externalNativeBuild/
obj/

# IntelliJ
## User-specific stuff
.idea/**/tasks.xml
.idea/**/workspace.xml
.idea/dictionaries
## Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/dynamic.xml
.idea/**/sqlDataSources.xml
.idea/**/uiDesigner.xml
## Gradle
.idea/**/gradle.xml
.idea/**/libraries
## VCS
.idea/vcs.xml
## Module files
*.iml
## File-based project format
*.iws

How to upload multiple files using PHP, jQuery and AJAX

My solution

  • Assuming that form id = "my_form_id"
  • It detects the form method and form action from HTML

jQuery code

$('#my_form_id').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    var msg_error = 'An error has occured. Please try again later.';
    var msg_timeout = 'The server is not responding';
    var message = '';
    var form = $('#my_form_id');
    $.ajax({
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        url: form.attr('action'),
        type: form.attr('method'),
        error: function(xhr, status, error) {
            if (status==="timeout") {
                alert(msg_timeout);
            } else {
                alert(msg_error);
            }
        },
        success: function(response) {
            alert(response);
        },
        timeout: 7000
    });
});

RegEx for valid international mobile phone number

Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.

Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.

django order_by query set, ascending and descending

This is working for me.

latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

findViewById in Fragment

You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View variables. Here's an example:

class GalleryFragment extends Fragment {
    private Gallery gallery;

    (...)

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        gallery = (Gallery) view.findViewById(R.id.gallery);
        gallery.setAdapter(adapter);
        super.onViewCreated(view, savedInstanceState);
    }
}

Create a one to many relationship using SQL Server

  1. Define two tables (example A and B), with their own primary key
  2. Define a column in Table A as having a Foreign key relationship based on the primary key of Table B

This means that Table A can have one or more records relating to a single record in Table B.

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 
  • fk_b: Name of the foreign key constraint, must be unique to the database
  • b_id: Name of column in Table A you are creating the foreign key relationship on
  • b: Name of table, in this case b
  • id: Name of column in Table B

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Recommended way to embed PDF in HTML?

FDView combines PDF2SWF (which itself is based on xpdf) with an SWF viewer so you can convert and embed PDF documents on the fly on your server.

xpdf is not a perfect PDF converter. If you need better results then Ghostview has some ability to convert PDF documents into other formats which you may be able to more easily build a Flash viewer for.

But for simple PDF documents, FDView should work reasonably well.

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

MySQL string replace

The replace function should work for you.

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.

Pandas read_csv from url

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
c = pd.read_csv(url, sep = "\t")

Javascript sleep/delay/wait function

You will have to use a setTimeout so I see your issue as

I have a script that is generated by PHP, and so am not able to put it into two different functions

What prevents you from generating two functions in your script?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';
}

Could be rewritten as

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it
}

You'll notice that a inside baz starts as buzz when it is invoked and at the end of invocation, a inside foo will be "complete".

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds you echo a setTimeout, end the function and start a new function to pick up where you left off.

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

If you just want to suppress warnings from a function, you can add an @ sign in front:

<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>

How to get the difference between two arrays in JavaScript?

Cast to string object type:

[1, 1].toString() === [1, 1].toString(); // true

SQL Server Restore Error - Access is Denied

From the error message, it says there's an error when validating the target (c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf) of your restore operation.

That sounds like:

a) that file already exists (because you've already restored it previously) and is in use by SQL Server

or

b) that directory doesn't exist at all

In your question, you mentioned you created a backup for that table - that's not how SQL Server backups work. Those backups are always the whole database (or at least one or several filegroups from that database).

My hunch is: you've already restored that database previously, and now, upon a second restore, you didn't check the checkbox "Overwrite existing database" in your restore wizard - thus the existing file cannot be overwritten and the restore fails.

The user that's running the restore on your remote server obviously doesn't have access to that directory on the remote server.

C:\program files\.... is a protected directory - normal (non-admin) users don't have access to this directory (and its subdirectories).

Easiest solution: try putting your BAK file somewhere else (e.g. C:\temp) and restore it from there

How can I show line numbers in Eclipse?

Eclipse has a search feature in the top left box of the Preferences. Type in 'line numbers' in that search box, and presto...

In case you're tired of googling each time you forget...

What's the best way to set a single pixel in an HTML5 canvas?

Fast HTML Demo code: Based on what I know about SFML C++ graphics library:

Save this as an HTML file with UTF-8 Encoding and run it. Feel free to refactor, I just like using japanese variables because they are concise and don't take up much space

Rarely are you going to want to set ONE arbitrary pixel and display it on the screen. So use the

PutPix(x,y, r,g,b,a) 

method to draw numerous arbitrary pixels to a back-buffer. (cheap calls)

Then when ready to show, call the

Apply() 

method to display the changes. (expensive call)

Full .HTML file code below:

<!DOCTYPE HTML >
<html lang="en">
<head>
    <title> back-buffer demo </title>
</head>
<body>

</body>

<script>
//Main function to execute once 
//all script is loaded:
function main(){

    //Create a canvas:
    var canvas;
    canvas = attachCanvasToDom();

    //Do the pixel setting test:
    var test_type = FAST_TEST;
    backBufferTest(canvas, test_type);
}

//Constants:
var SLOW_TEST = 1;
var FAST_TEST = 2;


function attachCanvasToDom(){
    //Canvas Creation:
    //cccccccccccccccccccccccccccccccccccccccccc//
    //Create Canvas and append to body:
    var can = document.createElement('canvas');
    document.body.appendChild(can);

    //Make canvas non-zero in size, 
    //so we can see it:
    can.width = 800;
    can.height= 600;

    //Get the context, fill canvas to get visual:
    var ctx = can.getContext("2d");
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(0,0,can.width-1, can.height-1);
    //cccccccccccccccccccccccccccccccccccccccccc//

    //Return the canvas that was created:
    return can;
}

//THIS OBJECT IS SLOOOOOWW!
// ? == "pen"
//T? == "Type:Pen"
function T?(canvas){


    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //?  =="image"
    //?  =="data"
    //??=="image data"
    //?  =="pen"
    var _?? = _ctx.createImageData(1,1); 
    // only do this once per page
    var _?  = _??.data;   


    function _putPix(x,y,  r,g,b,a){
        _?[0]   = r;
        _?[1]   = g;
        _?[2]   = b;
        _?[3]   = a;
        _ctx.putImageData( _??, x, y );  
    }
}

//Back-buffer object, for fast pixel setting:
//? =="butt,rear" using to mean "back-buffer"
//T?=="type: back-buffer"
function T?(canvas){

    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    this.Apply  = _apply;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _can = canvas;
    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //?  =="image"
    //?  =="data"
    //??=="image data"
    //?  =="pen"
    var _w = _can.width;
    var _h = _can.height;
    var _?? = _ctx.createImageData(_w,_h); 
    // only do this once per page
    var _?  = _??.data;   


    function _putPix(x,y,  r,g,b,a){

        //Convert XY to index:
        var dex = ( (y*4) *_w) + (x*4);

        _?[dex+0]   = r;
        _?[dex+1]   = g;
        _?[dex+2]   = b;
        _?[dex+3]   = a;

    }

    function _apply(){
        _ctx.putImageData( _??, 0,0 );  
    }

}

function backBufferTest(canvas_input, test_type){
    var can = canvas_input; //shorthand var.

    if(test_type==SLOW_TEST){
        var t? = new T?( can );

        //Iterate over entire canvas, 
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t?.PutPix(
                x,y, 
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

    }else
    if(test_type==FAST_TEST){
        var t? = new T?( can );

        //Iterate over entire canvas, 
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t?.PutPix(
                x,y, 
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

        //When done setting arbitrary pixels,
        //use the apply method to show them 
        //on screen:
        t?.Apply();

    }
}


main();
</script>
</html>

How to show multiline text in a table cell

the below code works like magic to me >>

td { white-space:pre-line }

Get encoding of a file in Windows

Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click "Save As...".
It'll look like this: enter image description here

Whatever the default-selected encoding is, that is what your current encoding is for the file.
If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).

I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.

FYI: From my understanding I think "Unicode" (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad's "Unicode" option: Windows 7 - UTF-8 and Unicdoe

jQuery UI Dialog with ASP.NET button postback

You are close to the solution, just getting the wrong object. It should be like this:

jQuery(function() {
    var dlg = jQuery("#dialog").dialog({
                         draggable: true,
                         resizable: true,
                         show: 'Transfer',
                         hide: 'Transfer',
                         width: 320,
                         autoOpen: false,
                         minHeight: 10,
                         minwidth: 10
                     });
    dlg.parent().appendTo(jQuery("form:first"));
});

How to get exception message in Python properly

I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:

try:
    pass
    log.info('Success')
except:
    log.exception('Failed')

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

What is the best way to calculate a checksum for a file that is on my machine?

Just use win32 Checksum api. MD5 is native in Win32.

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Print <div id="printarea"></div> only?

base on @Kevin Florida answer, i made a way to avoid script on current page disable because of overwrite content. I use other file called "printScreen.php" (or .html). Wrap everything you want to print in a div "printSource". And with javascript, open a new window you created before ("printScreen.php") then grab content in "printSource" of top window.

Here is the code.

Main window :

echo "<div id='printSource'>";
//everything you want to print here
echo "</div>";

//add button or link to print
echo "<button id='btnPrint'>Print</button>";

<script>
  $("#btnPrint").click(function(){
    printDiv("printSource");
  });

  function printDiv(divName) {
   var printContents = document.getElementById(divName).innerHTML;
   var originalContents = document.body.innerHTML;
   w=window.open("printScreen.php", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=50,left=50,width=900,height=400");
   }
</script>

This is "printScreen.php" - other file to grab content to print

<head>
// write everything about style/script here (.css, .js)

</head>
<body id='mainBody'></body>
</html>


<script>
    //get everything you want to print from top window
    src = window.opener.document.getElementById("printSource").innerHTML;

    //paste to "mainBody"
    $("#mainBody").html(src);
    window.print();
    window.close();
</script>

How to manage local vs production settings in Django?

In settings.py:

try:
    from local_settings import *
except ImportError as e:
    pass

You can override what needed in local_settings.py; it should stay out of your version control then. But since you mention copying I'm guessing you use none ;)

Flutter plugin not installed error;. When running flutter doctor

I’ve just had this problem after an update and I solved entering File/Settings/Plugins. Then at the top of the window there are two options: Marketplace and Installed, then I clicked on Installed and on Flutter plugin there’s was message saying that the current version of Flutter does not support the new version of Android Studio, so there was a green button Written “Restart” then I clicked and when It opened again, the problem disappeared. May not be the same for you, but many people will search for it here and may help someone.

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

How do you echo a 4-digit Unicode character in Bash?

Easy with a Python2/3 one-liner:

$ python -c 'print u"\u2620"'    # python2
$ python3 -c 'print(u"\u2620")'  # python3

Results in:

?

How do you define a class of constants in Java?

As Joshua Bloch notes in Effective Java:

  • Interfaces should only be used to define types,
  • abstract classes don't prevent instanciability (they can be subclassed, and even suggest that they are designed to be subclassed).

You can use an Enum if all your constants are related (like planet names), put the constant values in classes they are related to (if you have access to them), or use a non instanciable utility class (define a private default constructor).

class SomeConstants
{
    // Prevents instanciation of myself and my subclasses
    private SomeConstants() {}

    public final static String TOTO = "toto";
    public final static Integer TEN = 10;
    //...
}

Then, as already stated, you can use static imports to use your constants.

Remove leading zeros from a number in Javascript

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

_x000D_
_x000D_
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
_x000D_
_x000D_


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

_x000D_
_x000D_
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
_x000D_
_x000D_

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

_x000D_
_x000D_
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
_x000D_
_x000D_

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal)
  • If the input string begins with any other value, the radix is 10 (decimal)

Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

For this reason, always specify a radix when using parseInt

How to center an unordered list?

http://jsfiddle.net/psbu2/3/

If it is possible for you to use your own list bullets

Try this:

<html>
    <head>
        <style type="text/css">

            ul {
                margin:0;
                padding:0;
                text-align: center;
                list-style:none;                
            }
            ul  li {
                padding: 2px 5px;               
            }

            ul li:before {
                content:url(http://www.un.org/en/oaj/unjs/efiling/added/images/bullet-list-icon-blue.jpg);;
            }
        </style>
    </head>
    <body>

            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
            </ul>

    </body>
</html>

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

pypi UserWarning: Unknown distribution option: 'install_requires'

I'm on a Mac with python 2.7.11. I have been toying with creating extremely simple and straightforward projects, where my only requirement is that I can run python setup.py install, and have setup.py use the setup command, ideally from distutils. There are literally no other imports or code aside from the kwargs to setup() other than what I note here.

I get the error when the imports for my setup.py file are:

from distutils.core import setup

When I use this, I get warnings such as

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'entry_points' warnings.warn(msg)

If I change the imports (and nothing else) to the following:

from distutils.core import setup
import setuptools  # noqa

The warnings go away.

Note that I am not using setuptools, just importing it changes the behavior such that it no longer emits the warnings. For me, this is the cause of a truly baffling difference where some projects I'm using give those warnings, and some others do not.

Clearly, some form of monkey-patching is going on, and it is affected by whether or not that import is done. This probably isn't the situation for everyone researching this problem, but for the narrow environment in which I'm working, this is the answer I was looking for.


This is consistent with the other (community) comment, which says that distutils should monkeypatch setuptools, and that they had the problem when installing Ansible. Ansible appears to have tried to allow installs without having setuptools in the past, and then went back on that.

https://github.com/ansible/ansible/blob/devel/setup.py

A lot of stuff is up in the air... but if you're looking for a simple answer for a simple project, you should probably just import setuptools.

Read values into a shell variable from a pipe

How about this:

echo "hello world" | echo test=$(cat)

Start new Activity and finish current one in Android?

FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.

http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY

Allow docker container to connect to a local/host postgres database

Docker for Mac solution

17.06 onwards

Thanks to @Birchlabs' comment, now it is tons easier with this special Mac-only DNS name available:

docker run -e DB_PORT=5432 -e DB_HOST=docker.for.mac.host.internal

From 17.12.0-cd-mac46, docker.for.mac.host.internal should be used instead of docker.for.mac.localhost. See release note for details.

Older version

@helmbert's answer well explains the issue. But Docker for Mac does not expose the bridge network, so I had to do this trick to workaround the limitation:

$ sudo ifconfig lo0 alias 10.200.10.1/24

Open /usr/local/var/postgres/pg_hba.conf and add this line:

host    all             all             10.200.10.1/24            trust

Open /usr/local/var/postgres/postgresql.conf and edit change listen_addresses:

listen_addresses = '*'

Reload service and launch your container:

$ PGDATA=/usr/local/var/postgres pg_ctl reload
$ docker run -e DB_PORT=5432 -e DB_HOST=10.200.10.1 my_app 

What this workaround does is basically same with @helmbert's answer, but uses an IP address that is attached to lo0 instead of docker0 network interface.

What does a circled plus mean?

That's the XOR operator, not the PLUS operator

XOR works bit by bit, without carrying over like PLUS does

1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 0 = 0
0 XOR 1 = 1

Scrolling to element using webdriver?

You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains class:

from selenium.webdriver.common.action_chains import ActionChains

element = driver.find_element_by_id("my-id")

actions = ActionChains(driver)
actions.move_to_element(element).perform()

Or, you can also "scroll into view" via scrollIntoView():

driver.execute_script("arguments[0].scrollIntoView();", element)

If you are interested in the differences:

Joining three tables using MySQL

Simply use:

select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 

How to create Android Facebook Key Hash?

There is a short solution too. Just run this in your app:

FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this));

A longer one that doesn't need FB SDK (based on a solution here) :

public static void printHashKey(Context context) {
    try {
        final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        for (android.content.pm.Signature signature : info.signatures) {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            final String hashKey = new String(Base64.encode(md.digest(), 0));
            Log.i("AppLog", "key:" + hashKey + "=");
        }
    } catch (Exception e) {
        Log.e("AppLog", "error:", e);
    }
}

The result should end with "=" .

Does "git fetch --tags" include "git fetch"?

The general problem here is that git fetch will fetch +refs/heads/*:refs/remotes/$remote/*. If any of these commits have tags, those tags will also be fetched. However if there are tags not reachable by any branch on the remote, they will not be fetched.

The --tags option switches the refspec to +refs/tags/*:refs/tags/*. You could ask git fetch to grab both. I'm pretty sure to just do a git fetch && git fetch -t you'd use the following command:

git fetch origin "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/*"

And if you wanted to make this the default for this repo, you can add a second refspec to the default fetch:

git config --local --add remote.origin.fetch "+refs/tags/*:refs/tags/*"

This will add a second fetch = line in the .git/config for this remote.


I spent a while looking for the way to handle this for a project. This is what I came up with.

git fetch -fup origin "+refs/*:refs/*"

In my case I wanted these features

  • Grab all heads and tags from the remote so use refspec refs/*:refs/*
  • Overwrite local branches and tags with non-fast-forward + before the refspec
  • Overwrite currently checked out branch if needed -u
  • Delete branches and tags not present in remote -p
  • And force to be sure -f

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

Is there a way to collapse all code blocks in Eclipse?

Right click on the +/- sign and click collapse all or expand all.

Printing variables in Python 3.4

Version 3.6+: Use a formatted string literal, f-string for short

print(f"{i}. {key} appears {wordBank[key]} times.")

Powershell v3 Invoke-WebRequest HTTPS error

  1. Run this command

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}

in powershell using admin rights, This will generate all certificates in Personal directory

  1. To get rid of Privacy error, select these certificates, right click ? Copy. And paste in Trusted Root Certification Authority/Certificates.
  2. Last step is to select correct bindings in IIS. Go to IIS website, select Bindings, Select SNI checkbox and set the individual certificates for each website.

Make sure website hostname and certificate dns-name should exactly match

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

I had the same issue when forking with 'python'; the main reason is that the search path is relative, if you don't call g++ as /usr/bin/g++, it will not be able to work out the canonical paths to call cc1plus.

AngularJS : automatically detect change in model

And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified

It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.

You can setup the following watch: $scope.$watch('myForm.modified', handler) and your handler will be called if some form elements actually contains new data or if it reversed to initial state.

Also, you can use modified property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.

As a bonus, you can revert your form to initial state via call to form's reset() method.

You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview

Cheers!

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

Default Xmxsize in Java 8 (max heap size)

As of 8, May, 2019:

JVM heap size depends on system configuration, meaning:

a) client jvm vs server jvm

b) 32bit vs 64bit.

Links:

1) updation from J2SE5.0: https://docs.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
2) brief answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html
3) detailed answer: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#default_heap_size
4) client vs server: https://www.javacodegeeks.com/2011/07/jvm-options-client-vs-server.html

Summary: (Its tough to understand from the above links. So summarizing them here)

1) Default maximum heap size for Client jvm is 256mb (there is an exception, read from links above).

2) Default maximum heap size for Server jvm of 32bit is 1gb and of 64 bit is 32gb (again there are exceptions here too. Kindly read that from the links).

So default maximum jvm heap size is: 256mb or 1gb or 32gb depending on VM, above.

Getting Database connection in pure JPA setup

if you use EclipseLink: You should be in a JPA transaction to access the Connection

entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

Difference between SRC and HREF

after going through the HTML 5.1 ducumentation (1 November 2016):


part 4 (The elements of HTML)

chapter 2 (Document metadata)

section 4 (The link element) states that:

The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.

does not contain the src attribute ...

witch is logical because it is a link .


chapter 12 (Scripting)

section 1 (The script element) states that:

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.

it doesn't even mention the href attribute ...

this indicates that while using script tags always use the src attribute !!!


chapter 7 (Embedded content)

section 5 (The img element)

The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.

also doesn't mention the href attribute ...

this indicates that when using img tags the src attribute should be used aswell ...


Reference link to the W3C Recommendation

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

HTML Text with tags to formatted text in an Excel cell

I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:

_x000D_
_x000D_
.ExecWB 17, 0_x000D_
'Select all contents in browser_x000D_
.ExecWB 12, 2_x000D_
'Copy them
_x000D_
_x000D_
_x000D_

And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:

_x000D_
_x000D_
Sub ApplyHTML()_x000D_
  On Error GoTo ErrorHandler_x000D_
    ..._x000D_
  Exit Sub_x000D_
_x000D_
ErrorHandler:_x000D_
    Resume _x000D_
    'I.e. re-run the line of code that caused the error_x000D_
Exit Sub_x000D_
     _x000D_
End Sub
_x000D_
_x000D_
_x000D_

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

How can I escape square brackets in a LIKE clause?

Here is what I actually used:

like 'WC![R]S123456' ESCAPE '!'

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

Key error when selecting columns in pandas dataframe after read_csv

The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':

You could also try:

import csv
import pandas as pd
import re
    with open (filename, "r") as file:
        df = pd.read_csv(file, delimiter = ",")
        df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
        print(df.columns)

How do I make Visual Studio pause after executing a console application in debug mode?

I start the app with F11 and get a breakpoint somewhere in unit_test_main.ipp (can be assembly code). I use shift-f11 (Step out) to run the unit test and get the next assembly instruction in the CRT (normally in mainCRTStartup()). I use F9 to set a breakpoint at that instruction.

On the next invocation, I can start the app with F5 and the app will break after running the tests, therefore giving me a chance to peek at the console window

How do I correct the character encoding of a file?

And then there is the somewhat older recode program.

Launch programs whose path contains spaces

find an .exe file for the application you want to run example iexplore.exe and firefox.exe and remove .exe and use it in objShell.Run("firefox")

I hope this helps.

Send mail via Gmail with PowerShell V2's Send-MailMessage

I haven't used PowerShell V2's Send-MailMessage, but I have used System.Net.Mail.SMTPClient class in V1 to send messages to a Gmail account for demo purposes. This might be overkill, but I run an SMTP server on my Windows Vista laptop (see this link). If you're in an enterprise you will already have a mail relay server, and this step isn't necessary. Having an SMTP server I'm able to send email to my Gmail account with the following code:

$smtpmail = [System.Net.Mail.SMTPClient]("127.0.0.1")
$smtpmail.Send("[email protected]", "[email protected]", "Test Message", "Message via local SMTP")

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

An alternative to overriding VerifyRenderingInServerForm is to remove the grid from the controls collection while you do the render, and then add it back when you are finished before the page loads. This is helpful if you want to have some generic helper method to get grid html because you don't have to remember to add the override.

Control parent = grid.Parent;
int GridIndex = 0;
if (parent != null)
{
    GridIndex = parent.Controls.IndexOf(grid);
    parent.Controls.Remove(grid);
}

grid.RenderControl(hw);

if (parent != null)
{
    parent.Controls.AddAt(GridIndex, grid);
}

Another alternative to avoid the override is to do this:

grid.RenderBeginTag(hw);
grid.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grid.Rows)
{
    row.RenderControl(hw);
}
grid.FooterRow.RenderControl(hw);
grid.RenderEndTag(hw);

asp.net mvc3 return raw html to view

In controller you can use MvcHtmlString

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string rawHtml = "<HTML></HTML>";
        ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml);
        return View();
    }
}

In your View you can simply use that dynamic property which you set in your Controller like below

<div>
        @ViewBag.EncodedHtml
</div>

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Change this key in the Info.plist

I changed from

<key>JVMVersion</key>
<string>1.6*</string>

to

<key>JVMVersion</key>
<string>1.8*</string>

and it worked fine now..

Edited:
Per the official statement as mentioned above by hasternet and aried3r, the solution by Antonio Jose is correct.

Thanks!

How do I tell if a regular file does not exist in Bash?

The simplest way

FILE=$1
[ ! -e "${FILE}" ] && echo "does not exist" || echo "exists"

Range of values in C Int and Long 32 - 64 bits

There's no one answer. The standard defines minimum ranges. An int must be able to hold at least 65535. Most modern compilers however allow ints to be 32-bit values. Additionally, there's nothing preventing multiple types from having the same capacity (e.g. int and long).

That being said, the standard does say in your particular case:

0 ? +18446744073709551615

as the range for unsigned long long int.

Further reading: http://en.wikipedia.org/wiki/C_variable_types_and_declarations#Size

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

c# why can't a nullable int be assigned null as a value

Similarly I did for long:

myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;

Upgrading PHP on CentOS 6.5 (Final)

I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:

sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php

It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.

Convert java.util.Date to String

Here are examples of using new Java 8 Time API to format legacy java.util.Date:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).

List of predefined fomatters and pattern notation reference.

Credits:

How to parse/format dates with LocalDateTime? (Java 8)

Java8 java.util.Date conversion to java.time.ZonedDateTime

Format Instant to String

What's the difference between java 8 ZonedDateTime and OffsetDateTime?

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

How do I get currency exchange rates via an API such as Google Finance?

Here are some exchange APIs with PHP example.

[ Open Exchange Rates API ]

Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.

// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
    'app_id' => 'YOUR_APP_ID'
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->rates)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo $response->rates->JPY * 150;
}

150 USD = 18039.09015 JPY

[ Currency Layer API ]

Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.

$exchange_url = 'http://apilayer.net/api/live';
$params = array(
    'access_key' => 'YOUR_ACCESS_KEY',
    'source' => 'USD',
    'currencies' => 'JPY',
    'format' => 1 // 1 = JSON
);

// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
    CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);

if (!empty($response->quotes)) {
    // convert 150 USD to JPY ( Japanese Yen )
    echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}

150 USD = 18036.75045 JPY

How do you run a script on login in *nix?

At login, most shells execute a login script, which you can use to execute your custom script. The login script the shell executes depends, of course, upon the shell:

  • bash: .bash_profile, .bash_login, .profile (for backwards compabitibility)
  • sh: .profile
  • tcsh and csh: .login
  • zsh: .zshrc

You can probably find out what shell you're using by doing

echo $SHELL

from the prompt.

For a slightly wider definition of 'login', it's useful to know that on most distros when X is launched, your .xsessionrc will be executed when your X session is started.

How to compare strings

You need to use strcmp.

if (strcmp(string,"add") == 0){
    print("success!");
}

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Try adding below code in build.gradle, it worked for me -

compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    multiDexEnabled true
}

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).

How to print variables without spaces between values

It's the comma which is providing that extra white space.

One way is to use the string % method:

print 'Value is "%d"' % (value)

which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

print '%s is %3d.%d' % ('pi', 3, 14159)

For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

>>> print(1,2,3,4,5)
1 2 3 4 5

>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<

>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<

Is there any kind of hash code function in JavaScript?

I will try to go a little deeper than other answers.

Even if JS had better hashing support it would not magically hash everything perfectly, in many cases you will have to define your own hash function. For example Java has good hashing support, but you still have to think and do some work.

One problem is with the term hash/hashcode ... there is cryptographic hashing and non-cryptographic hashing. The other problem, is you have to understand why hashing is useful and how it works.

When we talk about hashing in JavaScript or Java most of the time we are talking about non-cryptographic hashing, usually about hashing for hashmap/hashtable (unless we are working on authentication or passwords, which you could be doing server-side using NodeJS ...).

It depends on what data you have and what you want to achieve.

Your data has some natural "simple" uniqueness:

  • The hash of an integer is ... the integer, as it is unique, lucky you !
  • The hash of a string ... it depends on the string, if the string represents a unique identifier, you may consider it as a hash (so no hashing needed).
  • Anything which is indirectly pretty much a unique integer is the simplest case
  • This will respect: hashcode equal if objects are equal

Your data has some natural "composite" uniqueness:

  • For example with a person object, you may compute a hash using firstname, lastname, birthdate, ... see how Java does it: Good Hash Function for Strings, or use some other ID info that is cheap and unique enough for your usecase

You have no idea what your data will be:

  • Good luck ... you could serialize to string and hash it Java style, but that may be expensive if the string is large and it will not avoid collisions as well as say the hash of an integer (self).

There is no magically efficient hashing technique for unknown data, in some cases it is quite easy, in other cases you may have to think twice. So even if JavaScript/ECMAScript adds more support, there is no magic language solution for this problem.

In practice you need two things: enough uniqueness, enough speed

In addition to that it is great to have: "hashcode equal if objects are equal"

Display an image with Python

Your code:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

What it should be:

plt.imshow(mpimg.imread('MyImage.png'))
File_name = mpimg.imread('FilePath')
plt.imshow(FileName)
plt.show()

you're missing a plt.show() unless you're in Jupyter notebook, other IDE's do not automatically display plots so you have to use plt.show() each time you want to display a plot or made a change to an existing plot in follow up code.

Read all worksheets in an Excel workbook into an R list with data.frames

I stumbled across this old question and I think the easiest approach is still missing.

You can use rio to import all excel sheets with just one line of code.

library(rio)
data_list <- import_list("test.xls")

If you're a fan of the tidyverse, you can easily import them as tibbles by adding the setclass argument to the function call.

data_list <- import_list("test.xls", setclass = "tbl")

Suppose they have the same format, you could easily row bind them by setting the rbind argument to TRUE.

data_list <- import_list("test.xls", setclass = "tbl", rbind = TRUE)

How do I declare a global variable in VBA?

Create a public integer in the General Declaration.

Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).

Public Numerator As Integer

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String

saveFolder = "c:\temp\"

     For Each objAtt In itm.Attachments
            FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
                      objAtt.SaveAsFile saveFolder & "\" & FileName
                      Numerator = Numerator + 1

          Set objAtt = Nothing
     Next
End Sub

Regex: match word that ends with "Id"

How about \A[a-z]*Id\z? [This makes characters before Id optional. Use \A[a-z]+Id\z if there needs to be one or more characters preceding Id.]

Bind TextBox on Enter-key press

This is not an answer to the original question, but rather an extension of the accepted answer by @Samuel Jack. I did the following in my own application, and was in awe of the elegance of Samuel's solution. It is very clean, and very reusable, as it can be used on any control, not just the TextBox. I thought this should be shared with the community.

If you have a Window with a thousand TextBoxes that all require to update the Binding Source on Enter, you can attach this behaviour to all of them by including the XAML below into your Window Resources rather than attaching it to each TextBox. First you must implement the attached behaviour as per Samuel's post, of course.

<Window.Resources>
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Setters>
            <Setter Property="b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed" Value="TextBox.Text"/>
        </Style.Setters>
    </Style>
</Window.Resources>

You can always limit the scope, if needed, by putting the Style into the Resources of one of the Window's child elements (i.e. a Grid) that contains the target TextBoxes.

How to use PHP OPCache?

Installation

OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.

Add the following line to your php.ini:

zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)

Note that when the path contains spaces you should wrap it in quotes:

zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"

Also note that you will have to use the zend_extension directive instead of the "normal" extension directive because it affects the actual Zend engine (i.e. the thing that runs PHP).

Usage

Currently there are four functions which you can use:

opcache_get_configuration():

Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.

var_dump(opcache_get_configuration());

opcache_get_status():

This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.

var_dump(opcache_get_status());

opcache_reset():

Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.

opcache_reset();

opcache_invalidate():

Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.

opcache_invalidate('/path/to/script/to/invalidate.php', true);

Maintenance and reports

There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.

OpCacheGUI

Disclaimer I am the author of this project

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Multilingual
  • Mobile device support
  • Shiny graphs

Screenshots:

status

cached-scripts

graphs

mobilr

URL: https://github.com/PeeHaa/OpCacheGUI

opcache-status

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • Cached scripts overview
  • Single file

Screenshot:

status

URL: https://github.com/rlerdorf/opcache-status

opcache-gui

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Automatic refresh

Screenshot:

opcache-gui-overview

URL: https://github.com/amnuts/opcache-gui

Adding author name in Eclipse automatically to existing files

To old files I don't know how to do it... I think you will need a script to go thru all files and add the header.

To change the new ones you can do this.

Go to Eclipse menu bar

  1. Window menu.
  2. Preferences
  3. search for Templates
  4. go to Code templates
  5. click on +code
  6. Click on New Java files
  7. Click Edit
  8. add

/**
${user}
*/

And it's done every new File will have your name on it !

What is the difference between a function expression vs declaration in JavaScript?

The first statement depends on the context in which it is declared.

If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.

If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"

EDIT:

I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.

END EDIT

Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore

var foo = function foo() { return 5; }

Is the same as

var foo = function fooYou() { return 5; }

What does the construct x = x || y mean?

If title is not set, use 'ERROR' as default value.

More generic:

var foobar = foo || default;

Reads: Set foobar to foo or default. You could even chain this up many times:

var foobar = foo || bar || something || 42;

How to store Configuration file and read it using React

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

For React:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

Not sure if it covers your use case but it's been working pretty well for us.

Java: Finding the highest value in an array

If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.

A simple way to find the maximum value from the array with the use of Collections:

Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
System.out.println("The highest maximum for the December is: " + Collections.max(a));

If you are interested in finding the minimum value, similar to finding maximum:

System.out.println(Collections.min(a));

The simplest line to sort the list:

Collections.sort(a);

Or alternatively the use of the Arrays class to sort an array:

Arrays.sort(decMax);

However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

Underline text in UIlabel

This is what i did. It works like butter.

1) Add CoreText.framework to your Frameworks.

2) import <CoreText/CoreText.h> in the class where you need underlined label.

3) Write the following code.

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"My Messages"];
    [attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
              value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
              range:(NSRange){0,[attString length]}];
    self.myMsgLBL.attributedText = attString;
    self.myMsgLBL.textColor = [UIColor whiteColor];

Generate random number between two numbers in JavaScript

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

How to ignore HTML element from tabindex?

The way to do this is by adding tabindex="-1". By adding this to a specific element, it becomes unreachable by the keyboard navigation. There is a great article here that will help you further understand tabindex.

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

What does "use strict" do in JavaScript, and what is the reasoning behind it?

"use strict" makes JavaScript code to run in strict mode, which basically means everything needs to be defined before use. The main reason for using strict mode is to avoid accidental global uses of undefined methods.

Also in strict mode, things run faster, some warnings or silent warnings throw fatal errors, it's better to always use it to make a neater code.

"use strict" is widely needed to be used in ECMA5, in ECMA6 it's part of JavaScript by default, so it doesn't need to be added if you're using ES6.

Look at these statements and examples from MDN:

The "use strict" Directive
The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5). It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.

Examples of using "use strict":
Strict mode for functions: Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

1) strict mode in functions

 function strict() {
     // Function-level strict mode syntax
     'use strict';
     function nested() { return 'And so am I!'; }
     return "Hi!  I'm a strict mode function!  " + nested();
 }
 function notStrict() { return "I'm not strict."; }

 console.log(strict(), notStrict());

2) whole-script strict mode

'use strict';
var v = "Hi! I'm a strict mode script!";
console.log(v);

3) Assignment to a non-writable global

'use strict';

// Assignment to a non-writable global
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError

// Assignment to a non-writable property
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
obj1.x = 9; // throws a TypeError

// Assignment to a getter-only property
var obj2 = { get x() { return 17; } };
obj2.x = 5; // throws a TypeError

// Assignment to a new property on a non-extensible object.
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = 'ohai'; // throws a TypeError

You can read more on MDN.

SQL: IF clause within WHERE clause

In sql server I had same problem I wanted to use an and statement only if parameter is false and on true I had to show both values true and false so I used it this way

(T.IsPublic = @ShowPublic or  @ShowPublic = 1)

Why is 22 the default port number for SFTP?

It's the default SSH port and SFTP is usually carried over an SSH tunnel.

iOS 7 - Status bar overlaps the view

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(void)viewWillLayoutSubviews{

 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) 
  {
    self.view.clipsToBounds = YES;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenHeight = 0.0;
    if(UIDeviceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]))
        screenHeight = screenRect.size.height;
    else
        screenHeight = screenRect.size.width;
    CGRect screenFrame = CGRectMake(0, 20, self.view.frame.size.width,screenHeight-20);
    CGRect viewFrame1 = [self.view convertRect:self.view.frame toView:nil];
    if (!CGRectEqualToRect(screenFrame, viewFrame1))
    {
        self.view.frame = screenFrame;
        self.view.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
  }
}

Add Key in plist--- View controller-based status bar appearance : NO

Spark Dataframe distinguish columns with duplicated name

You can use def drop(col: Column) method to drop the duplicated column,for example:

DataFrame:df1

+-------+-----+
| a     | f   |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+

DataFrame:df2

+-------+-----+
| a     | f   |
+-------+-----+
|107831 | ... |
|107831 | ... |
+-------+-----+

when I join df1 with df2, the DataFrame will be like below:

val newDf = df1.join(df2,df1("a")===df2("a"))

DataFrame:newDf

+-------+-----+-------+-----+
| a     | f   | a     | f   |
+-------+-----+-------+-----+
|107831 | ... |107831 | ... |
|107831 | ... |107831 | ... |
+-------+-----+-------+-----+

Now, we can use def drop(col: Column) method to drop the duplicated column 'a' or 'f', just like as follows:

val newDfWithoutDuplicate = df1.join(df2,df1("a")===df2("a")).drop(df2("a")).drop(df2("f"))

Centering the image in Bootstrap

Use This as the solution

This worked for me perfectly..

<div align="center">
   <img src="">
</div>

Using sed and grep/egrep to search and replace

Honestly, much as I love sed for appropriate tasks, this is definitely a task for perl -- it's truly more powerful for this kind of one-liners, especially to "write it back to where it comes from" (perl's -i switch does it for you, and optionally also lets you keep the old version around e.g. with a .bak appended, just use -i.bak instead).

perl -i.bak -pe 's/\.jpg|\.png|\.gif/.jpg/

rather than intricate work in sed (if even possible there) or awk...

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

List of Java processes

ps aux | grep java

or

$ ps -fea|grep -i java

How to download a file with Node.js (without using third-party libraries)?

Hi,I think you can use child_process module and curl command.

const cp = require('child_process');

let download = async function(uri, filename){
    let command = `curl -o ${filename}  '${uri}'`;
    let result = cp.execSync(command);
};


async function test() {
    await download('http://zhangwenning.top/20181221001417.png', './20181221001417.png')
}

test()

In addition,when you want download large?multiple files,you can use cluster module to use more cpu cores.

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

What is the PostgreSQL equivalent for ISNULL()

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, this js reproduces the same problem that happens with Paola

My solution:

$(document.body).tooltip({selector: '[title]'})
.on('click mouseenter mouseleave','[title]', function(ev) {
    $(this).tooltip('mouseenter' === ev.type? 'show': 'hide');
});

Dropdown using javascript onchange

Something like this should do the trick

<select id="leave" onchange="leaveChange()">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

<div id="message"></div>

Javascript

function leaveChange() {
    if (document.getElementById("leave").value != "100"){
        document.getElementById("message").innerHTML = "Common message";
    }     
    else{
        document.getElementById("message").innerHTML = "Having a Baby!!";
    }        
}

jsFiddle Demo

A shorter version and more general could be

HTML

<select id="leave" onchange="leaveChange(this)">
  <option value="5">Get Married</option>
  <option value="100">Have a Baby</option>
  <option value="90">Adopt a Child</option>
  <option value="15">Retire</option>
  <option value="15">Military Leave</option>
  <option value="15">Medical Leave</option>
</select>

Javascript

function leaveChange(control) {
    var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
    document.getElementById("message").innerHTML = msg;
}

how to concatenate two dictionaries to create a new one in Python?

  1. Slowest and doesn't work in Python3: concatenate the items and call dict on the resulting list:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1.items() + d2.items() + d3.items())'
    
    100000 loops, best of 3: 4.93 usec per loop
    
  2. Fastest: exploit the dict constructor to the hilt, then one update:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1, **d2); d4.update(d3)'
    
    1000000 loops, best of 3: 1.88 usec per loop
    
  3. Middling: a loop of update calls on an initially-empty dict:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.67 usec per loop
    
  4. Or, equivalently, one copy-ctor and two updates:

    $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
    'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
    
    100000 loops, best of 3: 2.65 usec per loop
    

I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];