Programs & Examples On #Sharepoint designer

A piece of software for a user to further develop their SharePoint site beyond its basic capabilities by manipulating the design and behavior of the site.

How to edit default.aspx on SharePoint site without SharePoint Designer

Easy quick solution which worked for me. 1. Go to the root folder. Copy the default.aspx file. 2. Delete the original file. 3. Rename the copied file to default.aspx.

Its all set to experiment again. Not sure how sharepoint referencing these webparts in that page. But works :)

How to use linux command line ftp with a @ sign in my username?

As an alternative, if you don't want to create config files, do the unattended upload with curl instead of ftp:

curl -u user:password -T file ftp://server/dir/file

How do I limit the number of results returned from grep?

The -m option is probably what you're looking for:

grep -m 10 PATTERN [FILE]

From man grep:

-m NUM, --max-count=NUM
        Stop reading a file after NUM matching lines.  If the  input  is
        standard  input  from a regular file, and NUM matching lines are
        output, grep ensures that the standard input  is  positioned  to
        just  after the last matching line before exiting, regardless of
        the presence of trailing context lines.  This enables a  calling
        process  to resume a search.

Note: grep stops reading the file once the specified number of matches have been found!

Executing Shell Scripts from the OS X Dock?

I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html

To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.

jQuery scroll to element

ONELINER

subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});

