Programs & Examples On #Instruments

Instruments usually refers to the performance analysis developer tool provided by Apple for Mac and iOS development.

Error Running React Native App From Terminal (iOS)

For any such problem:

  1. Go to .expo folder
  2. Find apk-cache
  3. Remove that folder

and you are done..

Hope it helps?

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

How do you load custom UITableViewCells from Xib files?

I've decided to post since I don't like any of these answers -- things can always be more simple and this is by far the most concise way I've found.

1. Build your Xib in Interface Builder as you like it

  • Set File's Owner to class NSObject
  • Add a UITableViewCell and set its class to MyTableViewCellSubclass -- if your IB crashes (happens in Xcode > 4 as of this writing), just use a UIView of do the interface in Xcode 4 if you still have it laying around
  • Layout your subviews inside this cell and attach your IBOutlet connections to your @interface in the .h or .m (.m is my preference)

2. In your UIViewController or UITableViewController subclass

@implementation ViewController

static NSString *cellIdentifier = @"MyCellIdentier";

- (void) viewDidLoad {

    ...
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCellSubclass" bundle:nil] forCellReuseIdentifier:cellIdentifier];
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCellSubclass *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    ...

    return cell;
}

3. In your MyTableViewCellSubclass

- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        ...
    }

    return self;
}

How do you find out which version of GTK+ is installed on Ubuntu?

get GTK3 version:

dpkg -s libgtk-3-0|grep '^Version'

or just version number

dpkg -s libgtk-3-0|grep '^Version' | cut -d' ' -f2-

Java: Get last element after split

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

Can Mockito stub a method without regard to the argument?

when(
  fooDao.getBar(
    any(Bazoo.class)
  )
).thenReturn(myFoo);

or (to avoid nulls):

when(
  fooDao.getBar(
    (Bazoo)notNull()
  )
).thenReturn(myFoo);

Don't forget to import matchers (many others are available):

For Mockito 2.1.0 and newer:

import static org.mockito.ArgumentMatchers.*;

For older versions:

import static org.mockito.Matchers.*;

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

select dept names who have more than 2 employees whose salary is greater than 1000

select D.DeptName from [Department] D where D.DeptID in 
( 
    select E.DeptId from [Employee] E
    where E.Salary > 1000
    group by E.DeptId
    having count(*) > 2
)

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

Is there a concise way to iterate over a stream with indices in Java 8?

I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:

public class WithIndex<T> {
    private int index;
    private T value;

    WithIndex(int index, T value) {
        this.index = index;
        this.value = value;
    }

    public int index() {
        return index;
    }

    public T value() {
        return value;
    }

    @Override
    public String toString() {
        return value + "(" + index + ")";
    }

    public static <T> Function<T, WithIndex<T>> indexed() {
        return new Function<T, WithIndex<T>>() {
            int index = 0;
            @Override
            public WithIndex<T> apply(T t) {
                return new WithIndex<>(index++, t);
            }
        };
    }
}

Usage:

public static void main(String[] args) {
    Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
    stream.map(WithIndex.indexed()).forEachOrdered(e -> {
        System.out.println(e.index() + " -> " + e.value());
    });
}

I want to remove double quotes from a String

Please try following regex for remove double quotes from string .

    $string = "I am here";
    $string =~ tr/"//d;
    print $string;
    exit();

Creating multiple log files of different content with log4j

I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.

My solution was to configure the 3 appenders, and then setup the logging like this:

log4j.threshold=ALL
log4j.rootLogger=,LowLogger

log4j.logger.HighLevel=ALL,Syslog,HighLogger
log4j.additivity.HighLevel=false

The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.

Hope this helps someone at some point!

Reportviewer tool missing in visual studio 2017 RC

Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:

  1. If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:

    • Microsoft.DataTools.ReportingServices.vsix, and
    • Microsoft.RdlcDesigner.vsix
  2. Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:

    • Microsoft.ReportViewer.Common.dll
    • Microsoft.ReportViewer.DataVisualization.dll
    • Microsoft.ReportViewer.Design.dll
    • Microsoft.ReportViewer.ProcessingObjectModel.dll
    • Microsoft.ReportViewer.WinForms.dll
  3. Install the 2 components from 1 above

  4. Add the dlls from 2 above as references (Project>References>Add...)
  5. (Optional) Add Reporting tab to the toolbar
  6. Add Items to Reporting tab
  7. Browse to the bin folder or where you have the above dlls and add them

You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project

NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Optional Parameters in Go?

Another possibility would be to use a struct which with a field to indicate whether its valid. The null types from sql such as NullString are convenient. Its nice to not have to define your own type, but in case you need a custom data type you can always follow the same pattern. I think the optional-ness is clear from the function definition and there is minimal extra code or effort.

As an example:

func Foo(bar string, baz sql.NullString){
  if !baz.Valid {
        baz.String = "defaultValue"
  }
  // the rest of the implementation
}

Logical operators for boolean indexing in Pandas

Logical operators for boolean indexing in Pandas

It's important to realize that you cannot use any of the Python logical operators (and, or or not) on pandas.Series or pandas.DataFrames (similarly you cannot use them on numpy.arrays with more than one element). The reason why you cannot use those is because they implicitly call bool on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.

NumPys logical functions

However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array, pandas.Series, pandas.DataFrame, or any other (conforming) numpy.array subclass:

So, essentially, one should use (assuming df1 and df2 are pandas DataFrames):

np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)

Bitwise functions and bitwise operators for booleans

However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):

Typically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:

(df1 < 10) | (df2 > 10)  # instead of the wrong df1 < 10 | df2 > 10

This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10 (where a and b are for example simple integers) and don't need the parenthesis.

Differences between logical and bitwise operations (on non-booleans)

It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:

>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])

>>> np.logical_and(a1, a2)
array([False, False, False,  True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)

And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:

>>> a3 = np.array([1, 2, 3, 4])

>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])

Summary table

Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
       and       |  np.logical_and        | np.bitwise_and         |        &
-------------------------------------------------------------------------------------
       or        |  np.logical_or         | np.bitwise_or          |        |
-------------------------------------------------------------------------------------
                 |  np.logical_xor        | np.bitwise_xor         |        ^
-------------------------------------------------------------------------------------
       not       |  np.logical_not        | np.invert              |        ~

Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise. However be careful with the bitwise invert on plain Python bools because the bool will be interpreted as integers in this context (for example ~False returns -1 and ~True returns -2).

Static extension methods

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();

history.replaceState() example?

According to MDN History doc
There is clearly said that second argument is for future used not for now. You are right that second argument is deal with web-page title but currently it's ignored by all major browser.

Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

CSS styling in Django forms

Write your form like:

    class MyForm(forms.Form):
         name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name")
         message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message")

In your HTML field do something like:

{% for field in form %}
      <div class="row">
        <label for="{{ field.name}}">{{ field.label}}</label>{{ field }}
     </div>
{% endfor %}

Then in your CSS write something like:

.name{
      /* you already have this class so create it's style form here */
}
.message{
      /* you already have this class so create it's style form here */
}
label[for='message']{
      /* style for label */
}

Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.

Random numbers with Math.random() in Java

Math.random() generates a number between 0 (inclusive) and 1 (exclusive).

So (int)(Math.random() * max) ranges from 0 to max-1 inclusive.

Then (int)(Math.random() * max) + min ranges from min to max + min - 1, which is not what you want.

Google's formula is correct.

Valid to use <a> (anchor tag) without href attribute?

Yes, it is valid to use the anchor tag without a href attribute.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

Yes, you can use class and other attributes, but you can not use target, download, rel, hreflang, and type.

The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a> without href. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.

Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link).

Source: W3C HTML5 Recommendation

"detached entity passed to persist error" with JPA/EJB code

Here .persist() only will insert the record.If we use .merge() it will check is there any record exist with the current ID, If it exists, it will update otherwise it will insert a new record.

Changing the git user inside Visual Studio Code

You can view all of your settings and where they are coming from using:

git config --list --show-origin

Delete the unwanted credentials from the directory and then VSCode ask you for the next time you perform git operation.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

Android Emulator sdcard push error: Read-only file system

I found this works

$./adb shell
$su
mount -o rw,remount rootfs /
chmod 777 /mnt/sdcard
exit

Source: http://www.coderanch.com/t/611842/Android/Mobile/Android-emulator-sdcard-writable

Hide all warnings in ipython

I eventually figured it out. Place:

import warnings
warnings.filterwarnings('ignore')

inside ~/.ipython/profile_default/startup/disable-warnings.py. I'm leaving this question and answer for the record in case anyone else comes across the same issue.

Quite often it is useful to see a warning once. This can be set by:

warnings.filterwarnings(action='once')

Java - remove last known item from ArrayList

This line means you instantiated a "List of ClientThread Objects".

private List<ClientThread> clients = new ArrayList<ClientThread>();

This line has two problems.

String hey = clients.get(clients.size());

1. This part of the line:

clients.get(clients.size());

ALWAYS throws IndexOutOfBoundsException because a collections size is always one bigger than its last elements index;

2. Compiler complains about incompatible types because you cant assign a ClientThread object to String object. Correct one should be like this.

ClientThread hey = clients.get(clients.size()-1);

Last but not least. If you know index of the object to remove just write

 clients.remove(23); //Lets say it is in 23. index

Don't write

   ClientThread hey = clients.get(23); 

   clients.remove(hey);

because you are forcing the list to search for the index that you already know. If you plan to do something with the removed object later. Write

   ClientThread hey = clients.remove(23); 

This way you can remove the object and get a reference to it at the same line.

Bonus: Never ever call your instance variable with name "hey". Find something meaningful.

And Here is your corrected and ready-to-run code:

public class ListExampleForDan {

    private List<ClientThread> clients = new ArrayList<ClientThread>();

    public static void main(String args[]) {

        clients.add(new ClientThread("First and Last Client Thread"));

        boolean success = removeLastElement(clients);

        if (success) {

            System.out.println("Last Element Removed.");

        } else {

            System.out.println("List Is Null/Empty, Operation Failed.");

        }

    }

    public static boolean removeLastElement(List clients) {

        if (clients == null || clients.isEmpty()) {

            return false;

        } else {

            clients.remove(clients.size() - 1);

            return true;

        }

    }
}

Enjoy!

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

Summary

To fix this issue encountered while running local app vs remote database, use SQL Server Configuration Manager to add an alias for the remote database.

Details

I had run into this problem recently when transitioning from a Windows 7 to a Windows 10 laptop. I was running a local development and runtime environment accessing our Dev database on a remote server. We access the Dev database through a server alias setup through SQL Server Client Network Utility (cliconfg.exe). After confirming that the alias was correctly setup in both the 64 and 32 bit versions of the utility and that the database server was accessible from the new laptop via SSMS, I still got the error seen by the OP (not the OP's IP address, of course).

It was necessary to use SQL Server Configuration Manager to add an alias for the remote Dev database server. Fixed things right up.

enter image description here

Send cookies with curl

.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE

The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:

  • domain - The domain that created AND that can read the variable.
  • flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
  • path - The path within the domain that the variable is valid for.
  • secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
  • expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
  • name - The name of the variable.
  • value - The value of the variable.

From http://www.cookiecentral.com/faq/#3.5

How to Handle Button Click Events in jQuery?

Try This:

_x000D_
_x000D_
$(document).on('click', '#btnClick', function(){ _x000D_
    alert("button is clicked");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
 <button id="btnClick">Click me</button> 
_x000D_
_x000D_
_x000D_

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

How can I see the raw SQL queries Django is running?

The following returns the query as valid SQL, based on https://code.djangoproject.com/ticket/17741:

def str_query(qs):
    """
    qs.query returns something that isn't valid SQL, this returns the actual
    valid SQL that's executed: https://code.djangoproject.com/ticket/17741
    """
    cursor = connections[qs.db].cursor()
    query, params = qs.query.sql_with_params()
    cursor.execute('EXPLAIN ' + query, params)
    res = str(cursor.db.ops.last_executed_query(cursor, query, params))
    assert res.startswith('EXPLAIN ')
    return res[len('EXPLAIN '):]

How to install PHP intl extension in Ubuntu 14.04

May be universe repository is disabled, here is your package in it

Enable it

sudo add-apt-repository universe

Update

sudo apt-get update

And install

sudo apt-get install php5-intl

How to get the month name in C#?

    private string MonthName(int m)
    {
        string res;
        switch (m)
        {
            case 1:
                res="Ene";
                break;
            case 2:
                res = "Feb";
                break;
            case 3:
                res = "Mar";
                break;
            case 4:
                res = "Abr";
                break;
            case 5:
                res = "May";
                break;
            case 6:
                res = "Jun";
                break;
            case 7:
                res = "Jul";
                break;
            case 8:
                res = "Ago";
                break;
            case 9:
                res = "Sep";
                break;
            case 10:
                res = "Oct";
                break;
            case 11:
                res = "Nov";
                break;
            case 12:
                res = "Dic";
                break;
            default:
                res = "Nulo";
                break;
        }
        return res;
    }

Call int() function on every list element?

Thought I'd consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.

How to remove files from git staging area?

Use

git reset

to unstage all the staged files.

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

No module named Image

Problem:

~$ simple-image-reducer

Traceback (most recent call last):

  File "/usr/bin/simple-image-reducer", line 28, in <module>
    import Image

**ImportError: No module named Image**

Reason:

Image != image

Solution:

1) make sure it is available

python -m pip install  Image

2) where is it available?

sudo find ~ -name image -type d

-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image ->> OK

3) make simple-image-reducer understand via link:

ln -s ~/.local/lib/python2.7/site-packages/image
~/.local/lib/python2.7/site-packages/Image

4) invoke simple-image-reducer again. Works:-)

Route.get() requires callback functions but got a "object Undefined"

I had the same error. The problem was in the export and import of the modules.

Example of my solution:

Controller (File: posts.js)

exports.getPosts = (req, res) => {
    res.json({
        posts: [
            { tittle: 'First posts' },
            { tittle: 'Second posts' },
        ]
    });
};

Router (File: posts.js)

const express = require('express');
const { getPosts } = require('../controllers/posts');

const routerPosts = express.Router();
routerPosts.get('/', getPosts);

exports.routerPosts = routerPosts;

Main (File: app.js)

const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { routerPosts } = require('./routes/posts');

const app = express();
const port = process.env.PORT || 3000;

dotenv.config();

// Middleware
app.use(morgan('dev'));

app.use('/', routerPosts);

app.listen(port, () => {
    console.log(`A NodeJS API is listining on port: ${port}`);
});

Running the application (chrome output)

// 20200409002022
// http://localhost:3000/

{
  "posts": [
    {
      "tittle": "First posts"
    },
    {
      "tittle": "Second posts"
    }
  ]
}

Console Log

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev

> [email protected] dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js

[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 304 5.093 ms - -
GET / 304 0.714 ms - -
GET / 304 0.653 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 200 4.427 ms - 62
GET / 304 0.783 ms - -
GET / 304 0.642 ms - -

Node Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ node -v
v13.12.0

NPM Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ npm -v
6.14.4

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

Invoking JavaScript code in an iframe from the parent page

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();

FileNotFoundError: [Errno 2] No such file or directory

with open(fpath, 'rb') as myfile:
    fstr = myfile.read()

I encounter this error because the file is empty. This answer may not a correct answer for this question but should give developers a hint like me.

Initializing multiple variables to the same value in Java

No, it's not possible in java.

You can do this way .. But try to avoid it.

String one, two, three;
one = two = three = "";

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

I think the simplest solution, rather than making the body element partially transparent, would be to add an extra div to hold the background, and change the opacity there, instead.

So you would add a div like:

<div id="background"></div>

And move your body element's background CSS to it, as well as some additional positioning properties, like this:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('images/background.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    opacity: 0.8;
    filter:alpha(opacity=80);
}

Here's an example: http://jsfiddle.net/nbVg4/4/

UITableView - scroll to the top

DONT USE

 tableView.setContentOffset(.zero, animated: true)

It can sometimes set the offset improperly. For example, in my case, the cell was actually slightly above the view with safe area insets. Not good.

INSTEAD USE

 tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)

How to keep onItemSelected from firing off on a newly instantiated Spinner?

The solution with a boolean flag or a counter didn't help me, 'cause during orientation change onItemSelected() calls "overflew" the flag or the counter.

I subclassed android.widget.Spinner and made tiny additions. The relevant parts are below. This solution worked for me.

private void setHandleOnItemSelected()
{
  final StackTraceElement [] elements = Thread.currentThread().getStackTrace();

  for (int index = 1; index < elements.length; index++)
  {
     handleOnItemSelected = elements[index].toString().indexOf("PerformClick") != -1; //$NON-NLS-1$

     if (handleOnItemSelected)
     {
        break;
     }
  }
}

@Override
public void setSelection(int position, boolean animate)
{
  super.setSelection(position, animate);

  setHandleOnItemSelected();
}

@Override
public void setSelection(int position)
{
  super.setSelection(position);

  setHandleOnItemSelected();
}

public boolean shouldHandleOnItemSelected()
{
  return handleOnItemSelected;
}

get current date from [NSDate date] but set the time to 10:00 am

As with all date manipulation you have to use NSDateComponents and NSCalendar

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:10];
NSDate *today10am = [calendar dateFromComponents:components];

in iOS8 Apple introduced a convenience method that saves a few lines of code:

NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];

Swift:

let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()

let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!

How to find current transaction level?

If you are talking about the current transaction nesting level, then you would use @@TRANCOUNT.

If you are talking about transaction isolation level, use DBCC USEROPTIONS and look for an option of isolation level. If it isn't set, it's read committed.

What's the effect of adding 'return false' to a click event listener?

Here's a more robust routine to cancel default behavior and event bubbling in all browsers:

// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
    if (!e)
        if (window.event) e = window.event;
        else return;
    if (e.cancelBubble != null) e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    if (e.preventDefault) e.preventDefault();
    if (window.event) e.returnValue = false;
    if (e.cancel != null) e.cancel = true;
}

An example of how this would be used in an event handler:

// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context) 
{
    // Find the tabStrip element (we know it's the parent element of this link)
    var tabstripElement = this.parentNode;
    Tabstrip.showTabByLink(tabstripElement, this);
    return eventCancel(evt);
}

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

Read input from console in Ruby?

you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number

#!/usr/bin/ruby

first_number = ARGV[0].to_i
second_number = ARGV[1].to_i

puts first_number + second_number

and you call it like this

% ./plus.rb 5 6
==> 11

How to output a multiline string in Bash?

Use the -e argument and the escape character \n:

echo -e "This will generate a next line \nThis new line is the result"

Iterate through Nested JavaScript Objects

You can create a recursive function like this to do a depth-first traversal of the cars object.

var findObjectByLabel = function(obj, label) {
    if(obj.label === label) { return obj; }
    for(var i in obj) {
        if(obj.hasOwnProperty(i)){
            var foundLabel = findObjectByLabel(obj[i], label);
            if(foundLabel) { return foundLabel; }
        }
    }
    return null;
};

which can be called like so

findObjectByLabel(car, "Chevrolet");

Psql list all tables

To see the public tables you can do

list tables

\dt

list table, view, and access privileges

\dp or \z

or just the table names

select table_name from information_schema.tables where table_schema = 'public';

How do I upload a file to an SFTP server in C# (.NET)?

Maybe you can script/control winscp?

Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

How to set recurring schedule for xlsm file using Windows Task Scheduler

Code below copied from -> Here

First off, you must save your work book as a macro enabled work book. So it would need to be xlsm not an xlsx. Otherwise, excel will disable the macro's due to not being macro enabled.

Set your vbscript (C:\excel\tester.vbs). The example sub "test()" must be located in your modules on the excel document.

dim eApp
set eApp = GetObject("C:\excel\tester.xlsm")
eApp.Application.Run "tester.xlsm!test"
set eApp = nothing

Then set your Schedule, give it a name, and a username/password for offline access.

Then you have to set your actions and triggers.

Set your schedule(trigger)

Set your trigger

Action, set your vbscript to open with Cscript.exe so that it will be executed in the background and not get hung up by any error handling that vbcript has enabled.

Action Properties

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

Access Control Origin Header error using Axios in React Web throwing error in Chrome

Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...

To make it work you should probably add this header to your response.You can also try to add the header crossorigin:true to your request.

calling javascript function on OnClientClick event of a Submit button

OnClientClick="SomeMethod()" event of that BUTTON, it return by default "true" so after that function it do postback

for solution use

//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"

//and your function like this
<script type="text/javascript">
  function SomeMethod(){
    // put your code here 
    return false;
  }
</script>

C# static class constructor

A static constructor looks like this

static class Foo
{
    static Foo()
    {
         // Static initialization code here
    }
}

It is executed only once when the type is first used. All classes can have static constructors, not just static classes.

Use CASE statement to check if column exists in table - SQL Server

Try this one -

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

Find the paths between two given nodes?

Dijkstra's algorithm applies more to weighted paths and it sounds like the poster was wanting to find all paths, not just the shortest.

For this application, I'd build a graph (your application sounds like it wouldn't need to be directed) and use your favorite search method. It sounds like you want all paths, not just a guess at the shortest one, so use a simple recursive algorithm of your choice.

The only problem with this is if the graph can be cyclic.

With the connections:

  • 1, 2
  • 1, 3
  • 2, 3
  • 2, 4

While looking for a path from 1->4, you could have a cycle of 1 -> 2 -> 3 -> 1.

In that case, then I'd keep a stack as traversing the nodes. Here's a list with the steps for that graph and the resulting stack (sorry for the formatting - no table option):

current node (possible next nodes minus where we came from) [stack]

  1. 1 (2, 3) [1]
  2. 2 (3, 4) [1, 2]
  3. 3 (1) [1, 2, 3]
  4. 1 (2, 3) [1, 2, 3, 1] //error - duplicate number on the stack - cycle detected
  5. 3 () [1, 2, 3] // back-stepped to node three and popped 1 off the stack. No more nodes to explore from here
  6. 2 (4) [1, 2] // back-stepped to node 2 and popped 1 off the stack.
  7. 4 () [1, 2, 4] // Target node found - record stack for a path. No more nodes to explore from here
  8. 2 () [1, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes to explore from here
  9. 1 (3) [1] //back-stepped to node 1 and popped 2 off the stack.
  10. 3 (2) [1, 3]
  11. 2 (1, 4) [1, 3, 2]
  12. 1 (2, 3) [1, 3, 2, 1] //error - duplicate number on the stack - cycle detected
  13. 2 (4) [1, 3, 2] //back-stepped to node 2 and popped 1 off the stack
  14. 4 () [1, 3, 2, 4] Target node found - record stack for a path. No more nodes to explore from here
  15. 2 () [1, 3, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes
  16. 3 () [1, 3] // back-stepped to node 3 and popped 2 off the stack. No more nodes
  17. 1 () [1] // back-stepped to node 1 and popped 3 off the stack. No more nodes
  18. Done with 2 recorded paths of [1, 2, 4] and [1, 3, 2, 4]

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

In my case, the error occurred because I had not initialized the select list in the controller like this:

viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();

As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

Had the same error when I had @Order annotation on a filter class. Even thou I added the filter through the HttpSecurity chain.

Removed the @Order and it worked.

PHP - warning - Undefined property: stdClass - fix?

If think this will work:

if(sizeof($response->records)>0)
$role_arr = getRole($response->records);

newly defined proprties included too.

html "data-" attribute as javascript parameter

HTML:

<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">

JavaScript:

function fun(obj) {
    var uid= $(obj).attr('data-uid');
    var name= $(obj).attr('data-name');
    var value= $(obj).attr('data-value');
}

but I'm using jQuery.

Where does Git store files?

It will create your repository in the .git folder in the current directory.

How to simulate "Press any key to continue?"

#include <iostream>
using namespace std;

int main () {
    bool boolean;
    boolean = true;

    if (boolean == true) {

        cout << "press any key to continue";
        cin >> boolean;

    }
    return 0;
}

How can I determine whether a specific file is open in Windows?

Try Unlocker.

The Unlocker site has a nifty chart (scroll down after following the link) that shows a comparison to other tools. Obviously such comparisons are usually biased since they are typically written by the tool author, but the chart at least lists the alternatives so that you can try them for yourself.

jQuery 'if .change() or .keyup()'

You could subscribe for the change and keyup events:

$(function() {
    $(':input').change(myFunction).keyup(myFunction);
});

where myFunction is the function you would like executed:

function myFunction() {
    alert( 'something happened!' );
}

Define global constants

In Angular 4, you can use environment class to keep all your globals.

You have environment.ts and environment.prod.ts by default.

For example

export const environment = {
  production: false,
  apiUrl: 'http://localhost:8000/api/'
};

And then on your service:

import { environment } from '../../environments/environment';
...
environment.apiUrl;

Current date and time - Default in MVC razor

Isn't this what default constructors are for?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}

Pandas convert dataframe to array of tuples

Motivation
Many data sets are large enough that we need to concern ourselves with speed/efficiency. So I offer this solution in that spirit. It happens to also be succinct.

For the sake of comparison, let's drop the index column

df = data_set.drop('index', 1)

Solution
I'll propose the use of zip and map

list(zip(*map(df.get, df)))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

It happens to also be flexible if we wanted to deal with a specific subset of columns. We'll assume the columns we've already displayed are the subset we want.

list(zip(*map(df.get, ['data_date', 'data_1', 'data_2'])))

[('2012-02-17', 24.75, 25.03),
 ('2012-02-16', 25.0, 25.07),
 ('2012-02-15', 24.99, 25.15),
 ('2012-02-14', 24.68, 25.05),
 ('2012-02-13', 24.62, 24.77),
 ('2012-02-10', 24.38, 24.61)]

What is Quicker?

Turn's out records is quickest followed by asymptotically converging zipmap and iter_tuples

I'll use a library simple_benchmarks that I got from this post

from simple_benchmark import BenchmarkBuilder
b = BenchmarkBuilder()

import pandas as pd
import numpy as np

def tuple_comp(df): return [tuple(x) for x in df.to_numpy()]
def iter_namedtuples(df): return list(df.itertuples(index=False))
def iter_tuples(df): return list(df.itertuples(index=False, name=None))
def records(df): return df.to_records(index=False).tolist()
def zipmap(df): return list(zip(*map(df.get, df)))

funcs = [tuple_comp, iter_namedtuples, iter_tuples, records, zipmap]
for func in funcs:
    b.add_function()(func)

def creator(n):
    return pd.DataFrame({"A": random.randint(n, size=n), "B": random.randint(n, size=n)})

@b.add_arguments('Rows in DataFrame')
def argument_provider():
    for n in (10 ** (np.arange(4, 11) / 2)).astype(int):
        yield n, creator(n)

r = b.run()

Check the results

r.to_pandas_dataframe().pipe(lambda d: d.div(d.min(1), 0))

        tuple_comp  iter_namedtuples  iter_tuples   records    zipmap
100       2.905662          6.626308     3.450741  1.469471  1.000000
316       4.612692          4.814433     2.375874  1.096352  1.000000
1000      6.513121          4.106426     1.958293  1.000000  1.316303
3162      8.446138          4.082161     1.808339  1.000000  1.533605
10000     8.424483          3.621461     1.651831  1.000000  1.558592
31622     7.813803          3.386592     1.586483  1.000000  1.515478
100000    7.050572          3.162426     1.499977  1.000000  1.480131

r.plot()

enter image description here

How can I create a keystore?

To answer the question in the title, you create a keystore with the Java Keytool utility that comes with any standard JDK distribution and can be located at %JAVA_HOME%\bin. On Windows this would usually be C:\Program Files\Java\jre7\bin.

So on Windows, open a command window and switch to that directory and enter a command like this

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Keytool prompts you to provide passwords for the keystore, provide the Distinguished Name fields and then the password for your key. It then generates the keystore as a file called my-release-key.keystore in the directory you're in. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias_name is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation at: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

and for more information on signing Android apps go here: http://developer.android.com/tools/publishing/app-signing.html

How to make android listview scrollable?

By default ListView is scrollable. Do not put ScrollView to the ListView

How to call multiple JavaScript functions in onclick event?

You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.

<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>

or you can put the composition as a seperate function in js file and call it

const newFunction = R.compose(fn1,fn2,fn3);


<a href="#" onclick="newFunction()">Click me To fire some functions</a>

PHP mail not working for some reason

This is probably a configuration error. If you insist on using PHP mail function, you will have to edit php.ini.

If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.

Remove old Fragment from fragment manager

Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

ArrayList<Fragment> fragmentList = fragmentManager.getFragments();

The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);

You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

I usually use this code for working with fragmentManager

public void replaceFragment(Fragment fragment, Bundle bundle) {

    if (bundle != null)
        fragment.setArguments(bundle);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

    //if oldFragment already exits in fragmentManager use it
    if (oldFragment != null) {
        fragment = oldFragment;
    }

    fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

    fragmentTransaction.commit();
}

Why is processing a sorted array faster than processing an unsorted array?

As what has already been mentioned by others, what behind the mystery is Branch Predictor.

I'm not trying to add something but explaining the concept in another way. There is a concise introduction on the wiki which contains text and diagram. I do like the explanation below which uses a diagram to elaborate the Branch Predictor intuitively.

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Two-way branching is usually implemented with a conditional jump instruction. A conditional jump can either be "not taken" and continue execution with the first branch of code which follows immediately after the conditional jump, or it can be "taken" and jump to a different place in program memory where the second branch of code is stored. It is not known for certain whether a conditional jump will be taken or not taken until the condition has been calculated and the conditional jump has passed the execution stage in the instruction pipeline (see fig. 1).

figure 1

Based on the described scenario, I have written an animation demo to show how instructions are executed in a pipeline in different situations.

  1. Without the Branch Predictor.

Without branch prediction, the processor would have to wait until the conditional jump instruction has passed the execute stage before the next instruction can enter the fetch stage in the pipeline.

The example contains three instructions and the first one is a conditional jump instruction. The latter two instructions can go into the pipeline until the conditional jump instruction is executed.

without branch predictor

It will take 9 clock cycles for 3 instructions to be completed.

  1. Use Branch Predictor and don't take a conditional jump. Let's assume that the predict is not taking the conditional jump.

enter image description here

It will take 7 clock cycles for 3 instructions to be completed.

  1. Use Branch Predictor and take a conditional jump. Let's assume that the predict is not taking the conditional jump.

enter image description here

It will take 9 clock cycles for 3 instructions to be completed.

The time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. As a result, making a pipeline longer increases the need for a more advanced branch predictor.

As you can see, it seems we don't have a reason not to use Branch Predictor.

It's quite a simple demo that clarifies the very basic part of Branch Predictor. If those gifs are annoying, please feel free to remove them from the answer and visitors can also get the live demo source code from BranchPredictorDemo

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

That's a half-open interval.

  • A closed interval [a,b] includes the end points.
  • An open interval (a,b) excludes them.

In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".

Half-open intervals are useful in programming because they correspond to the common idiom for looping:

for (int i = 0; i < n; ++i) { ... } 

Here i is in the range [0, n).

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

Jenkins Git Plugin: How to build specific tag?

Can't you tell Jenkins to build from a Ref name? If so then it's

refs/tags/tag-name

From all the questions I see about Jenkins and Hudson, I'd suggest switching to TeamCity. I haven't had to edit any configuration files to get TeamCity to work.

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

How to retrieve an element from a set without removing it?

Two options that don't require copying the whole set:

for e in s:
    break
# e is now an element from s

Or...

e = next(iter(s))

But in general, sets don't support indexing or slicing.

Writing image to local server

I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)

This is for reading images from Azure Cognative Services's Vision API

const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
    'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';

// Request parameters.
const params = {
    'visualFeatures': 'Categories,Description,Adult,Faces',
    'maxCandidates': '2',
    'details': 'Celebrities,Landmarks',
    'language': 'en'
};

const options = {
    uri: uriBase,
    qs: params,
    body: fs.readFileSync(./my_local_image_path.jpg),
    headers: {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, '  ');
body = JSON.parse(body);
if (body.code) // err
{
    console.log("AZURE: " + body.message)
}

console.log('Response\n' + jsonString);

Base64 length calculation?

Integers

Generally we don't want to use doubles because we don't want to use the floating point ops, rounding errors etc. They are just not necessary.

For this it is a good idea to remember how to perform the ceiling division: ceil(x / y) in doubles can be written as (x + y - 1) / y (while avoiding negative numbers, but beware of overflow).

Readable

If you go for readability you can of course also program it like this (example in Java, for C you could use macro's, of course):

public static int ceilDiv(int x, int y) {
    return (x + y - 1) / y;
}

public static int paddedBase64(int n) {
    int blocks = ceilDiv(n, 3);
    return blocks * 4;
}

public static int unpaddedBase64(int n) {
    int bits = 8 * n;
    return ceilDiv(bits, 6);
}

// test only
public static void main(String[] args) {
    for (int n = 0; n < 21; n++) {
        System.out.println("Base 64 padded: " + paddedBase64(n));
        System.out.println("Base 64 unpadded: " + unpaddedBase64(n));
    }
}

Inlined

Padded

We know that we need 4 characters blocks at the time for each 3 bytes (or less). So then the formula becomes (for x = n and y = 3):

blocks = (bytes + 3 - 1) / 3
chars = blocks * 4

or combined:

chars = ((bytes + 3 - 1) / 3) * 4

your compiler will optimize out the 3 - 1, so just leave it like this to maintain readability.

Unpadded

Less common is the unpadded variant, for this we remember that each we need a character for each 6 bits, rounded up:

bits = bytes * 8
chars = (bits + 6 - 1) / 6

or combined:

chars = (bytes * 8 + 6 - 1) / 6

we can however still divide by two (if we want to):

chars = (bytes * 4 + 3 - 1) / 3

Unreadable

In case you don't trust your compiler to do the final optimizations for you (or if you want to confuse your colleagues):

Padded

((n + 2) / 3) << 2

Unpadded

((n << 2) | 2) / 3

So there we are, two logical ways of calculation, and we don't need any branches, bit-ops or modulo ops - unless we really want to.

Notes:

  • Obviously you may need to add 1 to the calculations to include a null termination byte.
  • For Mime you may need to take care of possible line termination characters and such (look for other answers for that).

Disallow Twitter Bootstrap modal window from closing

The best I found is add this code to the link

<!-- Link -->
<a href="#mdl" role="button"  data-backdrop="static" data-keyboard="false" data-toggle="modal" id_team="" ></a>
<-- Div -->
<div id="mdl" class="modal hide fade" tabindex="-1" role="dialog" data-keyboard="false" data-backdrop="static"></div>

Setting initial values on load with Select2 with Ajax

Updated to new version:

Try this solution from here http://jsfiddle.net/EE9RG/430/

$('#sel2').select2({
multiple:true,
ajax:{}}).select2({"data": 
     [{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});

Auto increment in MongoDB to store sequence of Unique User ID

I know this is an old question, but I shall post my answer for posterity...

It depends on the system that you are building and the particular business rules in place.

I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.

The suggestion above worked perfectly for my project.

db.contacts.insert({
 "id":db.contacts.find().Count()+1,
 "name":"John Doe",
 "emails":[
    "[email protected]",
    "[email protected]"
 ],
 "phone":"555111322",
 "status":"Active"
});

The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.

My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.

Therefore, db.collection.find().count() + 1 is a perfect solution for me...

It won't work for everyone, but if you will not be deleting data, it works fine.

Android: How to turn screen on and off programmatically?

This is worked on Marshmallow

private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;

public void turnOnScreen() {
    if (_screenOffWakeLock != null) {
        _screenOffWakeLock.release();
    }
}

public void turnOffScreen() {
    try {
        _powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
        if (_powerManager != null) {
            _screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            if (_screenOffWakeLock != null) {
                _screenOffWakeLock.acquire();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

jQuery dialog popup

You can use the following script. It worked for me

The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.

 $(function () {
        modalPosition();
        $(window).resize(function () {
            modalPosition();
        });
        $('.openModal').click(function (e) {
            $('.modal, .modal-backdrop').fadeIn('fast');
            e.preventDefault();
        });
        $('.close-modal').click(function (e) {
            $('.modal, .modal-backdrop').fadeOut('fast');
        });
    });
    function modalPosition() {
        var width = $('.modal').width();
        var pageWidth = $(window).width();
        var x = (pageWidth / 2) - (width / 2);
        $('.modal').css({ left: x + "px" });
    }

Refer:- Modal popup using jquery in asp.net

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

Can I extend a class using more than 1 class in PHP?

One of the problems of PHP as a programming language is the fact that you can only have single inheritance. This means a class can only inherit from one other class.

However, a lot of the time it would be beneficial to inherit from multiple classes. For example, it might be desirable to inherit methods from a couple of different classes in order to prevent code duplication.

This problem can lead to class that has a long family history of inheritance which often does not make sense.

In PHP 5.4 a new feature of the language was added known as Traits. A Trait is kind of like a Mixin in that it allows you to mix Trait classes into an existing class. This means you can reduce code duplication and get the benefits whilst avoiding the problems of multiple inheritance.

Traits

How to send email to multiple address using System.Net.Mail

StewieFG suggestion is valid but if you want to add the recipient name use this, with what Marco has posted above but is email address first and display name second:

msg.To.Add(new MailAddress("[email protected]","Your name 1"));
msg.To.Add(new MailAddress("[email protected]","Your name 2"));

What is DOM element?

DOM stands for Document Object Model. It is the W3C(World Wide Web Consortium) Standard. It define standard for accessing and manipulating HTML and XML document and The elements of DOM is head,title,body tag etc. So the answer of your first statement is

Statement #1 You can add multiple classes to a single DOM element.

Explanation : "div class="cssclass1 cssclass2 cssclass3"

Here tag is element of DOM and i have applied multiple classes to DOM element.

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

PyCharm shows unresolved references error for valid code

I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project's interpreter. This solved my problem.

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

What is the difference between attribute and property?

Often an attribute is used to describe the mechanism or real-world thing.

A property is used to describe the model.

For instance, a document (sitting on your desk) may have the attribute that it is a draft.

The class that models documents has a property to indicate whether or not it's a draft. In this case the property captures the state.

How to shrink/purge ibdata1 file in MySQL

In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:

  • dump all you databases
  • uninstall mysql-server,
  • add in remained my.cnf:
    [mysqld]
    innodb_file_per_table=1
  • erase all in /var/lib/mysql
  • install mysql-server
  • restore users and databases

Simplest way to detect keypresses in javascript

There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:

function code(e) {
    e = e || window.event;
    return(e.keyCode || e.which);
}
window.onload = function(){
    document.onkeypress = function(e){
        var key = code(e);
        // do something with key
    };
};

Or a more structured way of handling it:

(function(d){
    var modern = (d.addEventListener), event = function(obj, evt, fn){
        if(modern) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, code = function(e){
        e = e || window.event;
        return(e.keyCode || e.which);
    }, init = function(){
        event(d, "keypress", function(e){
            var key = code(e);
            // do stuff with key here
        });
    };
    if(modern) {
        d.addEventListener("DOMContentLoaded", init, false);
    } else {
        d.attachEvent("onreadystatechange", function(){
            if(d.readyState === "complete") {
                init();
            }
        });
    }
})(document);

How to write a file or data to an S3 object using boto3

it is worth mentioning smart-open that uses boto3 as a back-end.

smart-open is a drop-in replacement for python's open that can open files from s3, as well as ftp, http and many other protocols.

for example

from smart_open import open
import json
with open("s3://your_bucket/your_key.json", 'r') as f:
    data = json.load(f)

The aws credentials are loaded via boto3 credentials, usually a file in the ~/.aws/ dir or an environment variable.

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

Replace the single quote (') character from a string

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
    
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")
    

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
    
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")
    

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended - works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)
    x.remove("'")
    ''.join(x)
    

Excel to JSON javascript code?

@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:

npm install xlsx --save

Then in my component code, import with:

import XLSX from 'xlsx'

The component UI should look like this:

<input
  accept=".xlsx"
  type="file"
  onChange={this.fileReader}
/>

It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

momentJS date string add 5 days

You can reduce what they said in a few lines of code:

var nowPlusOneDay = moment().add('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');

alert('nowPlusOneDay Without Format(Unix Date):'+nowPlusOneDay);
alert('nowPlusOneDay Formatted(String):'+nowPlusOneDayStr);

Converting year and month ("yyyy-mm" format) to a date?

Try this. (Here we use text=Lines to keep the example self contained but in reality we would replace it with the file name.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo .

The zoo series, z, that is created above has a "yearmon" time index and looks like this:

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" can be used alone as well:

> as.yearmon("2000-03")
[1] "Mar 2000"

Note:

  1. "yearmon" class objects sort in calendar order.

  2. This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z to "Date" class: time(z) <- as.Date(time(z)) .

How do I reformat HTML code using Sublime Text 2?

you can set shortcut key F12 easy!!!

{ "keys": ["f12"], "command": "reindent" , "args": { "single_line": false } }

see detail here.

Windows service on Local Computer started and then stopped error

Use Timer and tick event to copy your files.

On start the service, start the time and specify the interval in the time.

So the service is keep running and copy the files ontick.

Hope it help.

Python - round up to the nearest ten

This will round down correctly as well:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50

jQuery issue - #<an Object> has no method

I had this problem, or one that looked superficially similar, yesterday. It turned out that I wasn't being careful when mixing jQuery and prototype. I found several solutions at http://docs.jquery.com/Using_jQuery_with_Other_Libraries. I opted for

var $j = jQuery.noConflict();

but there are other reasonable options described there.

Calculate distance between two points in google maps V3

To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:

private void build_retrofit_and_get_response(String type) {

    String url = "https://maps.googleapis.com/maps/";

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitMaps service = retrofit.create(RetrofitMaps.class);

    Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Response<Example> response, Retrofit retrofit) {

            try {
                //Remove previous line from map
                if (line != null) {
                    line.remove();
                }
                // This loop will go through all the results and add marker on each location.
                for (int i = 0; i < response.body().getRoutes().size(); i++) {
                    String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                    String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                    ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                    String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                    List<LatLng> list = decodePoly(encodedString);
                    line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(20)
                                    .color(Color.RED)
                                    .geodesic(true)
                    );
                }
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });

}

Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:

package com.androidtutorialpoint.googlemapsdistancecalculator;


import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;

public interface RetrofitMaps {


/*
 * Retrofit get annotation with our URL
 * And our method that will return us details of student.
 */
@GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);

}

I hope this explains your query. All the best :)

Source: Google Maps Distance Calculator

Eclipse not recognizing JVM 1.8

I have had the same problem as noted above. I could not get Eclipse to install because of Java incompatibilities. The sequence I followed goes like this:

  1. Upgraded to MAC OS Sierra
  2. Downloaded the Eclipse installer but was prompted that I needed to instal a legacy Java.
  3. Installed Java 1.6
  4. Was unable to install Eclipse and was prompted that I needed Java 1.7 or greater. Downloaded and installed Java 1.8
  5. Ran the terminal code 'java -version' // this will check your jre version. This showed returned Java 1.6 despite the fact that I had upgraded to 1.8. The Java version listed in the Java control panel said 1.8
  6. Tried multiple downloads of eclipse and Java and multiple restarts always with the same result.
  7. Visited the Oracle web page noted above: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html I could not find the above reference to 8u73 and 8u74 but I did find and option to download 1.8.0_12. I did this. It installed without difficulty, and then I was able to install Eclipse without difficulty.

This took hours of my time. I hope this proves useful.

Efficient way of having a function only execute once in a loop

If I understand the updated question correctly, something like this should work

def function1():
    print "function1 called"

def function2():
    print "function2 called"

def function3():
    print "function3 called"

called_functions = set()
while True:
    n = raw_input("choose a function: 1,2 or 3 ")
    func = {"1": function1,
            "2": function2,
            "3": function3}.get(n)

    if func in called_functions:
        print "That function has already been called"
    else:
        called_functions.add(func)
        func()

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

How to check if a column exists in a SQL Server table?

I needed similar for SQL SERVER 2000 and, as @Mitch points out, this only works inm 2005+.

Should it help anyone else, this is what worked for me in the end:

if exists (
    select * 
    from 
        sysobjects, syscolumns 
    where 
        sysobjects.id = syscolumns.id 
        and sysobjects.name = 'table' 
        and syscolumns.name = 'column')

Bootstrap combining rows (rowspan)

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Copying from one text file to another using Python

The oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

Recommended with with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

Using less memory:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line) 

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

What do *args and **kwargs mean?

Also, we use them for managing inheritance.

class Super( object ):
   def __init__( self, this, that ):
       self.this = this
       self.that = that

class Sub( Super ):
   def __init__( self, myStuff, *args, **kw ):
       super( Sub, self ).__init__( *args, **kw )
       self.myStuff= myStuff

x= Super( 2.7, 3.1 )
y= Sub( "green", 7, 6 )

This way Sub doesn't really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.

"This operation requires IIS integrated pipeline mode."

The way to fix this issue is not within IIS. I was trying to run my application within IIS Express within Visual Studio. I searched the web and some articles were saying to add an identity tag to the system.web tag. This is not the correct way.

The way I was able to solve this issue was to click on the project file and go to properties. Under managed pipeline, I changed the property value from classic to integrated.

This solved my issue.

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

'Syntax Error: invalid syntax' for no apparent reason

If you are running the program with python, try running it with python3.

AngularJs event to call after content is loaded

var myTestApp = angular.module("myTestApp", []); 
myTestApp.controller("myTestController", function($scope, $window) {
$window.onload = function() {
 alert("is called on page load.");
};
});

How can I make setInterval also work when a tab is inactive in Chrome?

Here's my rough solution

(function(){
var index = 1;
var intervals = {},
    timeouts = {};

function postMessageHandler(e) {
    window.postMessage('', "*");

    var now = new Date().getTime();

    sysFunc._each.call(timeouts, function(ind, obj) {
        var targetTime = obj[1];

        if (now >= targetTime) {
            obj[0]();
            delete timeouts[ind];
        }
    });
    sysFunc._each.call(intervals, function(ind, obj) {
        var startTime = obj[1];
        var func = obj[0];
        var ms = obj[2];

        if (now >= startTime + ms) {
            func();
            obj[1] = new Date().getTime();
        }
    });
}
window.addEventListener("message", postMessageHandler, true);
window.postMessage('', "*");

function _setTimeout(func, ms) {
    timeouts[index] = [func, new Date().getTime() + ms];
    return index++;
}

function _setInterval(func, ms) {
    intervals[index] = [func, new Date().getTime(), ms];
    return index++;
}

function _clearInterval(ind) {
    if (intervals[ind]) {
        delete intervals[ind]
    }
}
function _clearTimeout(ind) {
    if (timeouts[ind]) {
        delete timeouts[ind]
    }
}

var intervalIndex = _setInterval(function() {
    console.log('every 100ms');
}, 100);
_setTimeout(function() {
    console.log('run after 200ms');
}, 200);
_setTimeout(function() {
    console.log('closing the one that\'s 100ms');
    _clearInterval(intervalIndex)
}, 2000);

window._setTimeout = _setTimeout;
window._setInterval = _setInterval;
window._clearTimeout = _clearTimeout;
window._clearInterval = _clearInterval;
})();

How do you open a file in C++?

To open and read a text file line per line, you could use the following:

// define your file name
string file_name = "data.txt";

// attach an input stream to the wanted file
ifstream input_stream(file_name);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// file contents  
vector<string> text;

// one line
string line;

// extract all the text from the input file
while (getline(input_stream, line)) {

    // store each line in the vector
    text.push_back(line);
}

To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function read():

// define your file name
string file_name = "binary_data.bin";

// attach an input stream to the wanted file
ifstream input_stream(file_name, ios::binary);

// check stream status
if (!input_stream) cerr << "Can't open input file!";

// use function that explicitly specifies the amount of block memory read 
int memory_size = 10;

// allocate 10 bytes of memory on heap
char* dynamic_buffer = new char[memory_size];

// read 10 bytes and store in dynamic_buffer
file_name.read(dynamic_buffer, memory_size);

When doing this you'll need to #include the header : <iostream>

UPDATE with CASE and IN - Oracle

"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually

UPDATE tab1   SET budgpost_gr1=     
CASE  WHEN (budgpost in ('1001,1012,50055'))  THEN 'BP_GR_A'   
      WHEN (budgpost in ('5,10,98,0'))  THEN 'BP_GR_B'  
      WHEN (budgpost in ('11,876,7976,67465'))     
      ELSE 'Missing' END`

If so, you need a function to take a string and parse it into a list of numbers.

create type tab_num is table of number;

create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
  v_tab_num tab_num := tab_num();
  v_start   number := 1;
  v_end     number;
  v_delim   VARCHAR2(1) := ',';
  v_cnt     number(1) := 1;
begin
  v_end := instr(i_str||v_delim,v_delim,1, v_start);
  WHILE v_end > 0 LOOP
    v_cnt := v_cnt + 1;
    v_tab_num.extend;
    v_tab_num(v_tab_num.count) := 
                  substr(i_str,v_start,v_end-v_start);
    v_start := v_end + 1;
    v_end := instr(i_str||v_delim,v_delim,v_start);
  END LOOP;
  RETURN v_tab_num;
end;
/

Then you can use the function like so:

select column_id, 
   case when column_id in 
     (select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red' 
   else 'blue' end
from  user_tab_columns
where table_name = 'EMP'

convert base64 to image in javascript/jquery

Have to add this based on @Joseph's answer. If someone want to create image object:

var image = new Image();
image.onload = function(){
   console.log(image.width); // image is loaded and we have image width 
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

Carriage Return\Line feed in Java

The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.

Integrating MySQL with Python in Windows

If you are looking for Python 3.2 this seems the best solution I found so far

Source: http://wiki.python.org/moin/MySQL

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

Virtual Memory Usage from Java under Linux, too much memory used

This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.

java -Xms1024m -Xmx4096m com.example.Hello

Different Ways to Measure Memory

On Linux, the top command gives you several different numbers for memory. Here's what it says about the Hello World example:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2120 kgregory  20   0 4373m  15m 7152 S    0  0.2   0:00.10 java
  • VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
  • RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
  • SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
  • SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, whether or not it's actually in the swap space. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.

The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the official documentation is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually documented. Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.

Understanding the Virtual Memory Map

The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the pmap command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.

0000000040000000     36K r-x--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000      8K rwx--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000    676K rwx--    [ anon ]
00000006fae00000  21248K rwx--    [ anon ]
00000006fc2c0000  62720K rwx--    [ anon ]
0000000700000000 699072K rwx--    [ anon ]
000000072aab0000 2097152K rwx--    [ anon ]
00000007aaab0000 349504K rwx--    [ anon ]
00000007c0000000 1048576K rwx--    [ anon ]
...
00007fa1ed00d000   1652K r-xs-  /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000   1024K rwx--    [ anon ]
00007fa1ed2d3000      4K -----    [ anon ]
00007fa1ed2d4000   1024K rwx--    [ anon ]
00007fa1ed3d4000      4K -----    [ anon ]
...
00007fa1f20d3000    164K r-x--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000   1020K -----  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000     28K rwx--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000   1576K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000   2044K -----  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000     16K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000      4K rwx--  /lib/x86_64-linux-gnu/libc-2.13.so
...

A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via mmap.

Starting from the top, we have

  • The JVM loader (ie, the program that gets run when you type java). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
  • A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the -Xmx value; this allows it to have a contiguous heap. The -Xms value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
  • A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
  • Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a StackOverFlowError. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
  • One of the shared libraries that holds the actual JVM code. There are several of these.
  • The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.

The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, libc has 1.5M of virtual memory space that can be shared.

When is Virtual Memory Size Important?

The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.

Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.

But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.

When is Resident Set Size Important?

Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.

But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.

Bottom Line

Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.

With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.

Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so.

Java: notify() vs. notifyAll() all over again

However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.

That is not correct. o.notifyAll() wakes all of the threads that are blocked in o.wait() calls. The threads are only allowed to return from o.wait() one-by-one, but they each will get their turn.


Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?

In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time.

Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.


In many cases, the code to await a condition will be written as a loop:

synchronized(o) {
    while (! IsConditionTrue()) {
        o.wait();
    }
    DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}

That way, if an o.notifyAll() call wakes more than one waiting thread, and the first one to return from the o.wait() makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.

Enum String Name from Value

Just need:

string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"

Angular 2 Show and Hide an element

When you don't care about removing the Html Dom-Element, use *ngIf.

Otherwise, use this:

<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
   COUNTER: {{numberOfUnreadAlerts}} 
</div>

Bigger Glyphicons

Write your <span> in <h1> or <h2>:

<h1> <span class="glyphicon glyphicon-th-list"></span></h1>

GridLayout (not GridView) how to stretch all children evenly

Try adding the following to your GridLayout spec. That should work.

android:useDefaultMargins="true"

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

How to convert C++ Code to C

There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.

TortoiseGit save user authentication / credentials

I upgraded to my Git for Windows to latest (2.30.0) 64-bit and it works fine now. get the latest from the url https://git-scm.com/download/win and run the commands below to verify. $ git --version $ git version 2.30.0.windows.1

jQuery how to bind onclick event to dynamically added HTML element

    function load_tpl(selected=""){
        $("#load_tpl").empty();
        for(x in ds_tpl){
            $("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
        }
        $.each($("#load_tpl a"),function(){
            $(this).on("click",function(e){
                alert(e.target.id);
            });
        });
    }

Getting the Facebook like/share count for a given URL

For latest 2.1 Graph API, an example to get likes for imdb.com will be

Using this to get the id https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%253A%252F%252Fwww.imdb.com%3Ffields%3Dlikes&version=v2.1

and then get the likes

https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes&version=v2.1

Document

URL /?id={url}

Represents an external URL as it relates to the Facebook social graph - shares and comments from the URL on Facebook, and any Open Graph objects associated with the URL.

Reference http://harshtechtalk.com/how-get-likes-count-posts-comments-facebook-graph-api/

Static method in a generic class?

Since static variables are shared by all instances of the class. For example if you are having following code

class Class<T> {
  static void doIt(T object) {
    // using T here 
  }
}

T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables

Python Remove last 3 characters of a string

You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.

Like this:

>>> text = "xxxxcbaabc"
>>> text.rstrip("abc")
'xxxx'

So instead, just use

text = text[:-3] 

(after replacing whitespace with nothing)

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

Removing an item from a select box

Remove an option:

_x000D_
_x000D_
$("#selectBox option[value='option1']").remove();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Add an option:

_x000D_
_x000D_
$("#selectBox").append('<option value="option5">option5</option>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

Maven Error: Could not find or load main class

I got it too, the key was to change the output folder from bin to target\classes. It seems that in Eclipse, when converting a project to Maven project, this step is not done automatically, but Maven project will not look for main class based on bin, but will on target\classes.

How to Split Image Into Multiple Pieces in Python

Not sure if this is the most efficient answer, but it works for me:

import os
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = None # to avoid image size warning

imgdir = "/path/to/image/folder"
# if you want file of a specific extension (.png):
filelist = [f for f in glob.glob(imgdir + "**/*.png", recursive=True)]
savedir = "/path/to/image/folder/output"

start_pos = start_x, start_y = (0, 0)
cropped_image_size = w, h = (500, 500)

for file in filelist:
    img = Image.open(file)
    width, height = img.size

    frame_num = 1
    for col_i in range(0, width, w):
        for row_i in range(0, height, h):
            crop = img.crop((col_i, row_i, col_i + w, row_i + h))
            name = os.path.basename(file)
            name = os.path.splitext(name)[0]
            save_to= os.path.join(savedir, name+"_{:03}.png")
            crop.save(save_to.format(frame_num))
            frame_num += 1

This is mostly based on DataScienceGuy answer here

Open button in new window?

<input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I ran into this issue when we changed to Visual Studio 2015. None of the above answers worked for us. In the end we got it working by adding the following config file to ALL sgen.exe executables on the machine

<?xml version ="1.0"?>
    <configuration>
        <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0" />
        </startup>    
</configuration>

Particularly in this location, even when we were targeting .NET 4.0:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

Why did Servlet.service() for servlet jsp throw this exception?

The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.

It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>


Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

Extracting the top 5 maximum values in excel

There 3 functions you want to look at here:

I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:

Excel sample

  • In Cells A13 to A17, the values 1 to 5 were inserted to specify the nth highest value.
  • In Cell B13, the following formula was added: =LARGE($B$2:$B$11, A13)
  • In Cell C13, the following formula was added: =INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
  • These formulae get the highest ranking OPS and Player based on the value in A13.
  • Simply select and drag to copy these formulae down to the next 4 cells which will reference the corresponding ranking in Column A.

how to get GET and POST variables with JQuery?

For GET parameters, you can grab them from document.location.search:

var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

document.write($_GET["test"]);

For POST parameters, you can serialize the $_POST object in JSON format into a <script> tag:

<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;

document.write($_POST["test"]);
</script>

While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:

var $_GET = <?php echo json_encode($_GET); ?>;

Note: You'll need PHP version 5 or higher to use the built-in json_encode function.


Update: Here's a more generic implementation:

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

How to select bottom most rows?

The currently accepted answer by "Justin Ethier" is not a correct answer as pointed out by "Protector one".

As far as I can see, as of now, no other answer or comment provides the equivalent of BOTTOM(x) the question author asked for.

First, let's consider a scenario where this functionality would be needed:

SELECT * FROM Split('apple,orange,banana,apple,lime',',')

This returns a table of one column and five records:

  • apple
  • orange
  • banana
  • apple
  • lime

As you can see: we don't have an ID column; we can't order by the returned column; and we can't select the bottom two records using standard SQL like we can do for the top two records.

Here is my attempt to provide a solution:

SELECT * INTO #mytemptable FROM Split('apple,orange,banana,apple,lime',',')
ALTER TABLE #mytemptable ADD tempID INT IDENTITY
SELECT TOP 2 * FROM #mytemptable ORDER BY tempID DESC
DROP TABLE #mytemptable

And here is a more complete solution:

SELECT * INTO #mytemptable FROM Split('apple,orange,banana,apple,lime',',')
ALTER TABLE #mytemptable ADD tempID INT IDENTITY
DELETE FROM #mytemptable WHERE tempID <= ((SELECT COUNT(*) FROM #mytemptable) - 2)
ALTER TABLE #mytemptable DROP COLUMN tempID
SELECT * FROM #mytemptable
DROP TABLE #mytemptable

I am by no means claiming that this is a good idea to use in all circumstances, but it provides the desired results.

How to get html table td cell value by JavaScript?

.......................

  <head>

    <title>Search students by courses/professors</title>

    <script type="text/javascript">

    function ChangeColor(tableRow, highLight)
    {
       if (highLight){
           tableRow.style.backgroundColor = '00CCCC';
       }

    else{
         tableRow.style.backgroundColor = 'white';
        }   
  }

  function DoNav(theUrl)
  {
  document.location.href = theUrl;
  }
  </script>

</head>
<body>

     <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">

            <% for (Course cs : courses){ %>

            <tr onmouseover="ChangeColor(this, true);" 
                onmouseout="ChangeColor(this, false);" 
                onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">

                 <td name = "title" align = "center"><%= cs.getTitle() %></td>

            </tr>
           <%}%>

........................
</body>

I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.

The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:

 onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"

This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier. It works.

Send text to specific contact programmatically (whatsapp)

Whatsapp and most other apps that integrate into the Android core components (like Contacts) use a mime-type based intent to launch a certain Activity within the application. Whatsapp uses 3 separate mimetypes - text messages (vnd.android.cursor.item/vnd.com.whatsapp.profile), voip calls (vnd.android.cursor.item/vnd.com.whatsapp.voip.call) and video calls(vnd.android.cursor.item/vnd.com.whatsapp.video.call). For each of these mimetypes, a separate activity is mapped inside the Manifest of the application. For ex: the mimetype (...whatsapp.profile) maps to an Activity (com.whatsapp.Conversation). You can see these in detail if you dump out all the Data rows that maps to any Whatsapp Raw_Contact in your Contacts database.

This is also how the Android Contacts app shows 3 separate rows of user action inside a "Whatsapp contact", and clicking either of these rows launches a separate function inside Whatsapp.

To launch a Conversation (chat) Activity for a certain contact in Whatsapp, you need to fire an intent containing MIME_TYPE and DATA_URL. The mimetype points to the mimetype corresponding to your action as defined inside Whatsapp's Raw Contact in Contacts database. The DATA_URL is the URI of the Raw_Contact in the Android contacts database.

String whatsAppMimeType = Uri.parse("vnd.android.cursor.item").buildUpon()
                                    .appendEncodedPath("vnd.com.whatsapp.profile").build().toString();

Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.whatsapp")
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "WhatsApp")
        .build();

Cursor cursor = getContentResolver().query(uri, null, null, null);
if (cursor==null || cursor.getCount()==0) continue;

cursor.moveToNext();
int rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
cursor.close();

// now search for the Data row entry that matches the mimetype and also points to this RawContact
Cursor dataCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        null,
        ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
        new String[]{whatsAppMimeType, String.valueOf(rawContactId)}, null);
if (dataCursor==null || dataCursor.getCount()==0) continue;

dataCursor.moveToNext();
int dataRowId = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));

Uri userRowUri = ContactsContract.Data.CONTENT_URI.buildUpon()
                        .appendPath(String.valueOf(dataRowId)).build();


// launch the whatsapp user chat activity
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(userRowUri, whatsAppMimeType);
startActivity(intent);

dataCursor.close();

This is the same way that all Contacts app use to launch a chat Activity for a Whatsapp contact. Inside this Activity, the application (Whatsapp) reads in the .getData() to get the DATA_URI which was passed to this Activity. The Android Contacts app uses a standard mechanism to use the URI of the Raw Contact in Whatsapp. Unfortunately, I am not aware of a way by which the .Conversation ativity in Whatsapp reads in any text / data information from the caller of the intent. This basically means that its possible (using a very standard technique) to launch a certain "user action" inside Whatsapp. Or for that matter, any similar app.

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

Can you get a Windows (AD) username in PHP?

No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials

http://us2.php.net/ldap

Complete list of reasons why a css file might not be working

New one for you Guys !

During my Gulp minification process

<!-- build:css /css/project-mini.css -->
    <link rel="stylesheet" href="css/main.css"/>
    <link rel="stylesheet" href="css/splash.css"/>
    <link rel="stylesheet" href="css/header.css"/>
    <link rel="stylesheet" href="css/print.css" media="print"/>
<!-- endbuild -->

Last CSS file was for print and the generated output gave me

    <link rel="stylesheet" href="css/project-mini.css" media="print"/>

So because of media="print" all CSS rules were skipped !

How to add a "sleep" or "wait" to my Lua Script?

If you have luasocket installed:

local socket = require 'socket'
socket.sleep(0.2)

How to use the divide function in the query?

Try something like this

select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT

I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.

Read user input inside a loop

I have found this parameter -u with read.

"-u 1" means "read from stdin"

while read -r newline; do
    ((i++))
    read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
    echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)

Add new column with foreign key constraint in one command

ALTER TABLE TableName ADD NewColumnName INTEGER, FOREIGN KEY(NewColumnName) REFERENCES [ForeignKey_TableName](Foreign_Key_Column)

How do I get the first element from an IEnumerable<T> in .net?

If your IEnumerable doesn't expose it's <T> and Linq fails, you can write a method using reflection:

public static T GetEnumeratedItem<T>(Object items, int index) where T : class
{
  T item = null;
  if (items != null)
  {
    System.Reflection.MethodInfo mi = items.GetType()
      .GetMethod("GetEnumerator");
    if (mi != null)
    {
      object o = mi.Invoke(items, null);
      if (o != null)
      {
        System.Reflection.MethodInfo mn = o.GetType()
          .GetMethod("MoveNext");
        if (mn != null)
        {
          object next = mn.Invoke(o, null);
          while (next != null && next.ToString() == "True")
          {
            if (index < 1)
            {
              System.Reflection.PropertyInfo pi = o
                .GetType().GetProperty("Current");
              if (pi != null) item = pi
                .GetValue(o, null) as T;
              break;
            }
            index--;
          }
        }
      }
    }
  }
  return item;
}

How can I pretty-print JSON using node.js?

If you just want to pretty print an object and not export it as valid JSON you can use console.dir().

It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

const jsonString = `{"name":"John","color":"green",
                     "smoker":false,"id":7,"city":"Berlin"}`
const object = JSON.parse(jsonString)

console.dir(object, {depth: null, colors: true})

Screenshot of logged object

Under the hood it is a shortcut for console.log(util.inspect(…)). The only difference is that it bypasses any custom inspect() function defined on an object.

Are dictionaries ordered in Python 3.6+?

Are dictionaries ordered in Python 3.6+?

They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).

As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.


How does the Python 3.6 dictionary implementation perform better[2] than the older one while preserving element order?

Essentially, by keeping two arrays.

  • The first array, dk_entries, holds the entries (of type PyDictKeyEntry) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).

  • The second, dk_indices, holds the indices for the dk_entries array (that is, values that indicate the position of the corresponding entry in dk_entries). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices and the corresponding entry is fetched by indexing dk_entries. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t(1 byte) to int32_t/int64_t (4/8 bytes) on 32/64 bit builds)

In the previous implementation, a sparse array of type PyDictKeyEntry and size dk_size had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size full for performance reasons. (and the empty space still had PyDictKeyEntry size!).

This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t (X depending on dict size) 2/3 * dk_sizes full is kept. The empty space changed from type PyDictKeyEntry to intX_t.

So, obviously, creating a sparse array of type PyDictKeyEntry is much more memory demanding than a sparse array for storing ints.

You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.


In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.

For example, the dictionary:

d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

is currently stored as [keyhash, key, value]:

entries = [['--', '--', '--'],
           [-8522787127447073495, 'barry', 'green'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           ['--', '--', '--'],
           [-9092791511155847987, 'timmy', 'red'],
           ['--', '--', '--'],
           [-6480567542315338377, 'guido', 'blue']]

Instead, the data should be organized as follows:

indices =  [None, 1, None, None, None, 0, None, 2]
entries =  [[-9092791511155847987, 'timmy', 'red'],
            [-8522787127447073495, 'barry', 'green'],
            [-6480567542315338377, 'guido', 'blue']]

As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.


[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==, !=). dicts currently don't offer any of those behaviors/methods.


[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.

Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.

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

Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.

see there: https://download.mono-project.com/archive/4.3.2/windows-installer/

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

Concatenation of strings in Lua

If you are asking whether there's shorthand version of operator .. - no there isn't. You cannot write a ..= b. You'll have to type it in full: filename = filename .. ".tmp"

Run a PHP file in a cron job using CPanel

I hope your problem is with path & php binary as well. If you have fixed the path as per older answers, please use php-cli instead of php command while running cron job.

It may be possible php_sapi_name() is not returning cli. Its returning something else like cgi-fcgi etc.

/usr/bin/php-cli -q /home/username/public_html/cron/cron.php >/dev/null

I hope it will help.

How to delete all instances of a character in a string in python?

I suggest split (not saying that the other answers are invalid, this is just another way to do it):

def findreplace(char, string):
   return ''.join(string.split(char))

Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

And the speed...

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

Not as fast as replace or translate, but ok.

How to create roles in ASP.NET Core and assign them to users?

In Configure method declare your role manager (Startup)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager<IdentityRole> roleManager)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        Task.Run(()=>this.CreateRoles(roleManager)).Wait();
    }


    private async Task CreateRoles(RoleManager<IdentityRole> roleManager)
    {
        foreach (string rol in this.Configuration.GetSection("Roles").Get<List<string>>())
        {
            if (!await roleManager.RoleExistsAsync(rol))
            {
                await roleManager.CreateAsync(new IdentityRole(rol));
            }
        }
    }

OPTIONAL - In appsettings.JSON (it depends on you where you wanna get roles from)

{
"Roles": [
"SuperAdmin",
"Admin",
"Employee",
"Customer"
  ]
}

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

Move the -h and specify that mydir is a directory

attrib /S /D /L -H mydir\*.*

What is the use of a private static variable in Java?

When in a static method you use a variable, the variable have to be static too as an example:

private static int a=0;  
public static void testMethod() {  
        a=1;  
}

How do you do dynamic / dependent drop downs in Google Sheets?

You can start with a google sheet set up with a main page and drop down source page like shown below.

You can set up the first column drop down through the normal Data > Validations menu prompts.

Main Page

Main Page with the drop down for the first column already populated.

Drop Down Source Page

Source page for all of the sub-categories needed

After that, you need to set up a script with the name onEdit. (If you don't use that name, the getActiveRange() will do nothing but return cell A1)

And use the code provided here:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var myRange = SpreadsheetApp.getActiveRange();
  var dvSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
  var option = new Array();
  var startCol = 0;

  if(sheet.getName() == "Front Page" && myRange.getColumn() == 1 && myRange.getRow() > 1){
    if(myRange.getValue() == "Category 1"){
      startCol = 1;
    } else if(myRange.getValue() == "Category 2"){
      startCol = 2;
    } else if(myRange.getValue() == "Category 3"){
      startCol = 3;
    } else if(myRange.getValue() == "Category 4"){
      startCol = 4;
    } else {
      startCol = 10
    }

  if(startCol > 0 && startCol < 10){
    option = dvSheet.getSheetValues(3,startCol,10,1);
    var dv = SpreadsheetApp.newDataValidation();
    dv.setAllowInvalid(false);  
    //dv.setHelpText("Some help text here");
    dv.requireValueInList(option, true);
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
   }

  if(startCol == 10){
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).clearDataValidations();
  } 
  }
}

After that, set up a trigger in the script editor screen by going to Edit > Current Project Triggers. This will bring up a window to have you select various drop downs to eventually end up at this:

Trigger set up

You should be good to go after that!

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

What is the preferred/idiomatic way to insert into a map?

As of C++11, you have two major additional options. First, you can use insert() with list initialization syntax:

function.insert({0, 42});

This is functionally equivalent to

function.insert(std::map<int, int>::value_type(0, 42));

but much more concise and readable. As other answers have noted, this has several advantages over the other forms:

  • The operator[] approach requires the mapped type to be assignable, which isn't always the case.
  • The operator[] approach can overwrite existing elements, and gives you no way to tell whether this has happened.
  • The other forms of insert that you list involve an implicit type conversion, which may slow your code down.

The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.

Second, you can use the emplace() method:

function.emplace(0, 42);

This is more concise than any of the forms of insert(), works fine with move-only types like unique_ptr, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace methods aren't usually used that way.

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:

  • you must supply arguments that matches whatever arguments the view needs,
  • these arguments must match regexp patterns.

Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.

An example of URL pattern:

url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),

And then what happens in shell:

>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.

It doesn't work because I supplied no arguments.

>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'

Now it worked, but...

>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.

Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).

You can use reverse with both positional arguments and keyword arguments. The syntax is:

reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)

As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:

{% url 'news.views.year_archive' yearvar %}

So I used it in a similar way in my HTML template:

{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}

But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:

Reverse for ''show_cookies'' with arguments...

It started to work when I removed the quotes:

{% url show_cookies hostname=u.hostname url_id=u.pk %}

And this is confusing.

LaTeX source code listing like in professional books

There are several other things you can do, such as selecting new fonts:

\documentclass[10pt,a4paper]{article}
% ... lots of packages e.g. babel, microtype, fontenc, inputenc &c.
\usepackage{color}    % Leave this out if you care about B/W printing, obviously.
\usepackage{upquote}  % Turns curly quotes in verbatim text into straight quotes. 
                      % People who have to copy/paste code from the PDF output 
                      % will love you for this. Or perhaps more accurately: 
                      % They will not hate you/hate you less.
\usepackage{beramono} % Or some other package that provides a fixed width font. q.v.
                      % http://www.tug.dk/FontCatalogue/typewriterfonts.html
\usepackage{listings} 
\lstset {                 % A rudimentary config that shows off some features.
    language=Java,
    basicstyle=\ttfamily, % Without beramono, we'd get cmtt, the teletype font.
    commentstyle=\textit, % cmtt doesn't do italics. It might do slanted text though.
    \keywordstyle=        % Nor does cmtt do bold text.
        \color{blue}\bfseries,
    \tabsize=4            % Or whatever you use in your editor, I suppose.
}
\begin{document} 
\begin{lstlisting}
public final int ourAnswer() { return 42; /* Our final answer */ }
\end{lstlisting} 
\end{document}

How to implement OnFragmentInteractionListener

For those of you who visit this page looking for further clarification on this error, in my case the activity making the call to the fragment needed to have 2 implements in this case, like this:

public class MyActivity extends Activity implements 
    MyFragment.OnFragmentInteractionListener, 
    NavigationDrawerFragment.NaviationDrawerCallbacks {
    ...// rest of the code
}

C# ASP.NET Single Sign-On Implementation

[disclaimer: I'm one of the contributors]

We built a very simple free/opensource component that adds SAML support for ASP.NET apps https://github.com/jitbit/AspNetSaml

Basically it's just one short C# file you can throw into your project (or install via Nuget) and use it with your app

How to force a list to be vertical using html css

Hope this is your structure:

   <ul> 
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
   </ul> 

By default, it will be add one after another row:

-----
-----
-----

if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:

|  |  |
|  |  |

li
{
   display:block;
   float:left;
   width:300px; /* adjust */
   height:150px; /* adjust */
   padding: 5px; /*adjust*/
}

UITableView Cell selected Color?

Try Following code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdArray objectAtIndex:indexPath.row] forIndexPath:indexPath];

    // Configure the cell...
    cell.backgroundView =
    [[UIImageView alloc] init] ;
    cell.selectedBackgroundView =[[UIImageView alloc] init];

    UIImage *rowBackground;
    UIImage *selectionBackground;


    rowBackground = [UIImage imageNamed:@"cellBackgroundDarkGrey.png"];
    selectionBackground = [UIImage imageNamed:@"selectedMenu.png"];

    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;



    return cell;
}

//Swift Version:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell


        cell.selectedBackgroundView = UIImageView()
        cell.backgroundView=UIImageView()

        let selectedBackground : UIImageView = cell.selectedBackgroundView as! UIImageView
        selectedBackground.image = UIImage.init(named:"selected.png");

        let backGround : UIImageView = cell.backgroundView as! UIImageView
        backGround.image = UIImage.init(named:"defaultimage.png");

        return cell


    } 

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You are confusing two different java dumps. kill -3 generates a thread dump, not a heap dump.

Thread dump = stack traces for each thread in the JVM output to stdout as text.

Heap dump = memory contents for the JVM process output to a binary file.

To take a thread dump on Windows, CTRL+BREAK if your JVM is the foreground process is the simplest way. If you have a unix-like shell on Windows like Cygwin or MobaXterm, you can use kill -3 {pid} like you can in Unix.

To take a thread dump in Unix, CTRL+C if your JVM is the foreground process or kill -3 {pid} will work as long as you get the right PID for the JVM.

With either platform, Java comes with several utilities that can help. For thread dumps, jstack {pid} is your best bet. http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstack.html

Just to finish the dump question out: Heap dumps are not commonly used because they are difficult to interpret. But, they have a lot of useful information in them if you know where/how to look at them. The most common usage is to locate memory leaks. It is a good practice to set the -D on the java command-line so that the heap dump is generated automatically upon an OutOfMemoryError, -XX:+HeapDumpOnOutOfMemoryError But, you can manually trigger a heap dump, also. The most common way is to use the java utility jmap.

NOTE: this utility is not available on all platforms. As of JDK 1.6, jmap is available on Windows.

An example command-line would look something like

jmap -dump:file=myheap.bin {pid of the JVM}

The output "myheap.bin" is not human readable (for most of us), and you will need a tool to analyze it. My preference is MAT. http://www.eclipse.org/mat/

Cannot find Microsoft.Office.Interop Visual Studio

Just doing like @Kjartan.

Steps are as follows:

  1. Right click your C# project name in Visual Studio's "Solution Explorer";

  2. Then, select "add -> Reference -> COM -> Type Libraries " in order;

  3. Find the "Microsoft Office 16.0 Object Library", and add it to reference (Note: the version number may vary with the OFFICE you have installed);

  4. After doing this, you will see "Microsoft.Office.Interop.Word" under the "Reference" item in your project.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I have changed my connection string from

var myConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=True;Jet OLEDB:Database Password=;",gisdbPath);

to this:

var myConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Mode=Share Deny None;Data Source={0};user id=Admin;password=;", gisdbPath);

It works fro me never asked for Microsoft.Jet.OLEDB.4.0'registered.

How to cin to a vector

If you know the size use this

No temporary variable used just to store user input

int main()
{
    cout << "Hello World!\n"; 
    int n;//input size
    cin >> n;
    vector<int>a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

//to verify output user input printed below

    for (auto x : a) {
        cout << x << " ";
    }
    return 0;
}

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

preventDefault() on an <a> tag

It's suggested that you do not use return false, as 3 things occur as a result:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

So in this type of situation, you should really only use event.preventDefault();

Archive of article - jQuery Events: Stop (Mis)Using Return False

doGet and doPost in Servlets

If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted. On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.

Examples from my html:

<body>  
<form action="StartProcessUrl" method="post">
.....
.....

Examples from my java servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
         String surname = request.getParameter("txtSurname");
         String firstname = request.getParameter("txtForename");
         String rqNo = request.getParameter("txtRQ6");
         String nhsNo = request.getParameter("txtNHSNo");

         String attachment1 = request.getParameter("base64textarea1");
         String attachment2 = request.getParameter("base64textarea2");

.........
.........

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

How to grant all privileges to root user in MySQL 8.0

Well, I just had the same problem. Even if route had '%' could not connect remotely. Now, having a look at my.ini file (config file in windows) the bind-address statement was missed.

So... I putted this bind-address = * after [mysqld] and restarted the service. Now it works!