Programs & Examples On #Custom cell

A custom cell is a unique, personalized or subclassed version of some generic cell type.

Using C++ base class constructors?

No, that's not how it is done. Normal way to initialize the base class is in the initialization list :

class A
{
public: 
    A(int val) {}
};

class B : public A
{
public:
  B( int v) : A( v )
  {
  }
};


void main()
{
    B b(10);
}

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Representing EOF in C code?

There is the constant EOF of type int, found in stdio.h. There is no equivalent character literal specified by any standard.

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

Best Practice for Forcing Garbage Collection in C#

Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.

I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0   2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0   2005-05-23
dtype: datetime64[ns]

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

Getting key with maximum value in dictionary?

key, value = max(stats.iteritems(), key=lambda x:x[1])

If you don't care about value (I'd be surprised, but) you can do:

key, _ = max(stats.iteritems(), key=lambda x:x[1])

I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

Javascript .querySelector find <div> by innerTEXT

You could use this pretty simple solution:

Array.from(document.querySelectorAll('div'))
  .find(el => el.textContent === 'SomeText, text continues.');
  1. The Array.from will convert the NodeList to an array (there are multiple methods to do this like the spread operator or slice)

  2. The result now being an array allows for using the Array.find method, you can then put in any predicate. You could also check the textContent with a regex or whatever you like.

Note that Array.from and Array.find are ES2015 features. Te be compatible with older browsers like IE10 without a transpiler:

Array.prototype.slice.call(document.querySelectorAll('div'))
  .filter(function (el) {
    return el.textContent === 'SomeText, text continues.'
  })[0];

What are good examples of genetic algorithms/genetic programming solutions?

I developed a multithreaded swing based simulation of robot navigation through a set of randomized grid terrain of food sources and mines and developed a genetic algorithm based strategy of exploring the optimization of robotic behavior and survival of fittest genes for a robotic chromosome. This was done using charting and mapping of each iteration cycle.

Since, then I have developed even more game behavior. An example application I built recently for myself was a genetic algorithm for solving the traveling sales man problem in route finding in UK taking into account start and goal states as well as one/multiple connection points, delays, cancellations, construction works, rush hour, public strikes, consideration between fastest vs cheapest routes. Then providing a balanced recommendation for the route to take on a given day.

Generally, my strategy is to use POJO based representaton of genes then I apply specific interface implementations for selection, mutation, crossover strategies, and the criteria point. My fitness function then basically becomes a quite complex based on the strategy and criteria I need to apply as a heuristic measure.

I have also looked into applying genetic algorithm into automated testing within code using systematic mutation cycles where the algorithm understands the logic and tries to ascertain a bug report with recommendations for code fixes. Basically, a way to optimize my code and provide recommendations for improvement as well as a way of automating the discovery of new programmatic code. I have also tried to apply genetic algorithms to music production amongst other applications.

Generally, I find evolutionary strategies like most metaheuristic/global optimization strategies, they are slow to learn at first but start to pick up as the solutions become closer and closer to goal state and as long as your fitness function and heuristics are well aligned to produce that convergence within your search space.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Ping site and return result in PHP

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}  

This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

How can I switch views programmatically in a view controller? (Xcode, iPhone)

[self.navigationController pushViewController:someViewController animated:YES];

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

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

How to read GET data from a URL using JavaScript?

try this way

var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

What is the easiest way to get the current day of the week in Android?

Calendar.getInstance().get(Calendar.DAY_OF_WEEK)

or

new GregorianCalendar().get(Calendar.DAY_OF_WEEK);

Just the same as in Java, nothing particular to Android.

Select first occurring element after another element

#many .more.selectors h4 + p { ... }

This is called the adjacent sibling selector.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.

How to add one column into existing SQL Table

alter table table_name add field_name (size);

alter table arnicsc add place number(10);

How to select bottom most rows?

SELECT TOP 10*from TABLE1 ORDER BY ID DESC

Where ID is the primary key of the TABLE1.

How to create EditText accepts Alphabets only in android?

Put code edittext xml file,

   android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

Exception thrown in catch and finally clause

Exceptions in the finally block supersede exceptions in the catch block.

Java Language Specification:

If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:

  • If the finally block completes normally, then the try statement completes abruptly for reason R.

  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php

or some variant thereof.

Groovy / grails how to determine a data type?

You can use the Membership Operator isCase() which is another groovy way:

assert Date.isCase(new Date())

Checkbox angular material checked by default

You need to make sure the checked property to be true inside the component.ts

export class CheckboxComponent implements OnInit {
 checked = true;
}

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

Session 'app' error while installing APK

I could install app on Nexus, but couldn't on Samsung. Nothing helped me except the change of the USB cable.

PostgreSQL error 'Could not connect to server: No such file or directory'

I had that problem when I upgraded Postgres to 9.3.x. The quick fix for me was to downgrade to whichever 9.2.x version I had before (no need to install a new one).

$ ls /usr/local/Cellar/postgresql/
9.2.4
9.3.2
$ brew switch postgresql 9.2.4
$ launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
<open a new Terminal tab or window to reload>
$ psql

"Homebrew install specific version of formula?" offers a much more comprehensive explanation along with alternative ways to fix the problem.

ECMAScript 6 arrow function that returns an object

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

Installing packages in Sublime Text 2

With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:

  1. Always look up a package in the wbond community. There you'll be able to see how many people have installed that package (the more popular, the better) as well as the documentation on the package (if any).
  2. Menu Items under Prefs > Package Control. Here you can install, remove or see a list of all installed packages.
  3. Prefs > Package Settings. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.
  4. CTRL+SHIFT+P. This will bring up a menu where you can look up a lot of the functions your installed packages can do. Just start typing and it will start filtering.

PyCharm shows unresolved references error for valid code

Sorry to bump this question, however I have an important update to make.

You may also want to revert your project interpreter to to Python 2.7.6 if you're using any other version than that This worked for me on my Ubuntu installation of PyCharm 4.04 professional after none of the other recommendations solved my problem.

Resolving tree conflict

Basically, tree conflicts arise if there is some restructure in the folder structure on the branch. You need to delete the conflict folder and use svn clean once. Hope this solves your conflict.

How to import csv file in PHP?

The simplest way I know ( str_getcsv ), it will import a CSV file into an array.

$csv = array_map('str_getcsv', file('data.csv'));

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

What is Haskell used for in the real world?

From Haskell:

Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry.

Basically Haskell can be used to create pretty much anything you would normally create using other general-purpose languages (e.g. C#, Java, C, C++, etc.).

How can I get terminal output in python?

The easiest way is to use the library commands

import commands
print commands.getstatusoutput('echo "test" | wc')

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

How to sort a Ruby Hash by number value?

No idea how you got your results, since it would not sort by string value... You should reverse a1 and a2 in your example

Best way in any case (as per Mladen) is:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
  # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]

If you need a hash as a result, you can use to_h (in Ruby 2.0+)

metrics.sort_by {|_key, value| value}.to_h
  # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

string encoding and decoding?

Guessing at all the things omitted from the original question, but, assuming Python 2.x the key is to read the error messages carefully: in particular where you call 'encode' but the message says 'decode' and vice versa, but also the types of the values included in the messages.

In the first example string is of type unicode and you attempted to decode it which is an operation converting a byte string to unicode. Python helpfully attempted to convert the unicode value to str using the default 'ascii' encoding but since your string contained a non-ascii character you got the error which says that Python was unable to encode a unicode value. Here's an example which shows the type of the input string:

>>> u"\xa0".decode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u"\xa0".decode("ascii", "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

In the second case you do the reverse attempting to encode a byte string. Encoding is an operation that converts unicode to a byte string so Python helpfully attempts to convert your byte string to unicode first and, since you didn't give it an ascii string the default ascii decoder fails:

>>> "\xc2".encode("ascii", "ignore")

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "\xc2".encode("ascii", "ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)

What's the best way to share data between activities?

Do what google commands you to do! here: http://developer.android.com/resources/faq/framework.html#3

  • Primitive Data Types
  • Non-Persistent Objects
  • Singleton class - my favorite :D
  • A public static field/method
  • A HashMap of WeakReferences to Objects
  • Persistent Objects (Application Preferences, Files, contentProviders, SQLite DB)

Is it possible to write to the console in colour in .NET?

Yes. See this article. Here's an example from there:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");

enter image description here

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

How to check if an email address is real or valid using PHP

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

How can I change the color of AlertDialog title and the color of the line under it

If you are creating custom Layout for alert dialog

then you may add like this way easily to change the color

<LinearLayout
    android:id="@+id/DialogTitleBorder"
    android:layout_width="fill_parent"
    android:layout_height="1dip"
    android:layout_below="@id/mExitDialogDesc"
    android:background="#4BBAE3"            <!--change color easily -->
    >

</LinearLayout>

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Another option is to add a new OnClickListener as parameter in setOnClickListener() and overriding the onClick()-method:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards)); 
exit_button = ((Button)this.findViewById(R.id.Button_Exit));

// Add onClickListener to mycards_button
mycards_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Start new activity
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
    }
});

// Add onClickListener to exit_button
exit_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Display alertDialog
        MyAlertDialog();
    }
});

Getting the 'external' IP address in Java

How about this? It's simple and worked the best for me :)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


public class IP {
    public static void main(String args[]) {
        new IP();
    }

    public IP() {
        URL ipAdress;

        try {
            ipAdress = new URL("http://myexternalip.com/raw");

            BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));

            String ip = in.readLine();
            System.out.println(ip);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

Subtracting two lists in Python

Python 2.7+ and 3.0 have collections.Counter (a.k.a. multiset). The documentation links to Recipe 576611: Counter class for Python 2.5:

from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter

class Counter(dict):
    '''Dict subclass for counting hashable objects.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    '''

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''        
        self.update(iterable, **kwds)

    def __missing__(self, key):
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

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

        '''        
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        return nlargest(n, self.iteritems(), key=itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        If an element's count has been set to zero or is a negative number,
        elements() will ignore it.

        '''
        for elem, count in self.iteritems():
            for _ in repeat(None, count):
                yield elem

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''        
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def copy(self):
        'Like dict.copy() but returns a Counter instance instead of a dict.'
        return Counter(self)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})


        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] + other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] - other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _max = max
        result = Counter()
        for elem in set(self) | set(other):
            newcount = _max(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in ifilter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result


if __name__ == '__main__':
    import doctest
    print doctest.testmod()

Then you can write

 a = Counter([0,1,2,1,0])
 b = Counter([0, 1, 1])
 c = a - b
 print list(c.elements())  # [0, 2]

Showing an image from an array of images - Javascript

<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}

glm rotate usage in Opengl

GLM has good example of rotation : http://glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));

Redirect to Action in another controller

This should work

return RedirectToAction("actionName", "controllerName", null);

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

As others pointed out, this message is coming from your shell prompt. The problem is that in a freshly created repository HEAD (.git/HEAD) points to a ref that doesn't exist yet.

% git init test
Initialized empty shared Git repository in /Users/jhelwig/tmp/test/.git/
% cd test
% cat .git/HEAD
ref: refs/heads/master
% ls -l .git/refs/heads
total 0
% git rev-parse HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

It looks like rev-parse is being used without sufficient error checking before-hand. After the first commit has been created .git/refs/heads looks a bit different and git rev-parse HEAD will no longer fail.

% ls -l .git/refs/heads
total 4
-rw------- 1 jhelwig staff 41 Oct 14 16:07 master
% git rev-parse HEAD
af0f70f8962f8b88eef679a1854991cb0f337f89

In the function that updates the Git information for the rest of my shell prompt (heavily modified version of wunjo prompt theme for ZSH), I have the following to get around this:

zgit_info_update() {
    zgit_info=()

    local gitdir=$(git rev-parse --git-dir 2>/dev/null)
    if [ $? -ne 0 ] || [ -z "$gitdir" ]; then
        return
    fi

    # More code ...
}

Shorten string without cutting words in JavaScript

If you (already) using a lodash library, there is a function called truncate which can be used for trimming the string.

Based on the example on the docs page

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
});
// => 'hi-diddly-ho there,...'

Writing html form data to a txt file without the use of a webserver

You can use JavaScript:

<script type ="text/javascript">
 function WriteToFile(passForm) {

    set fso = CreateObject("Scripting.FileSystemObject");  
    set s = fso.CreateTextFile("C:\test.txt", True);
    s.writeline(document.passForm.input1.value);
    s.writeline(document.passForm.input2.value);
    s.writeline(document.passForm.input3.value);
    s.Close();
 }
  </script>

If this does not work, an alternative is the ActiveX object:

<script type = "text/javascript">
function WriteToFile(passForm)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine(document.passForm.input.value);
s.Close();
}
</script>

Unfortunately, the ActiveX object, to my knowledge, is only supported in IE.

How to do join on multiple criteria, returning all combinations of both criteria

SELECT  aa.*,
        bb.meal
FROM    table1 aa
        INNER JOIN table2 bb
            ON aa.tableseat = bb.tableseat AND
                aa.weddingtable = bb.weddingtable
        INNER JOIN
        (
            SELECT  a.tableSeat
            FROM    table1 a
                    INNER JOIN table2 b
                        ON a.tableseat = b.tableseat AND
                            a.weddingtable = b.weddingtable
            WHERE b.meal IN ('chicken', 'steak')
            GROUP by a.tableSeat
            HAVING COUNT(DISTINCT b.Meal) = 2
        ) c ON aa.tableseat = c.tableSeat

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

source of historical stock data

We have purchased 12 years of intraday data from Kibot.com and are pretty satisfied with the quality.

As for storage requirements: 12 years of 1-minute data for all USA equities (more than 8000 symbols) is about 100GB.

With tick-by-tick data situation is little different. If you record time and sales only, that would be about 30GB of data per month for all USA equities. If you want to store bid / ask changes together with transactions, you can expect about 150GB per month.

I hope this helps. Please let me know if there is anything else I can assist you with.

Converting Secret Key into a String and Vice Versa

try this, it's work without Base64 ( that is included only in JDK 1.8 ), this code run also in the previous java version :)

private static String SK = "Secret Key in HEX";


//  To Encrupt

public static String encrypt( String Message ) throws Exception{

    byte[] KeyByte = hexStringToByteArray( SK);
    SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");

    Cipher c = Cipher.getInstance("DES","SunJCE");
    c.init(1, k);
    byte mes_encrypted[] = cipher.doFinal(Message.getBytes());

    String MessageEncrypted = byteArrayToHexString(mes_encrypted);
    return MessageEncrypted;
}

//  To Decrypt

public static String decrypt( String MessageEncrypted )throws Exception{

    byte[] KeyByte = hexStringToByteArray( SK );
    SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");

    Cipher dcr =  Cipher.getInstance("DES","SunJCE");
    dc.init(Cipher.DECRYPT_MODE, k);
    byte[] MesByte  = hexStringToByteArray( MessageEncrypted );
    byte mes_decrypted[] = dcipher.doFinal( MesByte );
    String MessageDecrypeted = new String(mes_decrypted);

    return MessageDecrypeted;
}

public static String byteArrayToHexString(byte bytes[]){

    StringBuffer hexDump = new StringBuffer();
    for(int i = 0; i < bytes.length; i++){
    if(bytes[i] < 0)
    {   
        hexDump.append(getDoubleHexValue(Integer.toHexString(256 - Math.abs(bytes[i]))).toUpperCase());
    }else
    {
        hexDump.append(getDoubleHexValue(Integer.toHexString(bytes[i])).toUpperCase());
    }
    return hexDump.toString();

}



public static byte[] hexStringToByteArray(String s) {

    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2)
    {   
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
    }
    return data;

} 

How can I create a keystore?

This tutorial:

http://techdroid.kbeanie.com/2010/02/sign-your-android-applications-for.html

was very helpful for me the first time I had to create a keystore. It is simple but the instructions on developer.android.com are a little too brief.

The part I was unsure about was where to save and what name to give the keystore file.

I seems it doesn't matter where you put it just be sure to keep it safe and keep a number of backups. I just put it in my app directory

Name the file "something.keystore" where something can be whatever you want. I used app_name.keystore, where app_name was the name of my app.

The next part was what to name the alias. Again it doesn't seem to matter so again I just used the app_name again. Keep the passwords the same as you used before. Fill out the rest of the fields and you are done.

How can I install packages using pip according to the requirements.txt file from a local directory?

This works for everyone:

pip install -r /path/to/requirements.txt

How to change the text of a label?

$('#<%= lblVessel.ClientID %>').html('New Text');

ASP.net Label will be rendered as a span in the browser. so user 'html'.

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Run the following on the command line :

$ mysql.server start

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

In a URL, should spaces be encoded using %20 or +?

When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Solution for Netbeans 8.02 and 8.1 IDE and JBOSS EAP 6.4:

  1. From the services tab of Netbeans, add JBOSS server to your "servers" node.
  2. If you are using MAVEN, netbeans compiles files and maven copies files to ./target directory. You need to create a symbolic link from .\target to JBOSS_HOME\standalone\deployments. Under windows, an example command would be

    cd %JBOSS_HOME%\standalone\deployments mklink /d MyWebApplication.war %PROJECTS_HOME%\MyWebApplication\target\MyWebApplication-1.0.0

    The above creates a symbolic link from %JBOSS_HOME%\standalone\deployments\MyWebApplication.war to \target\MyWebApplication-1.0.0 which is where maven transfers all files after compilation, or after a jsp, html or any other file changes.

  3. Last think to do is to create a CentralManagement.war.dodeploy file in %JBOSS_HOME%\standalone\deployments. This file will tell JBOSS to deploy the war "file" as a web application

What's the purpose of git-mv?

git mv oldname newname

is just shorthand for:

mv oldname newname
git add newname
git rm oldname

i.e. it updates the index for both old and new paths automatically.

How do I find the location of Python module sources?

In an IDE like Spyder, import the module and then run the module individually. enter image description here

Bootstrap 4 align navbar items to the right

It's little change in boostrap 4. To align navbar to right side, you've to make only two changes. they are:

  1. in navbar-nav class add w-100 as navbar-nav w-100 to make width as 100
  2. in nav-item dropdown class add ml-auto as nav-item dropdown ml-auto to make margin left as auto.

If you didn't understand, please refer the image that i've attached to this.

CodePen Link

enter image description here

Full source code

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav w-100">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item dropdown ml-auto">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>  
  </div>
</nav>

How to convert a string Date to long millseconds

  • First convert string to java.util.Date using date formatter
  • Use getTime() to obtain count of millisecs from date

How to know when a web page was last updated?

01. Open the page for which you want to get the information.

02. Clear the address bar [where you type the address of the sites]:

and type or copy/paste from below:

javascript:alert(document.lastModified)

03. Press Enter or Go button.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

http://msdn.microsoft.com/en-us/library/as4zy2kc.aspx

How to check variable type at runtime in Go language

What's wrong with

func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)

and so on?

Properly close mongoose's connection once you're done

The other answer didn't work for me. I had to use mongoose.disconnect(); as stated in this answer.

Align a div to center

This worked for me.

I included an unordered list on my page twice. One div class="menu" id="vertical" the other to be centered was div class="menu" id="horizontal". Since the list was floated left, I needed an inner div to center it. See below.

<div class=menu id="horizontal">
<div class="fix">
  Centered stuff
</div>
</div>

.menu#horizontal { display: block;  float: left; margin: 0px; padding: 0 10px; position: relative; left: 50%; }
#fix { float: right; position: relative; left: -50%; margin: 0px auto; }

Easy way to test a URL for 404 in PHP?

this is just and slice of code, hope works for you

            $ch = @curl_init();
            @curl_setopt($ch, CURLOPT_URL, 'http://example.com');
            @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
            @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            @curl_setopt($ch, CURLOPT_TIMEOUT, 10);

            $response       = @curl_exec($ch);
            $errno          = @curl_errno($ch);
            $error          = @curl_error($ch);

                    $response = $response;
                    $info = @curl_getinfo($ch);
return $info['http_code'];

How can I tell when HttpClient has timed out?

_httpClient = new HttpClient(handler) {Timeout = TimeSpan.FromSeconds(5)};

is what I usually do, seems to work out pretty good for me, its especially good when using proxies.

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

Can't connect to localhost on SQL Server Express 2012 / 2016

After doing the steps which were mentioned by @Ravindra Bagale, Try this step. Server name: localhost\{Instance name you were gave}

enter image description here

Encoding an image file with base64

I'm not sure I understand your question. I assume you are doing something along the lines of:

import base64

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.

Edit: Ok, here is an update after you have edited your original question.

First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).

That being said, you can use cStringIO to create such an object from a memory buffer:

import cStringIO
import PIL.Image

# assume data contains your decoded image
file_like = cStringIO.StringIO(data)

img = PIL.Image.open(file_like)
img.show()

SQL Server dynamic PIVOT query?

Updated version for SQL Server 2017 using STRING_AGG function to construct the pivot column list:

create table temp
(
    date datetime,
    category varchar(3),
    amount money
);

insert into temp values ('20120101', 'ABC', 1000.00);
insert into temp values ('20120201', 'DEF', 500.00);
insert into temp values ('20120201', 'GHI', 800.00);
insert into temp values ('20120210', 'DEF', 700.00);
insert into temp values ('20120301', 'ABC', 1100.00);


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = (SELECT STRING_AGG(category,',') FROM (SELECT DISTINCT category FROM temp WHERE category IS NOT NULL)t);

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p ';

execute(@query);

drop table temp;

Tesseract OCR simple example

A simple example of testing Tesseract OCR in C#:

    public static string GetText(Bitmap imgsource)
    {
        var ocrtext = string.Empty;
        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
        {
            using (var img = PixConverter.ToPix(imgsource))
            {
                using (var page = engine.Process(img))
                {
                    ocrtext = page.GetText();
                }
            }
        }

        return ocrtext;
    }

Info: The tessdata folder must exist in the repository: bin\Debug\

How do you manually execute SQL commands in Ruby On Rails using NuoDB

For me, I couldn't get this to return a hash.

results = ActiveRecord::Base.connection.execute(sql)

But using the exec_query method worked.

results = ActiveRecord::Base.connection.exec_query(sql)

How do I delete an entity from symfony2

From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>
    {% for guest in guests %}
    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
    {% endfor %}
</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.

Make an html number input always display 2 decimal places

Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.

Facebook key hash does not match any stored key hashes

After hours of trying I've finally found a solution.

  1. Delete any app on the website of Facebook (developers.facebook.com)
  2. Delete the file debug.keystore under C:\Users\yourUserName\.android
  3. Generate a new key (by running your app again)
  4. Create a new app on developers.facebook.com and add the new hash key
  5. Re-run your app
  6. Succes!

Selected value for JSP drop down using JSTL

Maybe I don't completely understand the accepted answer so it didn't work for me.

What i did was simply to check if the variable is null, assign it to a known value from my database. Which seems to be similar to the accepted answer whereby you first declare an known value and set it to selected

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
    </c:forEach>
</select>

because none of the options are selected, thus item = null

<%
    if(item == null){
        item = "selectedDept"; //known value from your database
    }
%>

This way if the user then selects another option, my IF clause will not catch it and assign to the fixed value that was declared at the start. My concept could be wrong here but it works for me

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

Use 'class' or 'typename' for template parameters?

As far as I know, it doesn't matter which one you use. They're equivalent in the eyes of the compiler. Use whichever one you prefer. I normally use class.

Jquery UI Datepicker not displaying

it's the css file in the new one doesn't work. Try to include the old 1.7.* css file on your header too, and try again.

Also, did you try to do a .datepicker( "show" ) right after it constructed?

YAML Multi-Line Arrays

have you tried this?

-
  name: Jack
  age: 32
-
  name: Claudia
  age: 25

I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}] (I use the YAML Ruby class).

ssh-copy-id no identities found error

The simplest way is to:

ssh-keygen
[enter]
[enter]
[enter]

cd ~/.ssh
ssh-copy-id -i id_rsa.pub USERNAME@SERVERTARGET

Att:

Its very very simple.

In manual of "ss-keygen" explains:

"DESCRIPTION ssh-keygen generates, manages and converts authentication keys for ssh(1). ssh-keygen can create RSA keys for use by SSH protocol version 1 and DSA, ECDSA or RSA keys for use by SSH protocol version 2. The type of key to be generated is specified with the -t option. If invoked without any arguments, ssh-keygen will generate an RSA key for use in SSH protocol 2 connections."

Insert current date in datetime format mySQL

I believe, you need to change your code little bit like follows alongside with your database filed type.

mysql_query("INSERT INTO table (`dateposted`) VALUES ($datetime)");

Hope, will work perfectly.

How to configure the web.config to allow requests of any length

I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.

How to print something when running Puppet client?

If, like me, you don't have access to the puppet master and need to print debug logs to inspect variables on your puppet client machine, you can try writing to a file from your puppet code itself:

file { '/tmp/puppet_debug.log':
  content => inline_template('<%= @variable_x.to_s %>'),
}

Is it a good practice to place C++ definitions in header files?

I think that it's absolutely absurd to put ALL of your function definitions into the header file. Why? Because the header file is used as the PUBLIC interface to your class. It's the outside of the "black box".

When you need to look at a class to reference how to use it, you should look at the header file. The header file should give a list of what it can do (commented to describe the details of how to use each function), and it should include a list of the member variables. It SHOULD NOT include HOW each individual function is implemented, because that's a boat load of unnecessary information and only clutters the header file.

Tomcat Server Error - Port 8080 already in use

Open below application

C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Apache Tomcat 8.5 Tomcat8

right click on Apache tomcat in system tray and click on stop services

Run your application from eclipse.

http://siddartech.com/apache/apachi-tomcat-server-already-in-use/

Node JS Promise.all and forEach

Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.

/**
 * 
 * @param items An array of items.
 * @param fn A function that accepts an item from the array and returns a promise.
 * @returns {Promise}
 */
function forEachPromise(items, fn) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item);
        });
    }, Promise.resolve());
}

And use it like this:

var items = ['a', 'b', 'c'];

function logItem(item) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            resolve();
        })
    });
}

forEachPromise(items, logItem).then(() => {
    console.log('done');
});

We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.

function forEachPromise(items, fn, context) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item, context);
        });
    }, Promise.resolve());
}

Your promise function would look like this:

function logItem(item, context) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            context.itemCount++;
            resolve();
        })
    });
}

Refused to load the script because it violates the following Content Security Policy directive

It was solved with:

script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';

jquery disable form submit on enter

The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:

Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) ** (ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )

So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.

<form id="myform" method="post">
  <input name="fav_color" type="text">
  <input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>

<script>
 $('#form-button-submit').click(function(){
    $('#myform').submit();
  });
</script>

Demo: http://codepen.io/anon/pen/fxeyv?editors=101

** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.

Fit Image into PictureBox

First off, in order to have any image "resize" to fit a picturebox, you can set the PictureBox.SizeMode = PictureBoxSizeMode.StretchImage

If you want to do clipping of the image beforehand (i.e. cut off sides or top and bottom), then you need to clearly define what behavior you want (start at top, fill the height of the pciturebox and crop the rest, or start at the bottom, fill the height of the picturebox to the top, etc), and it should be fairly simple to use the Height / Width properties of both the picturebox and the image to clip the image and get the effect you are looking for.

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

How do you get the length of a list in the JSF expression language?

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

In class MyBean:
public int getSomelistLength() { return this.somelist.length; }

In your JSF page:
#{MyBean.somelistLength}

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

In JSF page:
#{ fn:length(MyBean.somelist) }

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

How to read string from keyboard using C?

The following code can be used to read the input string from a user. But it's space is limited to 64.

char word[64] = { '\0' };  //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
    scanf_s("%c", &word[i++], 1);
}

Reading a string with spaces with sscanf

You want the %c conversion specifier, which just reads a sequence of characters without special handling for whitespace.

Note that you need to fill the buffer with zeroes first, because the %c specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):

memset(buffer, 0, 200);
sscanf("19 cool kid", "%d %199c", &age, buffer);

Easy way to prevent Heroku idling?

If you have access to a unix server that's always up, you can set a cron job to GET your website. Under the new terms of the free plan, you'll probably want to disable the GETs in the night hours, using a line in your crontab like this:

*/20 8-22 * * * /usr/bin/curl domain.com &> /dev/null

This instructs curl to GET domain.com every 20 minutes between the hours of 8 and 22.

Be aware that

  1. Not everyone who wants to see your website lives in your timezone and
  2. Your site may receive other requests in the middle of the night, waking up your dyno and causing another hour of usage time for each request. Even if no one else knows your domain, there are bots and crawlers that are active all the time. Therefore, it's advisable to set the process defined in your crontab to be active for only 14 to 16 hours to provide a buffer against these wake-ups

Also, make sure your system time is set up properly so that the down-time window happens when you expect it to.

How to get Top 5 records in SqLite?

TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).

select * from `Table_Name` LIMIT 5;

How to share data between different threads In C# using AOP?

When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.

  Worker myWorker = new Worker( /* arguments */ );

  Thread myThread = new Thread(new ThreadStart(myWorker.doWork));

  myThread.Start();

Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How to change values in a tuple?

Frist, ask yourself why you want to mutate your tuple. There is a reason why strings and tuple are immutable in Ptyhon, if you want to mutate your tuple then it should probably be a list instead.

Second, if you still wish to mutate your tuple then you can convert your tuple to a list then convert it back, and reassign the new tuple to the same variable. This is great if you are only going to mutate your tuple once. Otherwise, I personally think that is counterintuitive. Because It is essentially creating a new tuple and every time if you wish to mutate the tuple you would have to perform the conversion. Also If you read the code it would be confusing to think why not just create a list? But it is nice because it doesn't require any library.

I suggest using mutabletuple(typename, field_names, default=MtNoDefault) from mutabletuple 0.2. I personally think this way is a more intuitive and readable. The personal reading the code would know that writer intends to mutate this tuple in the future. The downside compares to the list conversion method above is that this requires you to import additional py file.

from mutabletuple import mutabletuple

myTuple = mutabletuple('myTuple', 'v w x y z')
p = myTuple('275', '54000', '0.0', '5000.0', '0.0')
print(p.v) #print 275
p.v = '200' #mutate myTuple
print(p.v) #print 200

TL;DR: Don't try to mutate tuple. if you do and it is a one-time operation convert tuple to list, mutate it, turn list into a new tuple, and reassign back to the variable holding old tuple. If desires tuple and somehow want to avoid listand want to mutate more than once then create mutabletuple.

Add key value pair to all objects in array

The map() function is a best choice for this case


tl;dr - Do this:

const newArr = [
  {name: 'eve'},
  {name: 'john'},
  {name: 'jane'}
].map(v => ({...v, isActive: true}))

The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.


Alternatives:

const initialArr = [
      {name: 'eve'},
      {name: 'john'},
      {name: 'jane'}
    ]

const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))

// Results of newArr1 and newArr2 are the same

Add a key value pair conditionally

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))

What if I don't want to add new field at all if the condition is false?

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(v => {
  return v.value > 1 ? {...v, isActive: true} : v 
})

Adding WITH modification of the initial array

const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});

This is probably not a best idea, but in a real life sometimes it's the only way.


Questions

  • Should I use a spread operator(...), or Object.assign and what's the difference?

Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)

  • Can I use function keyword instead of =>?

Sure you can. The fat arrow (=>) functions play a bit different with this, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.

  • What Actually happens inside map function: .map(v => ({...v, isActive: true})?

Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array. We tell to the .map() function following: take current value(v which is an object), take all key-value pairs away from v andput it inside a new object({...v}), but also add property isActive and set it to true ({...v, isActive: true}) and then return the result. Btw, if original object contains isActive filed it will be overwritten. Object.assign works in a similar way.

  • Can I add more then one field at a time

Yes.

[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
  • What I should not do inside .map() method

You shouldn't do any side effects[link 1, link 2], but apparently you can.

Also be noticed that map() iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).

  • Can I extract map's callback to a separate function?

Sure you can.

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(addIsActive)

function addIsActive(v) {
    return {...v, isActive: true}
}
  • What's wrong with old good for loop?

Nothing is wrong with for, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:

const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
 arr[i].isActive = true
}
  • What also i should learn

It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

Convert JsonObject to String

you can use

JsonObject.getString("msg"); 

How can I unstage my files again after making a local commit?

Use:

git reset HEAD^

That does a "mixed" reset by default, which will do what you asked; put foo.java in unstaged, removing the most recent commit.

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

Peak memory usage of a linux/unix process

Re-inventing the wheel, with hand made bash script. Quick and clean.

My use case: I wanted to monitor a linux machine which has less RAM and wanted to take a snapshot of per container usage when it runs under heavy usage.

#!/usr/bin/env bash

threshold=$1

echo "$(date '+%Y-%m-%d %H:%M:%S'): Running free memory monitor with threshold $threshold%.."

while(true)
    freePercent=`free -m | grep Mem: | awk '{print ($7/$2)*100}'`    
  do

  if (( $(awk 'BEGIN {print ("'$freePercent'" < "'$threshold'")}') ))
  then
       echo "$(date '+%Y-%m-%d %H:%M:%S'): Free memory $freePercent% is less than $threshold%"
       free -m
       docker stats --no-stream
       sleep 60  
       echo ""  
  else
       echo "$(date '+%Y-%m-%d %H:%M:%S'): Sufficient free memory available: $freePercent%"
  fi
  sleep 30

done

Sample output:

2017-10-12 13:29:33: Running free memory monitor with threshold 30%..

2017-10-12 13:29:33: Sufficient free memory available: 69.4567%

2017-10-12 13:30:03: Sufficient free memory available: 69.4567%

2017-10-12 16:47:02: Free memory 18.9387% is less than 30%

your custom command output

Best way to check if a URL is valid

You can use a native Filter Validator

filter_var($url, FILTER_VALIDATE_URL);

Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Example:

if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Not a valid URL');
}

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Import CSV to SQLite

As some websites and other article specifies, its simple have a look to this one. https://www.sqlitetutorial.net/sqlite-import-csv/

We don't need to specify the separator for csv file, becayse csv means comma separated. sqlite> .separator , no need of this line.

sqlite> create table cities(name, population);
sqlite> .mode csv
sqlite> .import c:/sqlite/city_no_header.csv cities

This will work flawlessly :)

PS: My cities.csv with header.


name,population
Abilene,115930
Akron,217074
Albany,93994
Albuquerque,448607
Alexandria,128283
Allentown,106632
Amarillo,173627
Anaheim,328014

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

With C++11 or higher you can use find() and find_first_of()

Example using find to find a single char:

#include <string>
std::string name = "Aaah";
size_t found_index = name.find('a');
if (found_index != std::string::npos) {
    // Found string containing 'a'
}

Example using find to find a full string & starting from position 5:

std::string name = "Aaah";
size_t found_index = name.find('h', 3);
if (found_index != std::string::npos) {
    // Found string containing 'h'
}

Example using the find_first_of() and only the first char, to search at the start only:

std::string name = ".hidden._di.r";
size_t found_index = name.find_first_of('.');
if (found_index == 0) {
    // Found '.' at first position in string
}

Good luck!

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

Google Chrome default opening position and size

First, close all instances of Google Chrome. There should be no instances of chrome.exe running in the Windows Task Manager. Then

  • Go to %LOCALAPPDATA%\Google\Chrome\User Data\Default\.
  • Open the file "Preferences" in a text editor like Notepad.
  • First, resave the file to something like "Preference - Old" without any extension (i.e. no .txt). This will serve as a backup, should something go wrong.
  • Look for a section called "browser." Inside that section, you should find a subsection called window_placement. Under window_placement you will see things like "bottom", "left", "right", etc. with numbers after them.

You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.

ssh: check if a tunnel is alive

This is my test. Hope it is useful.

# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND

# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   pkill -f -x "$COMMAND"
   $COMMAND
fi

Simplest way to do a recursive self-join?

WITH    q AS 
        (
        SELECT  *
        FROM    mytable
        WHERE   ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q

By adding the ordering condition, you can preserve the tree order:

WITH    q AS 
        (
        SELECT  m.*, CAST(ROW_NUMBER() OVER (ORDER BY m.PersonId) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    mytable m
        WHERE   ParentID IS NULL
        UNION ALL
        SELECT  m.*,  q.bc + '.' + CAST(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.PersonID) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN
        FROM    mytable m
        JOIN    q
        ON      m.parentID = q.PersonID
        )
SELECT  *
FROM    q
ORDER BY
        bc

By changing the ORDER BY condition you can change the ordering of the siblings.

How to send email in ASP.NET C#

Just pass parameter like body - The content(query) from the customer
subject - subject that defined in mail subject
username - nothing name anything
mail - mail (required)

   public static bool SendMail(String body, String subject, string username, String mail)
    {
        bool isSendSuccess = false;
        try
        {
            var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
            var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
            var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
            var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();


            MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
                new MailAddress(mail, username));
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;

            var client = new SmtpClient();
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
            client.Host = smtpHost;
            client.EnableSsl = false;
            client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
            client.Send(message);
            isSendSuccess = true;
        }
        catch (Exception ex)
        {
            throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
        }

        return isSendSuccess;
    }

if your using go daddy server this work . add this in web.config

  <appSettings>
    ---other ---setting

    <add key="FromEmailAddress" value="[email protected]" />
    <add key="FromEmailDisplayName" value="anyname" />
    <add key="FromEmailPassword" value="mypassword@" />
    <add key="SMTPHost" value="relay-hosting.secureserver.net" />
    <add key="SMTPPort" value="25" />

</appSettings>

if you are using localhost or vps server change this configuration to this

 <appSettings>
    ---other ---setting

    <add key="FromEmailAddress" value="[email protected]" />
    <add key="FromEmailDisplayName" value="anyname" />
    <add key="FromEmailPassword" value="mypassword@" />
    <add key="SMTPHost" value="smtp.gmail.com" /> 
    <add key="SMTPPort" value="587" />
</appSettings>

change the code

          client.EnableSsl = true;

if your are using gmail please enable secure app. using this link https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA

Tomcat view catalina.out log file

Try using this:

sudo tail -f /opt/tomcat/logs/catalina.out

update one table with data from another

Use the following block of query to update Table1 with Table2 based on ID:

UPDATE Table1, Table2 
SET Table1.DataColumn= Table2.DataColumn
where Table1.ID= Table2.ID;

This is the easiest and fastest way to tackle this problem.

How to host material icons offline?

Use material-design-icons-iconfont

Full disclosure, I'm the author of this package

Google's material-design-icons project is on low maintenance and out of date for a while. There's a gap between the version in https://material.io/icons/ and the version in material-design-icons.

I've created material-design-icons-iconfont to address these major issues:

  • material-design-icons jams npm install - all irrelevant svg/xml/... files has been removed
  • Font files are always up-to-date straight from Google Fonts CDN
  • Support for scss

Install via npm

npm install material-design-icons-iconfont --save

It depends on how you pack your web application (webpack/gulp/bower/...), you'll need to import the .css/.scss file (and might change the relative fonts path)


Import Using SCSS

Import in one of your sass files

$material-design-icons-font-path: '~material-design-icons-iconfont/dist/fonts/';
@import '~material-design-icons-iconfont/src/material-design-icons';

Later on, reference your desired icon <i class="material-icons"> + icon-id + </i>

<i class="material-icons">contact_support</i>

Demo page

It comes with a light demo page to assist searching and copy-pasting fonts

image

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

You are not seeding the number.

Use This:

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0)));
    cout << (rand() % 100) << endl;
    return 0;
}

You only need to seed it once though. Basically don't seed it every random number.

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
        END 
    AS BIT)
    return @result
END
GO

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

Regex that matches integers in between whitespace or start/end of string only

This worked in my case where I needed positive and negative integers that should NOT include zero-starting numbers like 01258 but should of course include 0

^(-?[1-9]+\d*)$|^0$

Example of valid values: "3", "-3", "0", "-555", "945465464654"

Example of not valid values: "0.0", "1.0", "0.7", "690.7", "0.0001", "a", "", " ", ".", "-", "001", "00.2", "000.5", ".3", "3.", " -1", "+100", "--1", "-.1", "-0", "00099", "099"

How to install pip for Python 3 on Mac OS X?

  1. brew install python3
  2. create alias in your shell profile

    • eg. alias pip3="python3 -m pip" in my .zshrc

? ~ pip3 --version

pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

Add string in a certain position in Python

As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use .join() using an empty string.

>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

How to delete a localStorage item when the browser window/tab is closed?

You can make use of the beforeunload event in JavaScript.

Using vanilla JavaScript you could do something like:

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};

That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.

NOTE: The onbeforeunload method should return a string.

How to combine GROUP BY and ROW_NUMBER?

Undoubtly this can be simplified but the results match your expectations.

The gist of this is to

  • Calculate the maximum price in a seperate CTE for each t2ID
  • Calculate the total price in a seperate CTE for each t2ID
  • Combine the results of both CTE's

SQL Statement

;WITH MaxPrice AS ( 
    SELECT  t2ID
            , t1ID
    FROM    (       
                SELECT  t2.ID AS t2ID
                        , t1.ID AS t1ID
                        , rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
                FROM    @t1 t1
                        INNER JOIN @relation r ON r.t1ID = t1.ID        
                        INNER JOIN @t2 t2 ON t2.ID = r.t2ID
            ) maxt1
    WHERE   maxt1.rn = 1                            
)
, SumPrice AS (
    SELECT  t2ID = t2.ID
            , Price = SUM(Price)
    FROM    @t1 t1
            INNER JOIN @relation r ON r.t1ID = t1.ID
            INNER JOIN @t2 t2 ON t2.ID = r.t2ID
    GROUP BY
            t2.ID           
)           
SELECT  t2.ID
        , t2.Name
        , t2.Orders
        , mp.t1ID
        , t1.ID
        , t1.Name
        , sp.Price
FROM    @t2 t2
        INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
        INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
        INNER JOIN @t1 t1 ON t1.ID = mp.t1ID

How do I make CMake output into a 'bin' dir?

English is not my native language; please excuse typing errors.

use this line config :
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/)
place your any CMakeLists.txt project.
this ${PROJECT_SOURCE_DIR} is your current source directory where project place .
and if wander why is ${EXECUTABLE_OUTPUT_PATH}
check this file CMakeCache.txt then search the key word output path,
all the variables define here , it would give a full explanation of the project all setting·

How to Handle Button Click Events in jQuery?

 $("#btnSubmit").click(function(){
        alert("button");
    });    

Colspan all columns

I have IE 7.0, Firefox 3.0 and Chrome 1.0

The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.

Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.

This does NOT work when the table-layout CSS property is set to fixed.

Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic. Hope this helps.

How to disable right-click context-menu in JavaScript

You can't rely on context menus because the user can deactivate it. Most websites want to use the feature to annoy the visitor.

postgresql port confusion 5433 or 5432?

Quick answer on OSX, set your environment variables.

>export PGHOST=localhost

>export PGPORT=5432

Or whatever you need.

How to create query parameters in Javascript?

Zabba has provided in a comment on the currently accepted answer a suggestion that to me is the best solution: use jQuery.param().

If I use jQuery.param() on the data in the original question, then the code is simply:

const params = jQuery.param({
    var1: 'value',
    var2: 'value'
});

The variable params will be

"var1=value&var2=value"

For more complicated examples, inputs and outputs, see the jQuery.param() documentation.

How to pass form input value to php function

Make your action empty. You don't need to set the onclick attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.

<?php
if( isset($_GET['submit']) )
{
    //be sure to validate and clean your variables
    $val1 = htmlentities($_GET['val1']);
    $val2 = htmlentities($_GET['val2']);

    //then you can use them in a PHP function. 
    $result = myFunction($val1, $val2);
}
?>

<?php if( isset($result) ) echo $result; //print the result above the form ?>

<form action="" method="get">
    Inserisci number1: 
    <input type="text" name="val1" id="val1"></input>

    <?php echo "ciaoooo"; ?>

    <br></br>
    Inserisci number2:
    <input type="text" name="val2" id="val2"></input>

    <br></br>

    <input type="submit" name="submit" value="send"></input>
</form>

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

In the ActionListener Class you can simply add

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

Pass props to parent component in React.js

This is an example without using the onClick event. I simply pass a callback function to the child by props. With that callback the child call also send data back. I was inspired by the examples in the docs.

Small example (this is in a tsx files, so props and states must be declared fully, I deleted some logic out of the components, so it is less code).

*Update: Important is to bind this to the callback, otherwise the callback has the scope of the child and not the parent. Only problem: it is the "old" parent...

SymptomChoser is the parent:

interface SymptomChooserState {
  // true when a symptom was pressed can now add more detail
  isInDetailMode: boolean
  // since when user has this symptoms
  sinceDate: Date,
}

class SymptomChooser extends Component<{}, SymptomChooserState> {

  state = {
    isInDetailMode: false,
    sinceDate: new Date()
  }

  helloParent(symptom: Symptom) {
    console.log("This is parent of: ", symptom.props.name);
    // TODO enable detail mode
  }

  render() {
    return (
      <View>
        <Symptom name='Fieber' callback={this.helloParent.bind(this)} />
      </View>
    );
  }
}

Symptom is the child (in the props of the child I declared the callback function, in the function selectedSymptom the callback is called):

interface SymptomProps {
  // name of the symptom
  name: string,
  // callback to notify SymptomChooser about selected Symptom.
  callback: (symptom: Symptom) => void
}

class Symptom extends Component<SymptomProps, SymptomState>{

  state = {
    isSelected: false,
    severity: 0
  }

  selectedSymptom() {
    this.setState({ isSelected: true });
    this.props.callback(this);
  }

  render() {
    return (
      // symptom is not selected
      <Button
        style={[AppStyle.button]}
        onPress={this.selectedSymptom.bind(this)}>
        <Text style={[AppStyle.textButton]}>{this.props.name}</Text>
      </Button>
    );
  }
}

Sum the digits of a number

Here is a solution without any loop or recursion but works for non-negative integers only (Python3):

def sum_digits(n):
    if n > 0:
        s = (n-1) // 9    
        return n-9*s
    return 0

Can't connect to MySQL server on 'localhost' (10061) after Installation

The solution that fixed the issue was using the following steps:

In Start Menu, search for "mysql". Among the results, you should see the "MySQL Installer - Community". Run it. MySQL Installer window will show up as shown below. Find "MySQL Server" under Product and click on "Reconfigure" link. MySQL Installer Community

The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.

After the MySQL Installer was finished, I started the MySQL service again.

Android, How can I Convert String to Date?

     import java.text.ParseException;
     import java.text.SimpleDateFormat;
     import java.util.Date;
     public class MyClass 
     {
     public static void main(String args[]) 
     {
     SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

     String dateInString = "Wed Mar 14 15:30:00 EET 2018";

     SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");


     try {

        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatterOut.format(date));

         } catch (ParseException e) {
        e.printStackTrace();
         }
    }
    }

here is your Date object date and the output is :

Wed Mar 14 13:30:00 UTC 2018

14 Mar 2018

Allow scroll but hide scrollbar

It's better, if you use two div containers in HTML .

As Shown Below:

HTML:

<div id="container1">
    <div id="container2">
        // Content here
    </div>
</div>

CSS:

 #container1{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

 #container2{
    height: 100%;
    width: 100%;
    overflow: auto;
    padding-right: 20px;
}

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

How to make a JFrame Modal in Swing java

not sure the contetns of your JFrame, if you ask some input from users, you can use JOptionPane, this also can set JFrame as modal

            JFrame frame = new JFrame();
            String bigList[] = new String[30];

            for (int i = 0; i < bigList.length; i++) {
              bigList[i] = Integer.toString(i);
            }

            JOptionPane.showInputDialog(
                    frame, 
                    "Select a item", 
                    "The List", 
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    bigList,
                    "none");
            }

How can I check for "undefined" in JavaScript?

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined.

You can check the type of the variable:

if (typeof(something) != "undefined") ...

Sometimes you don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then you can just evalue the variable. Example:

if (something) {
  something(param);
}

What causes: "Notice: Uninitialized string offset" to appear?

The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:

 $one="909";
 for($i=0;$i<10;$i++)
    echo ' '.$one[$i];

will show the error. first case u can take the mod of i.. for example

function mod($i,$length){
  $m = $i % $size;
  if ($m > $size)
  mod($m,$size)
  return $m;
}

for($i=0;$i<10;$i++)
{
  $k=mod($i,3);
  echo ' '.$one[$k];
}

or might be it not an array (maybe it was a value and you tried to access it like an array) for example:

$k = 2;
$k[0];

Extract file basename without path and extension in bash

Pure bash, no basename, no variable juggling. Set a string and echo:

p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"

Output:

foo

Note: the bash extglob option must be "on", (Ubuntu sets extglob "on" by default), if it's not, do:

shopt -s extglob

Walking through the ${p//+(*\/|.*)}:

  1. ${p -- start with $p.
  2. // substitute every instance of the pattern that follows.
  3. +( match one or more of the pattern list in parenthesis, (i.e. until item #7 below).
  4. 1st pattern: *\/ matches anything before a literal "/" char.
  5. pattern separator | which in this instance acts like a logical OR.
  6. 2nd pattern: .* matches anything after a literal "." -- that is, in bash the "." is just a period char, and not a regex dot.
  7. ) end pattern list.
  8. } end parameter expansion. With a string substitution, there's usually another / there, followed by a replacement string. But since there's no / there, the matched patterns are substituted with nothing; this deletes the matches.

Relevant man bash background:

  1. pattern substitution:
  ${parameter/pattern/string}
          Pattern substitution.  The pattern is expanded to produce a pat
          tern just as in pathname expansion.  Parameter is  expanded  and
          the  longest match of pattern against its value is replaced with
          string.  If pattern begins with /, all matches  of  pattern  are
          replaced   with  string.   Normally  only  the  first  match  is
          replaced.  If pattern begins with #, it must match at the begin-
          ning of the expanded value of parameter.  If pattern begins with
          %, it must match at the end of the expanded value of  parameter.
          If string is null, matches of pattern are deleted and the / fol
          lowing pattern may be omitted.  If parameter is @ or *, the sub
          stitution  operation  is applied to each positional parameter in
          turn, and the expansion is the resultant list.  If parameter  is
          an  array  variable  subscripted  with  @ or *, the substitution
          operation is applied to each member of the array  in  turn,  and
          the expansion is the resultant list.
  1. extended pattern matching:
  If the extglob shell option is enabled using the shopt builtin, several
   extended  pattern  matching operators are recognized.  In the following
   description, a pattern-list is a list of one or more patterns separated
   by a |.  Composite patterns may be formed using one or more of the fol
   lowing sub-patterns:

          ?(pattern-list)
                 Matches zero or one occurrence of the given patterns
          *(pattern-list)
                 Matches zero or more occurrences of the given patterns
          +(pattern-list)
                 Matches one or more occurrences of the given patterns
          @(pattern-list)
                 Matches one of the given patterns
          !(pattern-list)
                 Matches anything except one of the given patterns

How can I concatenate a string within a loop in JSTL/JSP?

Is JSTL's join(), what you searched for?

<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />

Duplicate AssemblyVersion Attribute

My error occurred because, somehow, there was an obj folder created inside my controllers folder. Just do a search in your application for a line inside your Assemblyinfo.cs. There may be a duplicate somewhere.

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

The representation of if-elseif-else in EL using JSF

The following code the easiest way:

 <h:outputLabel value="value = 10" rendered="#{row == 10}" /> 
 <h:outputLabel value="value = 15" rendered="#{row == 15}" /> 
 <h:outputLabel value="value xyz" rendered="#{row != 15 and row != 10}" /> 

Link for EL expression syntax. http://developers.sun.com/docs/jscreator/help/jsp-jsfel/jsf_expression_language_intro.html#syntax

How can I select records ONLY from yesterday?

Use:

AND oh.tran_date BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400

Reference: TRUNC

Calling a function on the tran_date means the optimizer won't be able to use an index (assuming one exists) associated with it. Some databases, such as Oracle, support function based indexes which allow for performing functions on the data to minimize impact in such situations, but IME DBAs won't allow these. And I agree - they aren't really necessary in this instance.

Submit a form in a popup, and then close the popup

I have executed the code in my machine its working for IE and FF also.

function closeSelf(){
    // do something

    if(condition satisfied){
       alert("conditions satisfied, submiting the form.");
       document.forms['certform'].submit();
       window.close();
    }else{
       alert("conditions not satisfied, returning to form");    
    }
}


<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
       <div>Certificate 1: <input type="file" name="cert1"/></div>
       <div>Certificate 2: <input type="file" name="cert2"/></div>
       <div>Certificate 3: <input type="file" name="cert3"/></div>

       // change the submit button to normal button
       <div><input type="button" value="Upload"  onclick="closeSelf();"/></div>
</form>

Java - removing first character of a string

In Java, remove leading character only if it is a certain character

Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

Prints:

blankstring
foobar
moobar

Java, remove all the instances of a character anywhere in a string:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java, remove the first instance of a character anywhere in a string:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

Error: «Could not load type MvcApplication»

You have to check the action method, whether there is one or more methods when calling the method that overloads argumens or invalid argument enter image description here

public string test(string a, string b){

}

public ActionResult x(){
     test(a) //test is need two arguments
}

How to make an Android Spinner with initial text "Select One"?

I think the easiest way is creating a dummy item on index 0 saying "select one" and then on saving maybe check that selection is not 0.

Mysql 1050 Error "Table already exists" when in fact, it does not

Your disk also might just be full. (just had that)

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

Try:

git config --global credential.helper cache

This command prevents git to ask username and password, not forever but with a default limit to 15 minutes.

git config --global credential.helper 'cache --timeout=3600'

This moves the default limit to 1 hour.

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

Set new id with jQuery

What happens when you set all of the attributes in one attr() command like so

$(this).attr({
               id : this.id + '_' + new_id,
               name: this.name + '_' + new_id,
               value: 'test' 
             });

UPDATE multiple tables in MySQL using LEFT JOIN

The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.

UPDATE t1
LEFT JOIN
 t2
ON 
 t2.some_id = t1.some_id
LEFT JOIN
 t3 
ON
 t2.t3_id = t3.id
SET 
 t1.new_column = t3.column;

This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

Install Oracle Guest Additions:

[host-hotkey (usually right Ctrl)] + [d],

Then:

sudo /media/VBOXADDITIONS_4.*/VBoxLinuxAdditions.run

You can now enjoy:

  • A guest that can run at native screen resolution
  • Ability to share files between host and guest
  • Share the clipboard (allowing you to copy and paste between host and guest).

To share folders set them up to be shared. Consider the permissions. Note that the host file permissions are transient. IOW if you can't write to file on host, the guest can't either.

After setting up the file to be shared create a destination if you don't have one: mkdir -p ~/destination

Now mount it under the name you configured it with:

sudo mount -t vboxsf myFileName ~/destination

As an extra tip you can really exploit this feature to do things like: - Use guest subversion client to create repository to mounted directory (you won't have a full svn client but the repo can be used in an IDE on the host). - I personally use my guest to download and unpack binaries like Tomcat to a targeted mount. Yes you can use Linux to install things on Windows!

To unmount all shares:

sudo umount -f -a -t vboxsf

Video 100% width and height

I use JavaScript and CSS to accomplish this. The JS function needs to be called once on init and on window resize. Just tested in Chrome.

HTML:

<video width="1920" height="1080" controls>
    <source src="./assets/video.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

JavaScript:

function scaleVideo() {
    var vid = document.getElementsByTagName('video')[0];
    var w = window.innerWidth;
    var h = window.innerHeight;

    if (w/16 >= h/9) {
        vid.setAttribute('width', w);
        vid.setAttribute('height', 'auto');
    } else {
        vid.setAttribute('width', 'auto');
        vid.setAttribute('height', h);
    }
}

CSS:

video {
    position:absolute;
    left:50%;
    top:50%;
    -webkit-transform:translate(-50%,-50%);
    transform:translate(-50%,-50%);
}

URL to load resources from the classpath in Java

From Java 9+ and up, you can define a new URLStreamHandlerProvider. The URL class uses the service loader framework to load it at run time.

Create a provider:

package org.example;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.spi.URLStreamHandlerProvider;

public class ClasspathURLStreamHandlerProvider extends URLStreamHandlerProvider {

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if ("classpath".equals(protocol)) {
            return new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) throws IOException {
                    return ClassLoader.getSystemClassLoader().getResource(u.getPath()).openConnection();
                }
            };
        }
        return null;
    }

}

Create a file called java.net.spi.URLStreamHandlerProvider in the META-INF/services directory with the contents:

org.example.ClasspathURLStreamHandlerProvider

Now the URL class will use the provider when it sees something like:

URL url = new URL("classpath:myfile.txt");

Code for best fit straight line of a scatter plot in python

from sklearn.linear_model import LinearRegression

X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, I had to remove the intellij internal sdk and started to use my local sdk. When I started to use the internal, the error was gone.

my sdks

Get the latest date from grouped MySQL data

This should work:

SELECT model, date FROM doc GROUP BY model ORDER BY date DESC

It just sort the dates from last to first and by grouping it only grabs the first one.

Detecting touch screen devices with Javascript

As already mentioned, a device may support both mouse and touch input. Very often, the question is not "what is supported" but "what is currently used".

For this case, you can simply register mouse events (including the hover listener) and touch events alike.

element.addEventListener('touchstart',onTouchStartCallback,false);

element.addEventListener('onmousedown',onMouseDownCallback,false);

...

JavaScript should automatically call the correct listener based on user input. So, in case of a touch event, onTouchStartCallback will be fired, emulating your hover code.

Note that a touch may fire both kinds of listeners, touch and mouse. However, the touch listener goes first and can prevent subsequent mouse listeners from firing by calling event.preventDefault().

function onTouchStartCallback(ev) {
    // Call preventDefault() to prevent any further handling
    ev.preventDefault();
    your code...
}

Further reading here.