_x000D_
_x000D_
subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior: 'smooth'});
_x000D_
.box,.foot{display: flex;background:#fdf;padding:500px 0} .foot{padding:250px}
_x000D_
<input type="text" class="textfield" value="click here" id="subject" name="subject">_x000D_
_x000D_
<div class="box">_x000D_
  Some content_x000D_
  <textarea></textarea>_x000D_
</div>_x000D_
_x000D_
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">_x000D_
_x000D_
<div class="foot">Some footer</div>
_x000D_
_x000D_
_x000D_

How to properly use the "choices" field option in Django

You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

import calendar
tuple((m, m) for m in calendar.month_name[1:])

Installing packages in Sublime Text 2

Here is a link to a shorter and to the point description: http://www.granneman.com/webdev/editors/sublime-text/packages/how-to-install-and-use-package-control/

The steps are:

  1. Install package control.
  2. Go to http://wbond.net/sublime_packages/package_control/installation and grab the install code.
  3. In Sublime Text 2 open the console (Ctrl+`) and paste the code.
  4. Restart Sublime Text 2.
  5. Open command palette via Command+Shift+P (Mac OSX) or Ctrl+Shift+P (Windows).
  6. Start typing Package Control and choose the package you are looking for.

How to split one string into multiple strings separated by at least one space in bash shell?

$ echo "This is   a sentence." | tr -s " " "\012"
This
is
a
sentence.

For checking for spaces, use grep:

$ echo "This is   a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null     
$ echo $?
1

disable past dates on datepicker

minDate: dateToday Or minDate: '0' is the key here. Try to set the minDate property.

$(function() {
    $( "#datepicker" ).datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        minDate: dateToday // minDate: '0' would work too
    });
});

Read more

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

Calculating Page Table Size

In 32 bit virtual address system we can have 2^32 unique address, since the page size given is 4KB = 2^12, we will need (2^32/2^12 = 2^20) entries in the page table, if each entry is 4Bytes then total size of the page table = 4 * 2^20 Bytes = 4MB

How do I open a new fragment from another fragment?

Add following code in your click listener function,

NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
             .replace(R.id.Layout_container, nextFrag, "findThisFragment")
             .addToBackStack(null)
             .commit();

The string "findThisFragment" can be used to find the fragment later, if you need.

Passing arguments to an interactive program non-interactively

Many ways

pipe your input

echo "yes
no
maybe" | your_program

redirect from a file

your_program < answers.txt

use a here document (this can be very readable)

your_program << ANSWERS
yes
no
maybe
ANSWERS

use a here string

your_program <<< $'yes\nno\nmaybe\n'

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

How to upgrade Git on Windows to the latest version?

If it is Windows, you can simply hit below command to update git. -

git update-git-for-windows

twitter bootstrap 3.0 typeahead ajax example

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

How to import or copy images to the "res" folder in Android Studio?

For Android Studio:

Right click on res, new Image Asset

Select the image radio button in 3rd option i.e Asset Type

Select the path of the image and click next and then finish

All the images are added to the respective folder, its very simple

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

Get integer value of the current year in Java

tl;dr

ZonedDateTime.now(  ZoneId.of( "Africa/Casablanca" )  )
             .getYear()

Time Zone

The answer by Raffi Khatchadourian wisely shows how to use the new java.time package in Java 8. But that answer fails to address the critical issue of time zone in determining a date.

int year = LocalDate.now().getYear();

That code depends on the JVM's current default time zone. The default zone is used in determining what today’s date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.

So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code at any moment changing the JVM's current default. Better to specify the time zone.

By the way, always use proper time zone names as defined by the IANA. Never use the 3-4 letter codes that are neither standardized nor unique.

java.time

Example in java.time of Java 8.

int year = ZonedDateTime.now(  ZoneId.of( "Africa/Casablanca" )  ).getYear() ;

Joda-Time

Some idea as above, but using the Joda-Time 2.7 library.

int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;

Incrementing/Decrementing Year

If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.

Example in java.time.

ZonedDateTime zdt = 
    ZonedDateTime
    .now(  ZoneId.of( "Africa/Casablanca" )  )
    .minusYears( 1 ) 
;

Example in Joda-Time 2.7.

DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;

Configuring Log4j Loggers Programmatically

In the case that you have defined an appender in log4j properties and would like to update it programmatically, set the name in the log4j properties and get it by name.

Here's an example log4j.properties entry:

log4j.appender.stdout.Name=console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=INFO

To update it, do the following:

((ConsoleAppender) Logger.getRootLogger().getAppender("console")).setThreshold(Level.DEBUG);

Pythonic way to return list of every nth item in a larger list

Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:

>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> l = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']

But this is still far slower than just using list slicing.

Reading CSV files using C#

My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.

These are the variants I have ran into:

  • quotes are quoted and doubled (excel) i.e. 15" -> field1,"15""",field3
  • quotes are not changed unless the field is quoted for some other reason. i.e. 15" -> field1,15",fields3
  • quotes are escaped with \. i.e. 15" -> field1,"15\"",field3
  • quotes are not changed at all (this is not always possible to parse correctly)
  • delimiter is quoted (excel). i.e. a,b -> field1,"a,b",field3
  • delimiter is escaped with \. i.e. a,b -> field1,a\,b,field3

I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.

In my projects I now use either the VB TextFieldParser or a custom splitter.

Comparing two byte arrays in .NET

Use SequenceEquals for this to comparison.

Difference between java.exe and javaw.exe

The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window

Best way to parseDouble with comma as decimal separator?

This would do the job:

Double.parseDouble(p.replace(',','.')); 

How do I handle Database Connections with Dapper in .NET?

I wrap connection with the helper class:

public class ConnectionFactory
{
    private readonly string _connectionName;

    public ConnectionFactory(string connectionName)
    {
        _connectionName = connectionName;
    }

    public IDbConnection NewConnection() => new SqlConnection(_connectionName);

    #region Connection Scopes

    public TResult Scope<TResult>(Func<IDbConnection, TResult> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return func(connection);
        }
    }

    public async Task<TResult> ScopeAsync<TResult>(Func<IDbConnection, Task<TResult>> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return await funcAsync(connection);
        }
    }

    public void Scope(Action<IDbConnection> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            func(connection);
        }
    }

    public async Task ScopeAsync<TResult>(Func<IDbConnection, Task> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            await funcAsync(connection);
        }
    }

    #endregion Connection Scopes
}

Examples of usage:

public class PostsService
{
    protected IConnectionFactory Connection;

    // Initialization here ..

    public async Task TestPosts_Async()
    {
        // Normal way..
        var posts = Connection.Scope(cnn =>
        {
            var state = PostState.Active;
            return cnn.Query<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });

        // Async way..
        posts = await Connection.ScopeAsync(cnn =>
        {
            var state = PostState.Active;
            return cnn.QueryAsync<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });
    }
}

So I don't have to explicitly open the connection every time. Additionally, you can use it this way for the convenience' sake of the future refactoring:

var posts = Connection.Scope(cnn =>
{
    var state = PostState.Active;
    return cnn.Query<Post>($"SELECT * FROM [{TableName<Post>()}] WHERE [{nameof(Post.State)}] = @{nameof(state)};", new { state });
});

What is TableName<T>() can be found in this answer.

Is JavaScript's "new" keyword considered harmful?

Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.

Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.

How to edit/save a file through Ubuntu Terminal

For editing use

vi galfit.feedme //if user has file editing permissions

or

sudo vi galfit.feedme //if user doesn't have file editing permissions

For inserting

Press i //Do required editing

For exiting

Press Esc

    :wq //for exiting and saving
    :q! //for exiting without saving

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

How to properly add 1 month from now to current date in moment.js

_x000D_
_x000D_
startdate = "20.03.2020";_x000D_
    var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');_x000D_
_x000D_
     alert(new_date)
_x000D_
_x000D_
_x000D_

How to set a timeout on a http.request() in Node?

At this moment there is a method to do this directly on the request object:

request.setTimeout(timeout, function() {
    request.abort();
});

This is a shortcut method that binds to the socket event and then creates the timeout.

Reference: Node.js v0.8.8 Manual & Documentation

Import and insert sql.gz file into database with putty

For an oneliner, on linux or cygwin, you need to do public key authentication on the host, otherwise ssh will be asking for password.


gunzip -c numbers.sql.gz | ssh user@host mysql --user=user_name --password=your_password db_name

Or do port forwarding and connect to the remote mysql using a "local" connection:

ssh -L some_port:host:local_mysql_port user@host

then do the mysql connection on your local machine to localhost:some_port.

The port forwarding will work from putty too, with the similar -L option or you can configure it from the settings panel, somewhere down on the tree.

Upload artifacts to Nexus, without Maven

In ruby https://github.com/RiotGames/nexus_cli A CLI wrapper around Sonatype Nexus REST calls.

Usage Example:

nexus-cli push_artifact com.mycompany.artifacts:myartifact:tgz:1.0.0 ~/path/to/file/to/push/myartifact.tgz

Configuration is done via the .nexus_cli file.

url:            "http://my-nexus-server/nexus/"
repository:     "my-repository-id"
username:       "username"
password:       "password"

Set Value of Input Using Javascript Function

document.getElementById('gadget_url').value = 'your value';

XAMPP on Windows - Apache not starting

The most likely reason would be that something else is using port 80. (Often this can be Skype, IIS, etc.)

This tutorials shows How to Change the Apache Port in XAMPP

notifyDataSetChanged example

I recently wrote on this topic, though this post it old, I thought it will be helpful to someone who wants to know how to implement BaseAdapter.notifyDataSetChanged() step by step and in a correct way.

Please follow How to correctly implement BaseAdapter.notifyDataSetChanged() in Android or the newer blog BaseAdapter.notifyDataSetChanged().

RecyclerView onClick

This is what I do to reuse OnClickListener

  public class TestAdapter extends RecyclerView.Adapter<TestAdapter.MyviewHolder>
                                         implements View.OnClickListener

in ViewHoder Take itemlayout's parent

  public class MyviewHolder extends RecyclerView.ViewHolder {

       LinearLayout linearLayout_item;

        public MyviewHolder(View itemView) {
            super(itemView);
            linearLayout_item=itemView.findViewById(R.id.linearLayout_item);
        }
    }

in onBindViewHolder set tag as position

   @Override
    public void onBindViewHolder(MyviewHolder holder, int position) {

       holder.linearLayout_item.setTag(position);
       holder.linearLayout_item.setOnClickListener(this);
    }

and in Onclick

 @Override
public void onClick(View v) {

    int position = (int) v.getTag();
    switch (v.getId()) {
        case R.id.linearLayout_item:

            // do some thing with position 

            break;
    }
}

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

How to left align a fixed width string?

With the new and popular f-strings in Python 3.6, here is how we left-align say a string with 16 padding length:

string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow  ..

If you have variable padding length:

k = 20
print(f"{string:<{k}}..")
Stack Overflow      .. 

f-strings are more compact.

Different between parseInt() and valueOf() in java?

Integer.valueOf(s)

is similar to

new Integer(Integer.parseInt(s))

The difference is valueOf() returns an Integer, and parseInt() returns an int (a primitive type). Also note that valueOf() can return a cached Integer instance, which can cause confusing results where the result of == tests seem intermittently correct. Before autoboxing there could be a difference in convenience, after java 1.5 it doesn't really matter.

Moreover, Integer.parseInt(s) can take primitive datatype as well.

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Push local Git repo to new remote including all branches and tags

To push all your branches, use either (replace REMOTE with the name of the remote, for example "origin"):

git push REMOTE '*:*'
git push REMOTE --all

To push all your tags:

git push REMOTE --tags

Finally, I think you can do this all in one command with:

git push REMOTE --mirror

However, in addition --mirror, will also push your remotes, so this might not be exactly what you want.

for each loop in Objective-C for accessing NSMutable dictionary

Just to not leave out the 10.6+ option for enumerating keys and values using blocks...

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];

If you want the actions to happen concurrently:

[dict enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                              usingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];

How to sort List of objects by some property

JAVA 8 and Above Answer (Using Lambda Expressions)

In Java 8, Lambda expressions were introduced to make this even easier! Instead of creating a Comparator() object with all of it's scaffolding, you can simplify it as follows: (Using your object as an example)

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted);

or even shorter:

Collections.sort(list, Comparator.comparingInt(ActiveAlarm ::getterMethod));

That one statement is equivalent to the following:

Collections.sort(list, new Comparator<ActiveAlarm>() {
    @Override
    public int compare(ActiveAlarm a1, ActiveAlarm a2) {
        return a1.timeStarted - a2.timeStarted;
    }
});

Think of Lambda expressions as only requiring you to put in the relevant parts of the code: the method signature and what gets returned.

Another part of your question was how to compare against multiple fields. To do that with Lambda expressions, you can use the .thenComparing() function to effectively combine two comparisons into one:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted             
       .thenComparing ((ActiveAlarm a1, ActiveAlarm a2) -> a1.timeEnded-a2.timeEnded)
);

The above code will sort the list first by timeStarted, and then by timeEnded (for those records that have the same timeStarted).

One last note: It is easy to compare 'long' or 'int' primitives, you can just subtract one from the other. If you are comparing objects ('Long' or 'String'), I suggest you use their built-in comparison. Example:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.name.compareTo(a2.name) );

EDIT: Thanks to Lukas Eder for pointing me to .thenComparing() function.

Int to Char in C#

(char)myint;

for example:

Console.WriteLine("(char)122 is {0}", (char)122);

yields:

(char)122 is z

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

How to change the size of the font of a JLabel to take the maximum size

label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));

taken from How to Use HTML in Swing Components

Group list by values

I don't know about elegant, but it's certainly doable:

oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
# change into: list = [["A", "C"], ["B"], ["D", "E"]]

order=[]
dic=dict()
for value,key in oldlist:
  try:
    dic[key].append(value)
  except KeyError:
    order.append(key)
    dic[key]=[value]
newlist=map(dic.get, order)

print newlist

This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Slick.js: Get current and total slides (ie. 3/5)

Modifications are done to the new Slick version 1.7.1.

Here is a updated script example: jsfiddle

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Python json.loads shows ValueError: Extra data

As you can see in the following example, json.loads (and json.load) does not decode multiple json object.

>>> json.loads('{}')
{}
>>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 368, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)

If you want to dump multiple dictionaries, wrap them in a list, dump the list (instead of dumping dictionaries multiple times)

>>> dict1 = {}
>>> dict2 = {}
>>> json.dumps([dict1, dict2])
'[{}, {}]'
>>> json.loads(json.dumps([dict1, dict2]))
[{}, {}]

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

How to ignore the first line of data when processing CSV data?

You could use an instance of the csv module's Sniffer class to deduce the format of a CSV file and detect whether a header row is present along with the built-in next() function to skip over the first row only when necessary:

import csv

with open('all16.csv', 'r', newline='') as file:
    has_header = csv.Sniffer().has_header(file.read(1024))
    file.seek(0)  # Rewind.
    reader = csv.reader(file)
    if has_header:
        next(reader)  # Skip header row.
    column = 1
    datatype = float
    data = (datatype(row[column]) for row in reader)
    least_value = min(data)

print(least_value)

Since datatype and column are hardcoded in your example, it would be slightly faster to process the row like this:

    data = (float(row[1]) for row in reader)

Note: the code above is for Python 3.x. For Python 2.x use the following line to open the file instead of what is shown:

with open('all16.csv', 'rb') as file:

Text inset for UITextField?

Swift 3 / Designable in Interface builder / Separate horizontal & vertical insects / usable out of the box

@IBDesignable
class TextFieldWithPadding: UITextField {

@IBInspectable var horizontalInset: CGFloat = 0
@IBInspectable var verticalInset: CGFloat = 0

override func textRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: horizontalInset , dy: verticalInset)
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: horizontalInset, dy: verticalInset)
}
}

usage:

usage

&

enter image description here

How to query for Xml values and attributes from table in SQL Server?

use value instead of query (must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):

select
    xt.Id
    , x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
    XmlTest xt
    cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)

Are 2 dimensional Lists possible in c#?

I used:

List<List<String>> List1 = new List<List<String>>
var List<int> = new List<int>();
List.add("Test");
List.add("Test2");
List1.add(List);
var List<int> = new List<int>();
List.add("Test3");
List1.add(List);

that equals:

List1
(
[0] => List2 // List1[0][x]
    (
        [0] => Test  // List[0][0] etc.
        [1] => Test2

    )
[1] => List2
    (
        [0] => Test3

MySQL Database won't start in XAMPP Manager-osx

I had success with easy killing all active mysql processes in Monitor Activity tool:

1) close XAMPP control

2) open Monitor Activity

3) select filter for All processes (default is My processes)

4) search for: mysql

5) force quit all the mysql

6) relaunch XAMPP control and launch apache again

Enjoy

How to change the locale in chrome browser

Open chrome, go to chrome://settings/languages

On the left, you should see a list of languages. Use mouse to drag the language you want to the top, that will change the order for the values in Accept-language of requests.

If you still don't see the language you prefer, it may be cookies. Go to cookies and clean it up you should be good.

Vue 2 - Mutating props vue-warn

I faced this issue as well. The warning gone after i use $on and $emit. It's something like use $on and $emit recommended to sent data from child component to parent component.

How do I print part of a rendered HTML page in JavaScript?

<div id="invocieContainer">
    <div class="row">
        ...Your html Page content here....
    </div>
</div>

<script src="/Scripts/printThis.js"></script>
<script>
    $(document).on("click", "#btnPrint", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#invocieContainer").printThis({
            debug: false, // show the iframe for debugging
            importCSS: true, // import page CSS
            importStyle: true, // import style tags
            printContainer: true, // grab outer container as well as the contents of the selector
            loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
            pageTitle: "", // add title to print page
            removeInline: false, // remove all inline styles from print elements
            printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
            header: null, // prefix to html
            formValues: true // preserve input/form values
        });

    });
</script>

For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js

How can I pass a list as a command-line argument with argparse?

You can parse the list as a string and use of the eval builtin function to read it as a list. In this case, you will have to put single quotes into double quote (or the way around) in order to ensure successful string parse.

# declare the list arg as a string
parser.add_argument('-l', '--list', type=str)

# parse
args = parser.parse()

# turn the 'list' string argument into a list object
args.list = eval(args.list)
print(list)
print(type(list))

Testing:

python list_arg.py --list "[1, 2, 3]"

[1, 2, 3]
<class 'list'>

Change bootstrap navbar background color and font color

No need for the specificity .navbar-default in your CSS. Background color requires background-color:#cc333333 (or just background:#cc3333). Finally, probably best to consolidate all your customizations into a single class, as below:

.navbar-custom {
    color: #FFFFFF;
    background-color: #CC3333;
}

..

<div id="menu" class="navbar navbar-default navbar-custom">

Example: http://www.bootply.com/OusJAAvFqR#

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

check if variable empty

you can use isset() routine .

also additionaly you can refer an range of is_type () functions like

is_string(), is_float(),is_int() etc to further specificaly test

Send data from activity to fragment in Android

I ran into a similar issue while using the latest Navigation architecture component. Tried out all the above-mentioned code with passing a bundle from my calling activity to Fragment.

The best solution, following the latest development trends in Android, is by using View Model (part of Android Jetpack).

Create and Initialize a ViewModel class in the parent Activity, Please note that this ViewModel has to be shared between the activity and fragment.

Now, Inside the onViewCreated() of the fragment, Initialize the Same ViewModel and setup Observers to listen to the ViewModel fields.

Here is a helpful, in-depth tutorial if you need.

https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c

What's the difference between console.dir and console.log?

None of the 7 prior answers mentioned that console.dir supports extra arguments: depth, showHidden, and whether to use colors.

Of particular interest is depth, which (in theory) allows travering objects into more than the default 2 levels that console.log supports.

I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose) and console.dir(mongoose, { depth: null }), the output was the same. What actually recursed deeply into the mongoose object was using util.inspect:

import * as util from 'util';
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

Format output string, right alignment

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

C - casting int to char and append char to char

int i = 100;
char c = (char)i;

There is no way to append one char to another. But you can create an array of chars and use it.

Project Links do not work on Wamp Server

I believe this is the best solution:

Open index.php in www folder and set

change line 30:$suppress_localhost = true;

to $suppress_localhost = false;

This will ensure the project is prefixed with your local host IP/name

Pagination on a list using ng-repeat

I've built a module that makes in-memory pagination incredibly simple.

It allows you to paginate by simply replacing ng-repeat with dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

Twitter Bootstrap onclick event on buttons-radio

Don't use data-toggle attribute so that you can control the toggle behavior by yourself. So it will avoid 'race-condition'

my codes:

button group template (written in .erb, embedded ruby for ruby on rails):

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

and javascript:

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

onChangeFeatures function will be triggered once the button is clicked.

Is it possible to wait until all javascript files are loaded before executing javascript code?

Expanding a bit on @Eruant's answer,

$(window).on('load', function() {
    // your code here
});

Works very well with both async and defer while loading on scripts.

So you can import all scripts like this:

<script src="/js/script1.js" async defer></script>
<script src="/js/script2.js" async defer></script>
<script src="/js/script3.js" async defer></script>

Just make sure script1 doesn't call functions from script3 before $(window).on('load' ..., make sure to call them inside window load event.

More about async/defer here.

Drawing a simple line graph in Java

Just complementing Hovercraft Full Of Eels's solution:

I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want.

Here is the Gist link, I'll also paste the code below: GraphPanel on Gist

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphPanel extends JPanel {

    private int width = 800;
    private int heigth = 400;
    private int padding = 25;
    private int labelPadding = 25;
    private Color lineColor = new Color(44, 102, 230, 180);
    private Color pointColor = new Color(100, 100, 100, 180);
    private Color gridColor = new Color(200, 200, 200, 200);
    private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
    private int pointWidth = 4;
    private int numberYDivisions = 10;
    private List<Double> scores;

    public GraphPanel(List<Double> scores) {
        this.scores = scores;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
        double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());

        List<Point> graphPoints = new ArrayList<>();
        for (int i = 0; i < scores.size(); i++) {
            int x1 = (int) (i * xScale + padding + labelPadding);
            int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
            graphPoints.add(new Point(x1, y1));
        }

        // draw white background
        g2.setColor(Color.WHITE);
        g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
        g2.setColor(Color.BLACK);

        // create hatch marks and grid lines for y axis.
        for (int i = 0; i < numberYDivisions + 1; i++) {
            int x0 = padding + labelPadding;
            int x1 = pointWidth + padding + labelPadding;
            int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
            int y1 = y0;
            if (scores.size() > 0) {
                g2.setColor(gridColor);
                g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
                g2.setColor(Color.BLACK);
                String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
                FontMetrics metrics = g2.getFontMetrics();
                int labelWidth = metrics.stringWidth(yLabel);
                g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
            }
            g2.drawLine(x0, y0, x1, y1);
        }

        // and for x axis
        for (int i = 0; i < scores.size(); i++) {
            if (scores.size() > 1) {
                int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
                int x1 = x0;
                int y0 = getHeight() - padding - labelPadding;
                int y1 = y0 - pointWidth;
                if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
                    g2.setColor(gridColor);
                    g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
                    g2.setColor(Color.BLACK);
                    String xLabel = i + "";
                    FontMetrics metrics = g2.getFontMetrics();
                    int labelWidth = metrics.stringWidth(xLabel);
                    g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
                }
                g2.drawLine(x0, y0, x1, y1);
            }
        }

        // create x and y axes 
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);

        Stroke oldStroke = g2.getStroke();
        g2.setColor(lineColor);
        g2.setStroke(GRAPH_STROKE);
        for (int i = 0; i < graphPoints.size() - 1; i++) {
            int x1 = graphPoints.get(i).x;
            int y1 = graphPoints.get(i).y;
            int x2 = graphPoints.get(i + 1).x;
            int y2 = graphPoints.get(i + 1).y;
            g2.drawLine(x1, y1, x2, y2);
        }

        g2.setStroke(oldStroke);
        g2.setColor(pointColor);
        for (int i = 0; i < graphPoints.size(); i++) {
            int x = graphPoints.get(i).x - pointWidth / 2;
            int y = graphPoints.get(i).y - pointWidth / 2;
            int ovalW = pointWidth;
            int ovalH = pointWidth;
            g2.fillOval(x, y, ovalW, ovalH);
        }
    }

//    @Override
//    public Dimension getPreferredSize() {
//        return new Dimension(width, heigth);
//    }
    private double getMinScore() {
        double minScore = Double.MAX_VALUE;
        for (Double score : scores) {
            minScore = Math.min(minScore, score);
        }
        return minScore;
    }

    private double getMaxScore() {
        double maxScore = Double.MIN_VALUE;
        for (Double score : scores) {
            maxScore = Math.max(maxScore, score);
        }
        return maxScore;
    }

    public void setScores(List<Double> scores) {
        this.scores = scores;
        invalidate();
        this.repaint();
    }

    public List<Double> getScores() {
        return scores;
    }

    private static void createAndShowGui() {
        List<Double> scores = new ArrayList<>();
        Random random = new Random();
        int maxDataPoints = 40;
        int maxScore = 10;
        for (int i = 0; i < maxDataPoints; i++) {
            scores.add((double) random.nextDouble() * maxScore);
//            scores.add((double) i);
        }
        GraphPanel mainPanel = new GraphPanel(scores);
        mainPanel.setPreferredSize(new Dimension(800, 600));
        JFrame frame = new JFrame("DrawGraph");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

It looks like this: Example pic

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

If you modify the grant tables manually (using INSERT, UPDATE, etc.), you should execute a FLUSH PRIVILEGES statement to tell the server to reload the grant tables.

PS: I wouldn't recommend to allow any host to connect for any user (especially not the root use). If you are using mysql for a client/server application, prefer a subnet address. If you are using mysql with a web server or application server, use specific IPs.

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

HTML form submit to PHP script

Here is what I find works

  1. Set a form name
  2. Use a default select option, for example...

    <option value="-1" selected>Please Select</option>

So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.

  1. Try to use HTML5 attributes now they are supported.

This input

<input type="submit">

should be

<input name="Submit" type="submit" value="Submit">

whenever I use a form that fails, it is a failure due to the difference in calling the button name submit and name as Submit.

You should also set your enctype attribute for your form as forms fail on my web host if it's not set.

How to build a RESTful API?

That is pretty much the same as created a normal website.

Normal pattern for a php website is:

  1. The user enter a url
  2. The server get the url, parse it and execute a action
  3. In this action, you get/generate every information you need for the page
  4. You create the html/php page with the info from the action
  5. The server generate a fully html page and send it back to the user

With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.

$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));

That all for the api. For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).

$info = file_get_contents(url);
$info = json_decode($info);

But it's more common to use the curl library to perform get and post call. You can ask me if you need help with curl.

Once the get the info from the api, you can do the 4 & 5 steps.

Look the php doc for json function and file_get_contents.

curl : http://fr.php.net/manual/fr/ref.curl.php


EDIT

No, wait, I don't get it. "php API page" what do you mean by that ?

The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.

ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.

So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.

Function getUserNameById(user_id)
{
  $userName = // call in db to get the user
  exit(json_encode($userName)); // maybe return work as well.
}

From the client side you do

    $username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
    <html>
    <body>
    <p>hello <?php echo $username ?> </p>
    </body>
    </html>

So the client never access directly the databases, that the api's role.

Is that clearer ?

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How do you check current view controller class in Swift?

Try this

if self is MyViewController {        

}

how to set radio button checked in edit mode in MVC razor view

Here is how I do it and works both for create and edit:

//How to do it with enums
<div class="editor-field">
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
   @Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>

//And with Booleans
<div class="editor-field">
   @Html.RadioButtonFor(x => x.IsMale, true) Male
   @Html.RadioButtonFor(x => x.IsMale, false) Female
</div>

the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:

<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">

And the checked property is dependent on the Model.IsMale value.

Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

Android custom dropdown/popup menu

First, create a folder named “menu” in the “res” folder.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Then, create your Activity Class:

public class PopupMenu1 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_menu_1);
    }

    public void onPopupButtonClick(View button) {
        PopupMenu popup = new PopupMenu(this, button);
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(PopupMenu1.this,
                        "Clicked popup menu item " + item.getTitle(),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        popup.show();
    }
}

Edit and Continue: "Changes are not allowed when..."

I had a database project in the solution which stopped the webforms project from being editted.

I clicked "Unload" on the database project and everything now works sweetly.

Can't bind to 'routerLink' since it isn't a known property

When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.

CKEditor, Image Upload (filebrowserUploadUrl)

To upload an image simple drag and drop from ur desktop or from anywhere n u can achieve this by copying the image and pasting it on the text area using ctrl+v

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

Try This.

Controller:

List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");

Uncaught TypeError: Cannot assign to read only property

I tried changing year to a different term, and it worked.

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}

Recursively look for files with a specific extension

The syntax I use is a bit different than what @Matt suggested:

find $directory -type f -name \*.in

(it's one less keystroke).

Share application "link" in Android

Share application with title is you app_name, content is your application link

private static void shareApp(Context context) {
    final String appPackageName = BuildConfig.APPLICATION_ID;
    final String appName = context.getString(R.string.app_name);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    String shareBodyText = "https://play.google.com/store/apps/details?id=" +
            appPackageName;
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, appName);
    shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
    context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string
            .share_with)));
}

New og:image size for Facebook share?

I'm using the minimum image size (200 x 200) and getting good results. Take a look:

enter image description here https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br

This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.

This size is on facebook documentation

duplicate 'row.names' are not allowed error

This related question points out a part of the ?read.table documentation that explains your problem:

If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered.

Your header row likely has 1 fewer column than the rest of the file and so read.table assumes that the first column is the row.names (which must all be unique), not a column (which can contain duplicated values). You can fix this by using one of the following two Solutions:

  1. adding a delimiter (ie \t or ,) to the front or end of your header row in the source file, or,
  2. removing any trailing delimiters in your data

The choice will depend on the structure of your data.

Example:
Here the header row is interpreted as having one fewer column than the data because the delimiters don't match:

v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

This is how it is interpreted by default:

   v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

The first column (with no header) values are interpreted as row.names: a1 and b1. If this column contains duplicates, which is entirely possible, then you get the duplicate 'row.names' are not allowed error.

If you set row.names = FALSE, the shift doesn't happen, but you still have a mismatching number of items in the header and in the data because the delimiters don't match.

Solution 1 Add trailing delimiter to header:

v1,v2,v3,  # 4 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

Solution 2 Remove excess trailing delimiter from non-header rows:

v1,v2,v3   # 3 items
a1,a2,a3   # 3 items!!
b1,b2,b3   # 3 items!!

iOS UIImagePickerController result image orientation after upload

Here is an UIImage extension in Swift 2 based on the accepted answer by @Anomie. It uses a clearer switch case. It also takes the optional value returned by CGBitmapContextCreateImage() into consideration.

extension UIImage {
    func rotateImageByOrientation() -> UIImage {
        // No-op if the orientation is already correct
        guard self.imageOrientation != .Up else {
            return self
        }

        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform = CGAffineTransformIdentity;

        switch (self.imageOrientation) {
        case .Down, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI))

        case .Left, .LeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))

        case .Right, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))

        default:
            break
        }

        switch (self.imageOrientation) {
        case .UpMirrored, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        case .LeftMirrored, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        default:
            break
        }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        let ctx = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
            CGImageGetBitsPerComponent(self.CGImage), 0,
            CGImageGetColorSpace(self.CGImage),
            CGImageGetBitmapInfo(self.CGImage).rawValue)
        CGContextConcatCTM(ctx, transform)
        switch (self.imageOrientation) {
        case .Left, .LeftMirrored, .Right, .RightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
        }

        // And now we just create a new UIImage from the drawing context
        if let cgImage = CGBitmapContextCreateImage(ctx) {
            return UIImage(CGImage: cgImage)
        } else {
            return self
        }
    }
}

C# Equivalent of SQL Server DataTypes

This is for SQL Server 2005. There are updated versions of the table for SQL Server 2008, SQL Server 2008 R2, SQL Server 2012 and SQL Server 2014.

SQL Server Data Types and Their .NET Framework Equivalents

The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.

SQL Server data type          CLR data type (SQL Server)    CLR data type (.NET Framework)  
varbinary                     SqlBytes, SqlBinary           Byte[]  
binary                        SqlBytes, SqlBinary           Byte[]  
varbinary(1), binary(1)       SqlBytes, SqlBinary           byte, Byte[] 
image                         None                          None

varchar                       None                          None
char                          None                          None
nvarchar(1), nchar(1)         SqlChars, SqlString           Char, String, Char[]     
nvarchar                      SqlChars, SqlString           String, Char[] 
nchar                         SqlChars, SqlString           String, Char[] 
text                          None                          None
ntext                         None                          None

uniqueidentifier              SqlGuid                       Guid 
rowversion                    None                          Byte[]  
bit                           SqlBoolean                    Boolean 
tinyint                       SqlByte                       Byte 
smallint                      SqlInt16                      Int16  
int                           SqlInt32                      Int32  
bigint                        SqlInt64                      Int64 

smallmoney                    SqlMoney                      Decimal  
money                         SqlMoney                      Decimal  
numeric                       SqlDecimal                    Decimal  
decimal                       SqlDecimal                    Decimal  
real                          SqlSingle                     Single  
float                         SqlDouble                     Double  

smalldatetime                 SqlDateTime                   DateTime  
datetime                      SqlDateTime                   DateTime 

sql_variant                   None                          Object  
User-defined type(UDT)        None                          user-defined type     
table                         None                          None 
cursor                        None                          None
timestamp                     None                          None 
xml                           SqlXml                        None

Downloading folders from aws s3, cp or sync?

sync method first lists both source and destination paths and copies only differences (name, size etc.).

cp --recursive method lists source path and copies (overwrites) all to the destination path.

If you have possible matches in the destination path, I would suggest sync as one LIST request on the destination path will save you many unnecessary PUT requests - meaning cheaper and possibly faster.

Generating combinations in c++

A simple way using std::next_permutation:

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

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

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

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

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

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

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

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

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

A bit of explanation:

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


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

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

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

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

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

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

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

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

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

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

test output:

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

How to set session attribute in java?

Java file : Jclass.java

package Jclasspackage

public class Jclass {

    public String uname ;
    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }

    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }

    public Jclass() {
        this.uname = null;
    }

    public static void main(String[] args) {

    }
}

JSP file: sample.jsp

    <%@ page language="java"
    import="java.util.*,java.io.*"
    pageEncoding="ISO-8859-1"%>

<jsp:directive.page import="Jclasspackage.Jclass.java" />   
<% Jclass jc = new Jclass();
String username = (String)request.getAttribute("un")
jc.setUname(username);
%>

-----------------

In this way you can access the username in the java file using "this.username" in the class

Alternative to google finance api

Updating answer a bit

1. Try Twelve Data API

For beginners try to run the following query with a JSON response:

https://api.twelvedata.com/time_series?symbol=AAPL&interval=1min&apikey=demo&source=docs

NO more real time Alpha Vantage API

For beginners you can try to get a JSON output from query such as

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

DON'T Try Yahoo Finance API (it is DEPRECATED or UNAVAILABLE NOW).

For beginners, you can generate a CSV with a simple API call:

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk

(This will generate and save a CSV for AAPL, GOOG, and MSFT)

Note that you must append the format to the query string (f=..). For an overview of all of the formats see this page.

For more examples, visit this page.

For XML and JSON-based data, you can do the following:

Don't use YQL (Yahoo Query Language)

For example:

http://developer.yahoo.com/yql/console/?q=select%20*%20from%20yahoo.finance
.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22
MSFT%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env

2. Use the webservice

For example, to get all stock quotes in XML:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote

To get all stock quotes in JSON, just add format=JSON to the end of the URL:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json

Alternatives:

  1. Currency API

    • 165+ real time currency rates, including few cryptos. Docs here.
  2. Financial Content API

  3. IEX

  4. Open Exchange Rates

  5. Polygon

  6. XE API

  7. Xignite API

  8. currencylayer API

  9. Other APIs - discussed at programmableWeb

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

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

Attempt to set a non-property-list object as an NSUserDefaults

Swift with @propertyWrapper

Save Codable object to UserDefault

@propertyWrapper
    struct UserDefault<T: Codable> {
        let key: String
        let defaultValue: T

        init(_ key: String, defaultValue: T) {
            self.key = key
            self.defaultValue = defaultValue
        }

        var wrappedValue: T {
            get {

                if let data = UserDefaults.standard.object(forKey: key) as? Data,
                    let user = try? JSONDecoder().decode(T.self, from: data) {
                    return user

                }

                return  defaultValue
            }
            set {
                if let encoded = try? JSONEncoder().encode(newValue) {
                    UserDefaults.standard.set(encoded, forKey: key)
                }
            }
        }
    }




enum GlobalSettings {

    @UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
}

Example User model confirm Codable

struct User:Codable {
    let name:String
    let pass:String
}

How to use it

//Set value 
 GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")

//GetValue
print(GlobalSettings.user)

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

SQL Server: converting UniqueIdentifier to string in a case statement

In my opinion, uniqueidentifier / GUID is neither a varchar nor an nvarchar but a char(36). Therefore I use:

CAST(xyz AS char(36))

Custom HTTP headers : naming conventions

The recommendation is was to start their name with "X-". E.g. X-Forwarded-For, X-Requested-With. This is also mentioned in a.o. section 5 of RFC 2047.


Update 1: On June 2011, the first IETF draft was posted to deprecate the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, x-gzip & gzip are now equivalent). So, the official recommendation is to just name them sensibly without the "X-" prefix.


Update 2: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as RFC 6648. Below are cites of relevance:

3. Recommendations for Creators of New Parameters

...

  1. SHOULD NOT prefix their parameter names with "X-" or similar constructs.

4. Recommendations for Protocol Designers

...

  1. SHOULD NOT prohibit parameters with an "X-" prefix or similar constructs from being registered.

  2. MUST NOT stipulate that a parameter with an "X-" prefix or similar constructs needs to be understood as unstandardized.

  3. MUST NOT stipulate that a parameter without an "X-" prefix or similar constructs needs to be understood as standardized.

Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also RFC 2119 for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.


Summary:

  • the official recommendation is to just name them sensibly without the "X-" prefix
  • you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

Convert UTC date time to local date time

@Adorojan's answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa. Below is the solution which I came with and is working perfectly fine for me:

_x000D_
_x000D_
// Input time in UTC_x000D_
var inputInUtc = "6/29/2011 4:52:48";_x000D_
_x000D_
var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));_x000D_
//Print date in UTC time_x000D_
document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>");_x000D_
_x000D_
var dateInLocalTz = convertUtcToLocalTz(dateInUtc);_x000D_
//Print date in local time_x000D_
document.write("Date in Local : " + dateInLocalTz.toISOString());_x000D_
_x000D_
function convertUtcToLocalTz(dateInUtc) {_x000D_
  //Convert to local timezone_x000D_
  return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000);_x000D_
}
_x000D_
_x000D_
_x000D_

How can I render repeating React elements?

This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:

Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)

kudos to https://php.quicoto.com/create-loop-inside-react-jsx/

How to Generate a random number of fixed length using JavaScript?

I created the below function to generate random number of fix length:

function getRandomNum(length) {
    var randomNum = 
        (Math.pow(10,length).toString().slice(length-1) + 
        Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
    return randomNum;
}

This will basically add 0's at the beginning to make the length of the number as required.

Unable to copy ~/.ssh/id_rsa.pub

Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:

clip.exe < ~/.ssh/id_rsa.pub

Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

It seems like your rvm does not load ".bash_profile" properly. I have done to fix it in MAC OS X or Ubuntu 14.04 by opening terminal and write:

source ~/.rvm/scripts/rvm

How to play videos in android from assets folder or raw folder?

Did you try to put manually Video on SDCard and try to play video store on SDCard ?

If it's working you can find the way to copy from Raw to SDcard here :

android-copy-rawfile-to-sdcard-video-mp4.

Does "\d" in regex mean a digit?

This is just a guess, but I think your editor actually matches every single digit — 1 2 3 — but only odd matches are highlighted, to distinguish it from the case when the whole 123 string is matched.

Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.

Content Type text/xml; charset=utf-8 was not supported by service

First Google hit says:

this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.

It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.

JQuery, select first row of table

jQuery is not necessary, you can use only javascript.

<table id="table">
  <tr>...</tr>
  <tr>...</tr>
  <tr>...</tr>
   ......
  <tr>...</tr>
</table>

The table object has a collection of all rows.

var myTable = document.getElementById('table');
var rows =  myTable.rows;
var firstRow = rows[0];

How to find a value in an excel column by vba code Cells.Find

Just for sake of completeness, you can also use the same technique above with excel tables.

In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.

Dim list As ListObject
Dim config As Worksheet
Dim cell as Range


Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")

'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)

If cell Is Nothing Then
    'when information is not found
Else
    'when information is found
End If

Does functional programming replace GoF design patterns?

You can't have this discussion without bringing up type systems.

The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.

That's because these features don't address the same issues that OOP does... they are alternatives to imperative programming. The FP answer to OOP lies in the type systems of ML and Haskell... specifically sum types, abstract data types, ML modules, and Haskell typeclasses.

But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use)

The first thing typeclasses do is eliminate the need for singletons.

You could go through the list of 23 and eliminate more, but I don't have time to right now.

How can I change the Java Runtime Version on Windows (7)?

Since Java 1.6, a java.exe is installed into %windir%\system32 that supports a "-version" command line option. You can use this to select a specific version to run, e.g.:

java -version:1.7 -jar [path to jar file]

will run a jar application in java 1.7, if it is installed.

See Oracle's documentation here: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

I've converted the http://html5pattern.com/Dates Full Date Validation (YYYY-MM-DD) to DD/MM/YYYY Brazilian format:

pattern='(?:((?:0[1-9]|1[0-9]|2[0-9])\/(?:0[1-9]|1[0-2])|(?:30)\/(?!02)(?:0[1-9]|1[0-2])|31\/(?:0[13578]|1[02]))\/(?:19|20)[0-9]{2})'

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

Is it possible to use if...else... statement in React render function?

If you want to use If, else if, and else then use this method

           {this.state.value === 0 ? (
                <Component1 />
            ) : this.state.value === 1 ? (
              <Component2 />
            ) : (
              <Component3 />
            )}

How to include files outside of Docker's build context?

Using docker-compose, I accomplished this by creating a service that mounts the volumes that I need and committing the image of the container. Then, in the subsequent service, I rely on the previously committed image, which has all of the data stored at mounted locations. You will then have have to copy these files to their ultimate destination, as host mounted directories do not get committed when running a docker commit command

You don't have to use docker-compose to accomplish this, but it makes life a bit easier

# docker-compose.yml

version: '3'
  services:
    stage:
      image: alpine
      volumes:
        - /host/machine/path:/tmp/container/path
      command: bash -c "cp -r /tmp/container/path /final/container/path"
    setup:
      image: stage
# setup.sh

# Start "stage" service
docker-compose up stage

# Commit changes to an image named "stage"
docker commit $(docker-compose ps -q stage) stage

# Start setup service off of stage image
docker-compose up setup

Using unset vs. setting a variable to empty

Mostly you don't see a difference, unless you are using set -u:

/home/user1> var=""
/home/user1> echo $var

/home/user1> set -u
/home/user1> echo $var

/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable

So really, it depends on how you are going to test the variable.

I will add that my preferred way of testing if it is set is:

[[ -n $var ]]  # True if the length of $var is non-zero

or

[[ -z $var ]]  # True if zero length

Responding with a JSON object in Node.js (converting object/array to JSON string)

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How do I simulate a low bandwidth, high latency environment?

In the past, I have used a bridge using the Linux Netem (Network Emulation) functionality. It is highly configurable -- allowing the introduction of delays (the first example is for a WAN), packet loss, corruption, etc.

I'm noting that Netem worked very well for my applications, but I also ended up using WANem several times. The provided bootable ISO (and virtual appliance images) made it quite handy.

How to close activity and go back to previous activity in android

You can go back to the previous activity by just calling finish() in the activity you are on. Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this.

If you want to return results to activity one then when starting activity two you need:

startActivityForResults(myIntent, MY_REQUEST_CODE);

Inside your called activity you can then get the Intent from the onCreate() parameter or used

getIntent();

To set return a result to activity one then in activity two do

setResult(Activity.RESULT_OK, MyIntentToReturn);

If you have no intent to return then just say

setResult(Activity.RESULT_OK);

If the the activity has bad results you can use Activity.RESULT_CANCELED (this is used by default). Then in activity one you do

onActivityResult(int requestCode, int resultCode, Intent data) {
    // Handle the logic for the requestCode, resultCode and data returned...
}

To finish activity two use the same methods with finish() as described above with your results already set.

How to use Visual Studio Code as Default Editor for Git

Another useful option is to set EDITOR environment variable. This environment variable is used by many utilities to know what editor to use. Git also uses it if no core.editor is set.

You can set it for current session using:

export EDITOR="code --wait"

This way not only git, but many other applications will use VS Code as an editor.

To make this change permanent, add this to your ~/.profile for example. See this question for more options.


Another advantage of this approach is that you can set different editors for different cases:

  1. When you working from local terminal.
  2. When you are connected through SSH session.

This is useful especially with VS Code (or any other GUI editor) because it just doesn't work without GUI.

On Linux OS, put this into your ~/.profile:

# Preferred editor for local and remote sessions
if [[ -n $SSH_CONNECTION ]]; then # SSH mode
  export EDITOR='vim'
else # Local terminal mode
  export EDITOR='code -w'
fi

This way when you use a local terminal, the $SSH_CONNECTION environment variable will be empty, so the code -w editor will be used, but when you are connected through SSH, then $SSH_CONNECTION environment variable will be a non-empty string, so the vim editor will be used. It is console editor, so it will work even when you are connected through SSH.

How do you create a dropdownlist from an enum in ASP.NET MVC?

UPDATED - I would suggest using the suggestion by Rune below rather than this option!


I assume that you want something like the following spat out:

<select name="blah">
    <option value="1">Movie</option>
    <option value="2">Game</option>
    <option value="3">Book</option>
</select>

which you could do with an extension method something like the following:

public static string DropdownEnum(this System.Web.Mvc.HtmlHelper helper,
                                  Enum values)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<select name=\"blah\">");
    string[] names = Enum.GetNames(values.GetType());
    foreach(string name in names)
    {
        sb.Append("<option value=\"");
        sb.Append(((int)Enum.Parse(values.GetType(), name)).ToString());
        sb.Append("\">");
        sb.Append(name);
        sb.Append("</option>");
    }
    sb.Append("</select>");
    return sb.ToString();
}

BUT things like this aren't localisable (i.e. it will be hard to translate into another language).

Note: you need to call the static method with an instance of the Enumeration, i.e. Html.DropdownEnum(ItemTypes.Movie);

There may be a more elegant way of doing this, but the above does work.

Facebook Oauth Logout

the mobile solution suggested by Sumit works perfectly for AS3 Air:

html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"

.htaccess not working apache

First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.

Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.

Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.

How to use document.getElementByName and getElementByTag?

If you have given same text name for both of your Id and Name properties you can give like document.getElementByName('frmMain')[index] other wise object required error will come.And if you have only one table in your page you can use document.getElementBytag('table')[index].

EDIT:

You can replace the index according to your form, if its first form place 0 for index.

When to use a View instead of a Table?

You should design your table WITHOUT considering the views.
Apart from saving joins and conditions, Views do have a performance advantage: SQL Server may calculate and save its execution plan in the view, and therefore make it faster than "on the fly" SQL statements.
View may also ease your work regarding user access at field level.

How to go from Blob to ArrayBuffer

You can use FileReader to read the Blob as an ArrayBuffer.

Here's a short example:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Here's a longer example:

// ArrayBuffer -> Blob
var uint8Array  = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob        = new Blob([arrayBuffer]);

// Blob -> ArrayBuffer
var uint8ArrayNew  = null;
var arrayBufferNew = null;
var fileReader     = new FileReader();
fileReader.onload  = function(event) {
    arrayBufferNew = event.target.result;
    uint8ArrayNew  = new Uint8Array(arrayBufferNew);

    // warn if read values are not the same as the original values
    // arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
    function arrayEqual(a, b) { return !(a<b || b<a); };
    if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
        console.warn("ArrayBuffer byteLength does not match");
    if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
        console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read

This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.

Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/

Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result versus this.result

Reference:

In a Bash script, how can I exit the entire script if a certain condition occurs?

A SysOps guy once taught me the Three-Fingered Claw technique:

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

Explanation

(based on flying sheep comment).

  • yell: print the script name and all arguments to stderr:
    • $0 is the path to the script ;
    • $* are all arguments.
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.

python: SyntaxError: EOL while scanning string literal

You can try this:

s = r'long\annoying\path'

Simple way to convert datarow array to datatable

For .Net Framework 3.5+

DataTable dt = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt1 = dr.CopyToDataTable();

But if there is no rows in the array, it can cause the errors such as The source contains no DataRows. Therefore, if you decide to use this method CopyToDataTable(), you should check the array to know it has datarows or not.

if (dr.Length > 0)
    DataTable dt1 = dr.CopyToDataTable();

Reference available at MSDN: DataTableExtensions.CopyToDataTable Method (IEnumerable)

Return multiple values from a SQL Server function

Here's the Query Analyzer template for an in-line function - it returns 2 values by default:

-- =============================================  
-- Create inline function (IF)  
-- =============================================  
IF EXISTS (SELECT *   
   FROM   sysobjects   
   WHERE  name = N'<inline_function_name, sysname, test_function>')  
DROP FUNCTION <inline_function_name, sysname, test_function>  
GO  

CREATE FUNCTION <inline_function_name, sysname, test_function>   
(<@param1, sysname, @p1> <data_type_for_param1, , int>,   
 <@param2, sysname, @p2> <data_type_for_param2, , char>)  
RETURNS TABLE   
AS  
RETURN SELECT   @p1 AS c1,   
        @p2 AS c2  
GO  

-- =============================================  
-- Example to execute function  
-- =============================================  
SELECT *   
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>   
    (<value_for_@param1, , 1>,   
     <value_for_@param2, , 'a'>)  
GO  

Using python map and other functional tools

Here's the solution you're looking for:

>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]

I'd recommend using a list comprehension (the [(x, bars) for x in foos] part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:

>>> y = ((x, bars) for x in foos)
>>> for z in y:
...     print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])

The difference is that the generator comprehension is lazily loaded.

UPDATE In response to this comment:

Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.

I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:

tbars = tuple(bars)
[(x, tbars) for x in foos]

Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:

from copy import copy
[(x, copy(bars)) for x in foos]

However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.

Get selected value of a dropdown's item using jQuery

try this

$("#yourDropdown option:selected").text();

Is there a simple way to use button to navigate page as a link does in angularjs

 <a type="button" href="#/new-page.html" class="btn btn-lg btn-success" >New Page</a>

Simple...

How do I run git log to see changes only for a specific branch?

If you want only those commits which are done by you in a particular branch, use the below command.

git log branch_name --author='Dyaniyal'

How can I get a Unicode character's code?

For me, only "Integer.toHexString(registered)" worked the way I wanted:

char registered = '®';
System.out.println("Answer:"+Integer.toHexString(registered));

This answer will give you only string representations what are usually presented in the tables. Jon Skeet's answer explains more.

Wordpress plugin install: Could not create directory

I had to give ownership of /plugins and /upgrade to the server, nothing else.

$ cd /var/www/wordpress/wp-content
$ sudo chown www-data:www-data /plugings
$ sudo chown www-data:www-data /upgrade

Running Apache server on Ubuntu 18.04. Maybe more dirs will need to be changed later. Anyways, I plan to restore permissions once I finish editing, as suggested in this anwser.

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

avrdude: stk500v2_ReceiveMessage(): timeout

The error message basically means that the programmer is unable to contact the bootloader on the device; the code you're trying to upload has no bearing on the problem.

What causes this can be numerous and varied, some possible issues:

  1. UART communications

    • Blinking is happening, so hopefully you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.

    • Connect TX to RX (and disconnect them from the AVR if possible) then open a terminal on the COM port, you should see characters echoed if you type them. If you don't, something is wrong up-stream of the chip, it could be the communications chip (I think the Arduino 2560 uses a secondary AVR instead of an FTDI for some reason, so that could be broken, either its software or hardware)

  2. ATmega* bootloader

    • The AVR is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the AVR (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.

    • Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.

  3. Arduino Mega 2560 only: ATmega8U/16U software

    • Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer to reflash the target.
  4. Hardware damage to the board, AVR(s), or FTDI chip

    • You're hosed; need a new chip.

Check this forum post for some more ideas.

Is there a constraint that restricts my generic method to numeric types?

This question is a bit of a FAQ one, so I'm posting this as wiki (since I've posted similar before, but this is an older one); anyway...

What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).

This has methods like T Add<T>(T x, T y), and other variants for arithmetic on different types (like DateTime + TimeSpan).

Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.

Some additional background on why this is tricky is here.

You may also want to know that dynamic (4.0) sort-of solves this issue indirectly too - i.e.

dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Last year, I took Prof: Andrew Ng’s online machine learning course. His recommendation was:

Training: 60%

Cross validation: 20%

Testing: 20%

When do items in HTML5 local storage expire?

Brynner Ferreira, has brought a good point: storing a sibling key where expiration info resides. This way, if you have a large amount of keys, or if your values are large Json objects, you don't need to parse them to access the timestamp.

here follows an improved version:

 /*  removeStorage: removes a key from localStorage and its sibling expiracy key
    params:
        key <string>     : localStorage key to remove
    returns:
        <boolean> : telling if operation succeeded
 */
 function removeStorage(name) {
    try {
        localStorage.removeItem(name);
        localStorage.removeItem(name + '_expiresIn');
    } catch(e) {
        console.log('removeStorage: Error removing key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
        return false;
    }
    return true;
}
/*  getStorage: retrieves a key from localStorage previously set with setStorage().
    params:
        key <string> : localStorage key
    returns:
        <string> : value of localStorage key
        null : in case of expired key or failure
 */
function getStorage(key) {

    var now = Date.now();  //epoch time, lets deal only with integer
    // set expiration for storage
    var expiresIn = localStorage.getItem(key+'_expiresIn');
    if (expiresIn===undefined || expiresIn===null) { expiresIn = 0; }

    if (expiresIn < now) {// Expired
        removeStorage(key);
        return null;
    } else {
        try {
            var value = localStorage.getItem(key);
            return value;
        } catch(e) {
            console.log('getStorage: Error reading key ['+ key + '] from localStorage: ' + JSON.stringify(e) );
            return null;
        }
    }
}
/*  setStorage: writes a key into localStorage setting a expire time
    params:
        key <string>     : localStorage key
        value <string>   : localStorage value
        expires <number> : number of seconds from now to expire the key
    returns:
        <boolean> : telling if operation succeeded
 */
function setStorage(key, value, expires) {

    if (expires===undefined || expires===null) {
        expires = (24*60*60);  // default: seconds for 1 day
    } else {
        expires = Math.abs(expires); //make sure it's positive
    }

    var now = Date.now();  //millisecs since epoch time, lets deal only with integer
    var schedule = now + expires*1000; 
    try {
        localStorage.setItem(key, value);
        localStorage.setItem(key + '_expiresIn', schedule);
    } catch(e) {
        console.log('setStorage: Error setting key ['+ key + '] in localStorage: ' + JSON.stringify(e) );
        return false;
    }
    return true;
}

Calling class staticmethod within the class body?

staticmethod objects apparently have a __func__ attribute storing the original raw function (makes sense that they had to). So this will work:

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):

>>> class Foo(object):
...     @staticmethod
...     def foo():
...         return 3
...     global z
...     z = foo

>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>

Similar sorts of digging in an interactive session (dir is very helpful) can often solve these sorts of question very quickly.

How can I obtain the element-wise logical NOT of a pandas Series?

@unutbu's answer is spot on, just wanted to add a warning that your mask needs to be dtype bool, not 'object'. Ie your mask can't have ever had any nan's. See here - even if your mask is nan-free now, it will remain 'object' type.

The inverse of an 'object' series won't throw an error, instead you'll get a garbage mask of ints that won't work as you expect.

In[1]: df = pd.DataFrame({'A':[True, False, np.nan], 'B':[True, False, True]})
In[2]: df.dropna(inplace=True)
In[3]: df['A']
Out[3]:
0    True
1   False
Name: A, dtype object
In[4]: ~df['A']
Out[4]:
0   -2
0   -1
Name: A, dtype object

After speaking with colleagues about this one I have an explanation: It looks like pandas is reverting to the bitwise operator:

In [1]: ~True
Out[1]: -2

As @geher says, you can convert it to bool with astype before you inverse with ~

~df['A'].astype(bool)
0    False
1     True
Name: A, dtype: bool
(~df['A']).astype(bool)
0    True
1    True
Name: A, dtype: bool

generate model using user:references vs user_id:integer

Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:

:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)

The second command adds a belongs_to :user relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id column and it will use a model named User to instantiate the specific user.

The second command also adds an index on the new user_id column.

Installing Apache Maven Plugin for Eclipse

Installing m2eclipse

All downloads are provided under the terms and conditions of the Eclipse Foundation Software User Agreement unless otherwise specified.

m2e is tested against Eclipse 4.2 (Juno) and 4.3 (Kepler).

See http://wiki.eclipse.org/M2E_updatesite_and_gittags for detailed information about available builds and m2e build repository layout.

m2e 1.3 and earlier version have been removed from the main m2e update site. These old releases are still available and can be installed from repositories documented in http://wiki.eclipse.org/M2E_updatesite_and_gittags

Please note that links below point at Eclipse p2 repositories; you must access them from Eclipse (see how). Update Sites Latest m2e release (recommended) http://download.eclipse.org/technology/m2e/releases m2e milestone builds towards version 1.5 http://download.eclipse.org/technology/m2e/milestones/1.5 Latest m2e 1.5 SNAPSHOT build (not tested, not hosted at eclipse.org) http://repository.takari.io:8081/nexus/content/sites/m2e.extras/m2e/1.5.0/N/LATEST/

Concatenating two std::vectors

If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator along with insert (or copy):

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

int main(int argc, char** argv) {
  std::vector<int> dest{1,2,3,4,5};
  std::vector<int> src{6,7,8,9,10};

  // Move elements from src to dest.
  // src is left in undefined but safe-to-destruct state.
  dest.insert(
      dest.end(),
      std::make_move_iterator(src.begin()),
      std::make_move_iterator(src.end())
    );

  // Print out concatenated vector.
  std::copy(
      dest.begin(),
      dest.end(),
      std::ostream_iterator<int>(std::cout, "\n")
    );

  return 0;
}

This will not be more efficient for the example with ints, since moving them is no more efficient than copying them, but for a data structure with optimized moves, it can avoid copying unnecessary state:

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

int main(int argc, char** argv) {
  std::vector<std::vector<int>> dest{{1,2,3,4,5}, {3,4}};
  std::vector<std::vector<int>> src{{6,7,8,9,10}};

  // Move elements from src to dest.
  // src is left in undefined but safe-to-destruct state.
  dest.insert(
      dest.end(),
      std::make_move_iterator(src.begin()),
      std::make_move_iterator(src.end())
    );

  return 0;
}

After the move, src's element is left in an undefined but safe-to-destruct state, and its former elements were transfered directly to dest's new element at the end.

Select Pandas rows based on list index

Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:

df[df.index.isin([1,3])]

PS: You figure out the reason

enter image description here

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

How do I download a binary file over HTTP?

Following solutions will first read the whole content to memory before writing it to disc (for more i/o efficient solutions look at the other answers).

You can use open-uri, which is a one liner

require 'open-uri'
content = open('http://example.com').read

Or by using net/http

require 'net/http'
File.write("file_name", Net::HTTP.get(URI.parse("http://url.com")))

How to set bot's status

.setGame is discontinued. Use:

client.user.setActivity("Game"); 

To set a playing game status.

As an addition, if you were using an earlier version of discord.js, try this:

client.user.setGame("Game");

In newer versions of discord.js, this is deprecated.

How to manage local vs production settings in Django?

I am also working with Laravel and I like the implementation there. I tried to mimic it and combining it with the solution proposed by T. Stone (look above):

PRODUCTION_SERVERS = ['*.webfaction.com','*.whatever.com',]

def check_env():
    for item in PRODUCTION_SERVERS:
        match = re.match(r"(^." + item + "$)", socket.gethostname())
        if match:
            return True

if check_env():
    PRODUCTION = True
else:
    PRODUCTION = False

DEBUG = not PRODUCTION

Maybe something like this would help you.

Sort Dictionary by keys

"sorted" in iOS 9 & xcode 7.3, swift 2.2 is impossible, change "sorted" to "sort", like this:

let dictionary = ["main course": 10.99, "dessert": 2.99, "salad": 5.99]
let sortedKeysAndValues = Array(dictionary).sort({ $0.0 < $1.0 })
print(sortedKeysAndValues)

//sortedKeysAndValues = ["desert": 2.99, "main course": 10.99, "salad": 5.99]

Can I catch multiple Java exceptions in the same catch clause?

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

Set a cookie to never expire

Can't you just say a never ending loop, cookie expires as current date + 1 so it never hits the date it's supposed to expire on because it's always tomorrow? A bit overkill but just saying.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

actual error thrown Message=Unrecognized element 'providers' in web.config so from the web.config file remove the providers section

Run javascript function when user finishes typing instead of on key up?

You guys have heard of closures in javascript ?!

it's very simple and straightforward just compare you current input value with the old value that the setTimeOut function closes over, and voila, you're done.

let timer;
$('#myInput').on('keyup', function() {
  window.clearTimeout(timer);
  // here is the closures javascript magic happens.
  const value = $(this).val();
  timer = setTimeout(() => {
    if(value === $(this).val() && $(this).val()!== ''){
        alert($(this).val());
    }
  }, 500);
})

Box shadow in IE7 and IE8

Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.

It supports box-shadow (except for the inset keyword).

How to determine whether a substring is in a different string

People mentioned string.find(), string.index(), and string.indexOf() in the comments, and I summarize them here (according to the Python Documentation):

First of all there is not a string.indexOf() method. The link posted by Deviljho shows this is a JavaScript function.

Second the string.find() and string.index() actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find() returns -1 while string.index() raises an ValueError.

Unix command-line JSON parser?

You can use this command-line parser (which you could put into a bash alias if you like), using modules built into the Perl core:

perl -MData::Dumper -MJSON::PP=from_json -ne'print Dumper(from_json($_))'

Exec : display stdout "live"

I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log() is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout or stderr with process.stdout.write() instead of console.log(), then you'll get the console output from the spawned process 'as is'.

I saw that solution here: Node.js: printing to console without a trailing newline?

Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).

Extract hostname name from string

This is not a full answer, but the below code should help you:

function myFunction() {
    var str = "https://www.123rf.com/photo_10965738_lots-oop.html";
    matches = str.split('/');
    return matches[2];
}

I would like some one to create code faster than mine. It help to improve my-self also.

Setting device orientation in Swift iOS

Swift 2.2

    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

    if self.window?.rootViewController?.presentedViewController is SignatureLandscapeViewController {

        let secondController = self.window!.rootViewController!.presentedViewController as! SignatureLandscapeViewController

        if secondController.isPresented {

            return UIInterfaceOrientationMask.LandscapeLeft;

        } else {

            return UIInterfaceOrientationMask.Portrait;
        }

    } else {

        return UIInterfaceOrientationMask.Portrait;
    }
}

Concat all strings inside a List<string> using LINQ

You can use Aggregate, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.

You can use Aggregate function with a seed string.

var seed = string.Empty;
var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carAggregate = cars.Aggregate(seed,
                (partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');

you can use string.Join doesn’t care if you pass it an empty collection.

var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carJoin = string.Join(seperator, cars);

How can I completely uninstall nodejs, npm and node in Ubuntu

It is better to remove NodeJS and its modules manually because installation leaves a lot of files, links and modules behind and later this creates problems when we reconfigure another version of NodeJS and its modules.

To remove the files, run the following commands:

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d
rm -rf ~/.npm
rm -rf ~/.node-gyp
sudo rm -rf /opt/local/bin/node
sudo rm -rf /opt/local/include/node
sudo rm -rf /opt/local/lib/node_modules
sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

I have posted a step by step guide with commands on my blog: AMCOS IT Support For Windows and Linux: To completely uninstall node js from Ubuntu.

Is there a real solution to debug cordova apps

The best for me is to attach the Chrome debugger.

To do it, run your app in a emulator or device (using $cordova emulate)

then, open Google Chrome and go to chrome://inspect/

You'll see a list with running apps. Your app should be there. Click on "inspect".

A new window will open with developer tools. There you can click on "console" to check for errors

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

SQL Call Stored Procedure for each Row without using a cursor

DECLARE @SQL varchar(max)=''

-- MyTable has fields fld1 & fld2

Select @SQL = @SQL + 'exec myproc ' + convert(varchar(10),fld1) + ',' 
                   + convert(varchar(10),fld2) + ';'
From MyTable

EXEC (@SQL)

Ok, so I would never put such code into production, but it does satisfy your requirements.

Filter spark DataFrame on string contains

You can use contains (this works with an arbitrary sequence):

df.filter($"foo".contains("bar"))

like (SQL like with SQL simple regular expression whith _ matching an arbitrary character and % matching an arbitrary sequence):

df.filter($"foo".like("bar"))

or rlike (like with Java regular expressions):

df.filter($"foo".rlike("bar"))

depending on your requirements. LIKE and RLIKE should work with SQL expressions as well.

Clearing content of text file using php

Use 'w' and not, 'a'.

if (!$handle = fopen($file, 'w'))

Extension methods must be defined in a non-generic static class

A work-around for people who are experiencing a bug like Nathan:

The on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either.

I'd like to know what causes the bug?

But the work-around is to write a new Extension class (not nested) even in same file and re-build.

Figured that this thread is getting enough views that it's worth passing on (the limited) solution I found. Most people probably tried adding 'static' before google-ing for a solution! and I didn't see this work-around fix anywhere else.

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

How would you implement an LRU cache in Java?

Here is my short implementation, please criticize or improve it!

package util.collection;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Limited size concurrent cache map implementation.<br/>
 * LRU: Least Recently Used.<br/>
 * If you add a new key-value pair to this cache after the maximum size has been exceeded,
 * the oldest key-value pair will be removed before adding.
 */

public class ConcurrentLRUCache<Key, Value> {

private final int maxSize;
private int currentSize = 0;

private ConcurrentHashMap<Key, Value> map;
private ConcurrentLinkedQueue<Key> queue;

public ConcurrentLRUCache(final int maxSize) {
    this.maxSize = maxSize;
    map = new ConcurrentHashMap<Key, Value>(maxSize);
    queue = new ConcurrentLinkedQueue<Key>();
}

private synchronized void freeSpace() {
    Key key = queue.poll();
    if (null != key) {
        map.remove(key);
        currentSize = map.size();
    }
}

public void put(Key key, Value val) {
    if (map.containsKey(key)) {// just heat up that item
        put(key, val);
        return;
    }
    while (currentSize >= maxSize) {
        freeSpace();
    }
    synchronized(this) {
        queue.add(key);
        map.put(key, val);
        currentSize++;
    }
}

public Value get(Key key) {
    return map.get(key);
}
}

Struct like objects in Java

I don't see the harm if you know that it's always going to be a simple struct and that you're never going to want to attach behaviour to it.

Remove header and footer from window.print()

I am sure Adding this code on your css file will solve the problem

<style type="text/css" media="print">
    @page 
    {
        size: auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }
</style>

You may visit this to know more about this

How to enable PHP short tags?

If you are using Ubuntu with Apache+php5, then on current versions there are 2 places where you need to change to short_open_tag = On

  1. /etc/php5/apache2/php.ini - this is for the pages loaded through your web server (Apache)
  2. /etc/php5/cli/php.ini - this configuration is used when you launch your php files from command line, like: php yourscript.php - that goes for manually or cronjob executed php files directly on the server.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

CSS way to horizontally align table

Add to the div style:

width: fit-content;

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

Add number of days to a date

I know this is an old question, but for PHP <5.3 you could try this:

$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Target class controller does not exist - Laravel 8

In Laravel 8 the way routes are specified has changed:

Route::resource('homes', HomeController::class)->names('home.index');

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }