Programs & Examples On #Xamarin.ios

Xamarin.iOS (previously known as MonoTouch) is a commercial software development kit for Mac OS X and Windows that lets you use C# (a .NET programming language) to create native applications for Apple iPhone, iPod Touch, iPad (iOS), Apple Watch (watchOS) and AppleTV (tvOS) devices.

Looking to understand the iOS UIViewController lifecycle

Haider's answer is correct for pre-iOS 6. However, as of iOS 6 viewDidUnload and viewWillUnload are never called. The docs state: "Views are no longer purged under low-memory conditions and so this method is never called."

How to force a UIViewController to Portrait orientation in iOS 6

Not to be dull here, but would you be so kind to share your subclass? Thank you.

edit: well, I finally did it, the subclass was dead simple to do. I just had to declare the navigationController in the AppDelegate as UINavigationControllerSubclass instead of the default UINavigationController, then modified your subclass with:

- (BOOL)shouldAutorotate {
    return _shouldRotate;
}

so I can set any view I want to rotate or not by calling at viewDidLoad

_navController = (UINavigationController *)self.navigationController;
[_navController setShouldRotate : YES / NO]

Hope this tweak will help others as well, thanks for your tip!

Tip: Make use of

- (NSUInteger)supportedInterfaceOrientations

in your view controllers, so you don't end up by having a portrait desired view in landscape or vice versa.

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

With num_rows() you first perform the query, and then you can check how many rows you got. count_all_results() on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.

// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query

// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query

How to make html <select> element look like "disabled", but pass values?

If you can supply a default value for your selects, then you can use the same approach for unchecked check boxes which requires a hidden input before the actual element, as these don't post a value if left unchecked:

<input type="hidden" name="myfield" value="default" />
<select name="myfield">
    <option value="default" selected="selected">Default</option>
    <option value="othervalue">Other value</option>
    <!-- ... //-->
</select>

This will actually post the value "default" (without quotes, obviously) if the select is disabled by javascript (or jQuery) or even if your code writes the html disabling the element itself with the attribute: disabled="disabled".

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Create an interface to define the 'indexer' interface

Then create your object with that index.

Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.

You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>

// this should be global somewhere, or you may already be 
// using a library that provides such a type
export interface ObjectIndexer<T> {
  [id: string]: T;
}

interface ISomeObject extends ObjectIndexer<string>
{
    firstKey:   string;
    secondKey:  string;
    thirdKey:   string;
}

let someObject: ISomeObject = {
    firstKey:   'firstValue',
    secondKey:  'secondValue',
    thirdKey:   'thirdValue'
};

let key: string = 'secondKey';

let secondValue: string = someObject[key];

Typescript Playground


You can even use this in a generic constraint when defining a generic type:

export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup

Then T inside the class can be indexed :-)

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Deleting all pending tasks in celery / rabbitmq

1. To properly purge the queue of waiting tasks you have to stop all the workers (http://celery.readthedocs.io/en/latest/faq.html#i-ve-purged-messages-but-there-are-still-messages-left-in-the-queue):

$ sudo rabbitmqctl stop

or (in case RabbitMQ/message broker is managed by Supervisor):

$ sudo supervisorctl stop all

2. ...and then purge the tasks from a specific queue:

$ cd <source_dir>
$ celery amqp queue.purge <queue name>

3. Start RabbitMQ:

$ sudo rabbitmqctl start

or (in case RabbitMQ is managed by Supervisor):

$ sudo supervisorctl start all

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

How do I view the list of functions a Linux shared library is exporting?

On a MAC, you need to use nm *.o | c++filt, as there is no -C option in nm.

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Push an associative item into an array in JavaScript

To make something like associative array in JavaScript you have to use objects. ?

_x000D_
_x000D_
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
_x000D_
_x000D_
_x000D_

DEMO: http://jsfiddle.net/bz8pK/1/

Is there a better way to compare dictionary values

If you're just comparing for equality, you can just do this:

if not dict1 == dict2:
    match = False

Otherwise, the only major problem I see is that you're going to get a KeyError if there is a key in dict1 that is not in dict2, so you may want to do something like this:

for key in dict1:
    if not key in dict2 or dict1[key] != dict2[key]:
        match = False

You could compress this into a comprehension to just get the list of keys that don't match too:

mismatch_keys = [key for key in x if not key in y or x[key] != y[key]]
match = not bool(mismatch_keys) #If the list is not empty, they don't match 
for key in mismatch_keys:
    print key
    print '%s -> %s' % (dict1[key],dict2[key])

The only other optimization I can think of might be to use "len(dict)" to figure out which dict has fewer entries and loop through that one first to have the shortest loop possible.

How to mock a final class with mockito

Just to follow up. Please add this line to your gradle file:

testCompile group: 'org.mockito', name: 'mockito-inline', version: '2.8.9'

I have tried various version of mockito-core and mockito-all. Neither of them work.

CSS align images and text on same line

You can simply center the image and text in the parent tag by setting

div {
     text-align: center;
}

vertical center the img and span

img {
     vertical-align:middle;
}
span {
     vertical-align:middle;
}

You can just add second set below, and one thing to mention is that h4 has block display attribute, so you might want to set

h4 {
    display: inline-block
}

to set the h4 "inline".

The full example is shown here.

_x000D_
_x000D_
<div id="photo" style="text-align: center">_x000D_
  <img style="vertical-align:middle" src="https://via.placeholder.com/22x22" alt="">_x000D_
  <span style="vertical-align:middle">Take a photo</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you find the sum of all the numbers in an array in Java?

In you can use streams:

int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);

Output:

The sum is 150.

It's in the package java.util.stream

import java.util.stream.*;

Which data type for latitude and longitude?

If you do not need all the functionality PostGIS offers, Postgres (nowadays) offers an extension module called earthdistance. It uses the point or cube data type depending on your accuracy needs for distance calculations.

You can now use the earth_box function to -for example- query for points within a certain distance of a location.

Comparing two hashmaps for equal values and same key sets?

public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {

    if (map1 == null || map2 == null)
        return false;

    for (String ch1 : map1.keySet()) {
        if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
            return false;

    }
    for (String ch2 : map2.keySet()) {
        if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
            return false;

    }

    return true;
}

What is the most compatible way to install python modules on a Mac?

Directly install one of the fink packages (Django 1.6 as of 2013-Nov)

fink install django-py27
fink install django-py33

Or create yourself a virtualenv:

fink install virtualenv-py27
virtualenv django-env
source django-env/bin/activate
pip install django
deactivate # when you are done

Or use fink django plus any other pip installed packages in a virtualenv

fink install django-py27
fink install virtualenv-py27
virtualenv django-env --system-site-packages
source django-env/bin/activate
# django already installed
pip install django-analytical # or anything else you might want
deactivate # back to your normally scheduled programming

Is there a Google Voice API?

I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:

http://github.com/mastermind202/GoogleVoice

I hope others find it useful. Feedback and suggestions welcome.

Zero an array in C code

Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));

Press any key to continue

I've created a little Powershell function to emulate MSDOS pause. This handles whether running Powershell ISE or non ISE. (ReadKey does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox. This can sometimes be confusing, because the MessageBox does not always come to the forefront. Anyway, here it goes:

Usage: pause "Press any key to continue"

Function definition:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

How to remove the Flutter debug banner?

Well this is simple answer you want.

MaterialApp(
 debugShowCheckedModeBanner: false
)

But if you want to go deep with app (Want a release apk (which don't have debug banner) and if you are using android studio then go to

Run -> Flutter Run 'main.dart' in Relese mode

java: How can I do dynamic casting of a variable from one type to another?

Just thought I would post something that I found quite useful and could be possible for someone who experiences similar needs.

The following method was a method I wrote for my JavaFX application to avoid having to cast and also avoid writing if object x instance of object b statements every time the controller was returned.

public <U> Optional<U> getController(Class<U> castKlazz){
    try {
        return Optional.of(fxmlLoader.<U>getController());
    }catch (Exception e){
        e.printStackTrace();
    }
    return Optional.empty();
}

The method declaration for obtaining the controller was

public <T> T getController()

By using type U passed into my method via the class object, it could be forwarded to the method get controller to tell it what type of object to return. An optional object is returned in case the wrong class is supplied and an exception occurs in which case an empty optional will be returned which we can check for.

This is what the final call to the method looked like (if present of the optional object returned takes a Consumer

getController(LoadController.class).ifPresent(controller->controller.onNotifyComplete());

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Heroku deployment error H10 (App crashed)

I encountered the same problem today. I did heroku run rake db:migrate though I migrated the model before, and the app doesn't crash.

gcc-arm-linux-gnueabi command not found

Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx

where xxx is gcc or ar or ld, etc

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

How to use QTimer

Other way is using of built-in method start timer & event TimerEvent.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

Source:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

Possible to extend types in Typescript?

May be below approach will be helpful for someone TS with reactjs

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

Need table of key codes for android and presenter

This is so out of date, but in case someone googles this, I have the same issue and figured it out.

If you use KeyEvent Viewer, volume up has a code=24, but a scanCode of 115.

Now my USB controller, only has code=# and all scanCodes are 0. But my airmouse (Mele F10) has all keys with codes and scan codes, but the scancode is what you have to put in the .kl file.

Hope this helps someone out there.

How can I represent an infinite number in Python?

In Python, you can do:

test = float("inf")

In Python 3.5, you can do:

import math
test = math.inf

And then:

test > 1
test > 10000
test > x

Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").

Additionally (Python 2.x ONLY), in a comparison to Ellipsis, float(inf) is lesser, e.g:

float('inf') < Ellipsis

would return true.

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

When to use <span> instead <p>?

A practical explanation: By default, <p> </p> will add line breaks before and after the enclosed text (so it creates a paragraph). <span> does not do this, that is why it is called inline.

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

how to load CSS file into jsp

I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css). Make sure your servlet doesn't contain the "/" urlPattern. I hope this worked for u too, - Axel Montini

HTML input type=file, get the image before submitting the form

Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.

Checking for an empty file in C++

C++17 solution:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

Assumes you have the filepath location stored, I don't think you can extract a filepath from an std::ifstream object.

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

How do you make an element "flash" in jQuery

You could use the highlight effect in jQuery UI to achieve the same, I guess.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I'm a MacOS user.

I solved it by uninstalling Android Studio and reinstalling it again.

If you want to try this link helped me a lot.

Uninstall Android Studio MacOS (terminal)

How to subtract 30 days from the current datetime in mysql?

MySQL subtract days from now:

select now(), now() - interval 1 day

Prints:

2014-10-08 09:00:56     2014-10-07 09:00:56

Other Interval Temporal Expression Unit arguments:

https://dev.mysql.com/doc/refman/5.5/en/expressions.html#temporal-intervals

select now() - interval 1 microsecond 
select now() - interval 1 second 
select now() - interval 1 minute 
select now() - interval 1 hour 
select now() - interval 1 day 
select now() - interval 1 week 
select now() - interval 1 month 
select now() - interval 1 year 

sorting and paging with gridview asp.net

Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.

The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.

There are other methods, too, such as persisting user profiles.

I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx

To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

In my case, I followed all answers I could find on Stackoverflow and none of them seemed to solve this problem. All the answers would point to a possible xml file corruption or conflict with Gradle names. Some answers claimed that it would be necessary to clean the project or Sync Project With Gradle files. none of these solutions would solve the problem. Also, once I was following a tutorial on how to build a Hello World app and I just followed the Android Studio wizard windows without any coding at all, it wouldn't make any sense to suspect it was a typo ar anything like this.

TLDR

The problem turned out to be the Build Tools Version. My was set to 23.0.0 rc1, so I changed it to 22.0.1. I suppose it was because I'm using the last available release of Android Available.

To change this value you can open your Project browser on the left window > right click "app > Open Module Setting" and look for it on the "Properties Tab"

MySql Error: 1364 Field 'display_name' doesn't have default value

All of these answers are a good way, but I don't think you want to always go to your DB and modify the default value that you have set to NULL.

I suggest you go to the app/User.php and modify the protected $fillable so it will take your new fields in the data array used to register.

Let's say you add a new input field called "first_name", your $fillable should be something like this :

protected $fillable = [ 'first_name', 'email', 'password',]; 

This did it for me. Good luck!

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

How to make a Python script run like a service or daemon in Linux

You should use the python-daemon library, it takes care of everything.

From PyPI: Library to implement a well-behaved Unix daemon process.

What is the difference between <html lang="en"> and <html lang="en-US">?

<html lang="en">
<html lang="en-US">

The first lang tag only specifies a language code. The second specifies a language code, followed by a country code.

What other values can follow the dash? According to w3.org "Any two-letter subcode is understood to be a [ISO3166] country code." so does that mean any value listed under the alpha-2 code is an accepted value?

Yes, however the value may or may not have any real meaning.

<html lang="en-US"> essentially means "this page is in the US style of English." In a similar way, <html lang="en-GB"> would mean "this page is in the United Kingdom style of English."

If you really wanted to specify an invalid combination, you could. It wouldn't mean much, but <html lang="en-ES"> is valid according to the specification, as I understand it. However, that language/country combination won't do much since English isn't commonly spoken in Spain.

I mean does this somehow further help the browser to display the page?

It doesn't help the browser to display the page, but it is useful for search engines, screen readers, and other things that might read and try to interpret the page, besides human beings.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

I run it like this -

created > startOfDay(-0d)

It gives me all issues created today. When you change -0d to -1d, it will give you all issues created yesterday and today.

Get all LI elements in array

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

npm throws error without sudo

For me, execute only

sudo chown -R $(whoami) ~/.npm

doesn't work. Then, I execute too

sudo chown -R $(whoami) /usr/lib/node_modules/
sudo chown -R $(whoami) /usr/bin/node
sudo chown -R $(whoami) /usr/bin/npm

And all works fine!

Best way to find the months between two dates

My simple solution:

import datetime

def months(d1, d2):
    return d1.month - d2.month + 12*(d1.year - d2.year)

d1 = datetime.datetime(2009, 9, 26)  
d2 = datetime.datetime(2019, 9, 26) 

print(months(d1, d2))

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

TypeError: Missing 1 required positional argument: 'self'

You need to initialize it first:

p = Pump().getPumps()

Create code first, many to many, with additional fields in association table

I'll just post the code to do this using the fluent API mapping.

public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class Email {
    public int EmailID { get; set; }
    public string Address { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class UserEmail {
    public int UserID { get; set; }
    public int EmailID { get; set; }
    public bool IsPrimary { get; set; }
}

On your DbContext derived class you could do this:

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder builder) {
        // Primary keys
        builder.Entity<User>().HasKey(q => q.UserID);
        builder.Entity<Email>().HasKey(q => q.EmailID);
        builder.Entity<UserEmail>().HasKey(q => 
            new { 
                q.UserID, q.EmailID
            });

        // Relationships
        builder.Entity<UserEmail>()
            .HasRequired(t => t.Email)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.EmailID)

        builder.Entity<UserEmail>()
            .HasRequired(t => t.User)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.UserID)
    }
}

It has the same effect as the accepted answer, with a different approach, which is no better nor worse.

Namespace not recognized (even though it is there)

I've had a similar issue, that took a bit to troubleshoot, so I thought to share it:

The namespace that could not be resolved in my case was Company.Project.Common.Models.EF. I had added a file in a new Company.Project.BusinessLogic.Common namespace.

The majority of the files were having a

using Company.Project;

And then referencing the models as Common.Models.EF. All the files that also had a

using Company.Project.BusinessLogic;

Were failing as VS could not determine which namespace to use.

The solution has been to change the second namespace to Company.Project.BusinessLogic.CommonServices

Nested routes with react router v4 / v5

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

Remove json element

I recommend splice method to remove an object from JSON objects array.

jQuery(json).each(function (index){
        if(json[index].FirstName == "Test1"){
            json.splice(index,1); // This will remove the object that first name equals to Test1
            return false; // This will stop the execution of jQuery each loop.
        }
});

I use this because when I use delete method, I get null object after I do JSON.stringify(json)

convert string into array of integers

Better one line solution:

var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
   answerInt.push(parseInt(item))
});

How do I get a computer's name and IP address using VB.NET?

Here is Example for this. In this example we can get IP address of our given host name.

   Dim strHostName As String = "jayeshsorathia.blogspot.com"
    'string strHostName = "www.microsoft.com";
    ' Get DNS entry of specified host name
    Dim addresses As IPAddress() = Dns.GetHostEntry(strHostName).AddressList

    ' The DNS entry may contains more than one IP addresses.
    ' Iterate them and display each along with the type of address (AddressFamily).
    For Each address As IPAddress In addresses
        Response.Write(String.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily))
        Response.Write("<br/><br/>")
    Next

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Creating multiple log files of different content with log4j

Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git

My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

'const string' vs. 'static readonly string' in C#

You can change the value of a static readonly string only in the static constructor of the class or a variable initializer, whereas you cannot change the value of a const string anywhere.

CSS last-child selector: select last-element of specific class, not last child inside of parent?

I guess that the most correct answer is: Use :nth-child (or, in this specific case, its counterpart :nth-last-child). Most only know this selector by its first argument to grab a range of items based on a calculation with n, but it can also take a second argument "of [any CSS selector]".

Your scenario could be solved with this selector: .commentList .comment:nth-last-child(1 of .comment)

But being technically correct doesn't mean you can use it, though, because this selector is as of now only implemented in Safari.

For further reading:

NotificationCompat.Builder deprecated in Android O

Call the 2-arg constructor: For compatibility with Android O, call support-v4 NotificationCompat.Builder(Context context, String channelId). When running on Android N or earlier, the channelId will be ignored. When running on Android O, also create a NotificationChannel with the same channelId.

Out of date sample code: The sample code on several JavaDoc pages such as Notification.Builder calling new Notification.Builder(mContext) is out of date.

Deprecated constructors: Notification.Builder(Context context) and v4 NotificationCompat.Builder(Context context) are deprecated in favor of Notification[Compat].Builder(Context context, String channelId). (See Notification.Builder(android.content.Context) and v4 NotificationCompat.Builder(Context context).)

Deprecated class: The entire class v7 NotificationCompat.Builder is deprecated. (See v7 NotificationCompat.Builder.) Previously, v7 NotificationCompat.Builder was needed to support NotificationCompat.MediaStyle. In Android O, there's a v4 NotificationCompat.MediaStyle in the media-compat library's android.support.v4.media package. Use that one if you need MediaStyle.

API 14+: In Support Library from 26.0.0 and higher, the support-v4 and support-v7 packages both support a minimum API level of 14. The v# names are historical.

See Recent Support Library Revisions.

Difference Between $.getJSON() and $.ajax() in jQuery

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.

java.lang.RuntimeException: Unable to start activity ComponentInfo

Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
     android:minSdkVersion="8" android:targetSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MainTabPanel"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MyBookActivity"  >            
    </activity>
</application>

How do you send a Firebase Notification to all devices via CURL?

EDIT: It appears that this method is not supported anymore (thx to @FernandoZamperin). Please take a look at the other answers!

Instead of subscribing to a topic you could instead make use of the condition key and send messages to instances, that are not in a group. Your data might look something like this:

{
    "data": {
        "foo": "bar"
    },
    "condition": "!('anytopicyoudontwanttouse' in topics)"
}

See https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics_2

How do I force git to use LF instead of CR+LF under windows?

The proper way to get LF endings in Windows is to first set core.autocrlf to false:

git config --global core.autocrlf false

You need to do this if you are using msysgit, because it sets it to true in its system settings.

Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto in your .gitattributes for all files:

* text=auto

And set core.eol to lf:

git config --global core.eol lf

Now you can also switch single repos to crlf (in the working directory!) by running

git config core.eol crlf

After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:

git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f

If you now want git to also normalize the files in your working directory, run these commands:

git ls-files -z | xargs -0 rm
git checkout .

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

Same error

Installing collected packages: six, pyparsing, packaging, appdirs, setuptools
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/six.py'

and here I use --user without sudo to solve this issue

$ pip install --user scikit-image h5py keras pygame
Collecting scikit-image
  Downloading http://mirrors.aliyun.com/pypi/packages/65/69/27a1d55ce8f77c8ac757938707105b1070ff4f2ae47d2dc99461bfae4491/scikit_image-0.13.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (28.1MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 28.1MB 380kB/s
Collecting h5py
  Downloading http://mirrors.aliyun.com/pypi/packages/b7/cc/1c29b0815b12de2c92b5323cad60f724ac8f0e39d0166d0b9dfacbcb70dd/h5py-2.7.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 4.5MB 503kB/s
Requirement already satisfied: keras in /Library/Python/2.7/site-packages
Requirement already satisfied: pygame in /Library/Python/2.7/site-packages
Requirement already satisfied: matplotlib>=1.3.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scikit-image)
Requirement already satisfied: six>=1.7.3 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: pillow>=2.1.0 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: networkx>=1.8 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: PyWavelets>=0.4.0 in /Library/Python/2.7/site-packages (from scikit-image)
Collecting scipy>=0.17.0 (from scikit-image)
  Downloading http://mirrors.aliyun.com/pypi/packages/72/eb/d398b9f63ee936575edc62520477d6c2353ed013bacd656bd0c8bc1d0fa7/scipy-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (16.2MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 16.2MB 990kB/s
Requirement already satisfied: numpy>=1.7 in /Library/Python/2.7/site-packages (from h5py)
Requirement already satisfied: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: tornado in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: pyparsing>=1.5.6 in /Users/qiuwei/Library/Python/2.7/lib/python/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: nose in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: olefile in /Library/Python/2.7/site-packages (from pillow>=2.1.0->scikit-image)
Requirement already satisfied: decorator>=3.4.0 in /Library/Python/2.7/site-packages (from networkx>=1.8->scikit-image)
Requirement already satisfied: singledispatch in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: certifi in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: backports_abc>=0.4 in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Installing collected packages: scipy, scikit-image, h5py
Successfully installed h5py-2.7.0 scikit-image-0.13.0 scipy-0.19.0 

Hope it will help someone who encounter similar issue!

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

How do I retrieve the number of columns in a Pandas data frame?

In order to include the number of row index "columns" in your total shape I would personally add together the number of columns df.columns.size with the attribute pd.Index.nlevels/pd.MultiIndex.nlevels:

Set up dummy data

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

Writing our process as a function:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

This prints:

Ignore the index:
3 3

Include the index:
4 5

If you want to only include the number of indices if the index is a pd.MultiIndex, then you can throw in an isinstance check in the defined function.

As an alternative, you could use df.reset_index().columns.size to achieve the same result, but this won't be as performant since we're temporarily inserting new columns into the index and making a new index before getting the number of columns.

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Github Windows 'Failed to sync this branch'

This error also occurs if the branch you're trying to sync has been deleted.

git status won't tell you that, but you'll get a "no such ref was fetched" message if you try git pull.

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

Copy the DLL to C:\Windows\SysWoW64\
In an elevated command prompt: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

Copy the DLL to C:\Windows\System32\
In an elevated command prompt: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

I know it seems the wrong way round, but that's the way it works. See:

http://support.microsoft.com/kb/249873
Quote: "Note On a 64-bit version of a Windows operating system, there are two versions of the Regsv32.exe file:
The 64-bit version is %systemroot%\System32\regsvr32.exe.
The 32-bit version is %systemroot%\SysWoW64\regsvr32.exe.
"

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

How to export SQL Server database to MySQL?

I had some data I had to get from mssql into mysql, had difficulty finding a solution. So what I did in the end (a bit of a long winded way to do it, but as a last resort it works) was:

  • Open the mssql database in sql server management studio express (I used 2005)
  • Open each table in turn and
  • Click the top left corner box to select whole table:

  • Copy data to clipboard (ctrl + v)

  • Open ms excel
  • Paste data from clipboard
  • Save excel file as .csv
  • Repeat the above for each table
  • You should now be able to import the data into mysql

Hope this helps

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

Looked around online too long not to contribute. After trying to type in the mysql prompt from the command line, I was continuing to receive this message:

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

This was due to the fact that my local mysql server was no longer running. In order to restart the server, I navigated to

shell> cd /user/local/bin

where my mysql.server was located. From here, simply type:

shell> mysql.server start

This will relaunch the local mysql server.

From there you can reset the root password if need be..

mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
->                   WHERE User='root';
mysql> FLUSH PRIVILEGES;

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I had to set

C:\ProgramData\MySQL\MySQL Server 8.0/my.ini  secure-file-priv=""

When I commented line with secure-file-priv, secure-file-priv was null and I couldn't download data.

Enable/Disable a dropdownbox in jquery

try this

 <script type="text/javascript">
        $(document).ready(function () {
            $("#chkdwn2").click(function () {
                if (this.checked)
                    $('#dropdown').attr('disabled', 'disabled');
                else
                    $('#dropdown').removeAttr('disabled');
            });
        });
    </script>

setting min date in jquery datepicker

Hiya working demo: http://jsfiddle.net/femy8/

Now the calendar will only go to minimum of 1999-10-25.

Click on the image i.e. small icon next to text box for calendar to appear. You can try selecting up until 1999 but the minimum date for selection is 25th of oct 1999. which is what you want.

This will help, have a nice one! :) cheers!

Jquery Code

$(".mypicker").datepicker({
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    showButtonPanel: true,
    changeMonth: true,
    changeYear: true,
    showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date('1999/10/25'),
        maxDate: '+30Y',
        inline: true
});


?

Check if space is in a string

word = ' '
while True:
    if ' ' in word:
        word = raw_input("Please enter a single word: ")
    else:
        print "Thanks"
        break

This is more idiomatic python - comparison against True or False is not necessary - just use the value returned by the expression ' ' in word.

Also, you don't need to use pastebin for such a small snippet of code - just copy the code into your post and use the little 1s and 0s button to make your code look like code.

Ruby: How to convert a string to boolean

Don't think too much:

bool_or_string.to_s == "true"  

So,

"true".to_s == "true"   #true
"false".to_s == "true"  #false 
true.to_s == "true"     #true
false.to_s == "true"    #false

You could also add ".downcase," if you are worried about capital letters.

Find all storage devices attached to a Linux machine

libsysfs does look potentially useful, but not directly from a shell script. There's a program that comes with it called systool which will do what you want, though it may be easier to just look in /sys directly rather than using another program to do it for you.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

I assume you are using gcc, to simply link object files do:

$ gcc -o output file1.o file2.o

To get the object-files simply compile using

$ gcc -c file1.c

this yields file1.o and so on.

If you want to link your files to an executable do

$ gcc -o output file1.c file2.c

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Sum up a column from a specific row down

Something like this worked for me (references columns C and D from the row 8 till the end of the columns, in Excel 2013 if relevant):

=SUMIFS(INDIRECT(ADDRESS(ROW(D$8), COLUMN())&":"&ADDRESS(ROWS($C:$C), COLUMN())),INDIRECT("C$8:C"&ROWS($C:$C)),$C$2)

How do I debug "Error: spawn ENOENT" on node.js?

For anyone who might stumble upon this, if all the other answers do not help and you are on Windows, know that there is currently a big issue with spawn on Windows and the PATHEXT environment variable that can cause certain calls to spawn to not work depending on how the target command is installed.

How correctly produce JSON by RESTful web service?

You can annotate your bean with jaxb annotations.

  @XmlRootElement
  public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }

and then your method would look like this:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

There is a chapter in the latest documentation that deals with this:

https://jersey.java.net/documentation/latest/user-guide.html#json

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

Use CSS3 transitions with gradient backgrounds

I use this at work :) IE6+ https://gist.github.com/GrzegorzPerko/7183390

Don't forget about <element class="ahover"><span>Text</span></a> if you use a text element.

.ahover {
    display: block;
    /** text-indent: -999em; ** if u use only only img **/
    position: relative;
}
.ahover:after {
    content: "";
    height: 100%;
    left: 0;
    opacity: 0;
    position: absolute;
    top: 0;
    transition: all 0.5s ease 0s;
    width: 100%;
    z-index: 1;
}
.ahover:hover:after {
    opacity: 1;
}
.ahover span {
    display: block;
    position: relative;
    z-index: 2;
}

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

SQL update from one Table to another based on a ID match

update from one table to another table on id matched

UPDATE 
     TABLE1 t1, 
     TABLE2 t2
SET 
     t1.column_name = t2.column_name 
WHERE
     t1.id = t2.id;

How do I declare a namespace in JavaScript?

I think you all use too much code for such a simple problem. No need to make a repo for that. Here's a single line function.

namespace => namespace.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

Try it :

_x000D_
_x000D_
// --- definition ---
const namespace = name => name.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

// --- Use ----
const c = namespace("a.b.c");
c.MyClass = class MyClass {};

// --- see ----
console.log("a : ", a);
_x000D_
_x000D_
_x000D_

How to start nginx via different port(other than 80)

If you are experiencing this problem when using Docker be sure to map the correct port numbers. If you map port 81:80 when running docker (or through docker-compose.yml), your nginx must listen on port 80 not 81, because docker does the mapping already.

I spent quite some time on this issue myself, so hope it can be to some help for future googlers.

Document Root PHP

Yes, on the server side $_SERVER['DOCUMENT_ROOT'] is equivalent to / on the client side.

For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png" will be the string /var/www/html/images/thumbnail.png on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png

No, in other words the value of $_SERVER['DOCUMENT_ROOT'] is not / rather it is the server's local path to what the server shows the client at example.com/

note: $_SERVER['DOCUMENT_ROOT'] does not include a trailing /

Calculating sum of repeated elements in AngularJS ng-repeat

This is my solution

<div ng-controller="MainCtrl as mc">
  <ul>
      <li ng-repeat="n in [1,2,3,4]" ng-init="mc.sum = ($first ? 0 : mc.sum) + n">{{n}}</li>
      <li>sum : {{mc.sum}}</li>
  </ul>
</div>

It require you to add name to controller as Controller as SomeName so we can cache variable in there (is it really require? I don't familiar with using $parent so I don't know)

Then for each repeat, add ng-init"SomeName.SumVariable = ($first ? 0 : SomeName.SumVariable) + repeatValue"

$first for checking it is first then it reset to zero, else it would continue aggregate value

http://jsfiddle.net/thainayu/harcv74f/

How to pass multiple values through command argument in Asp.net?

You can try this:

CommandArgument='<%# "scrapid=" + Eval("ScrapId")+"&"+"UserId="+ Eval("UserId")%>'

Pycharm: run only part of my Python file

You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:

enter image description here

After you've enabled, set a break-point to where you want it to:

enter image description here

After you're done setting the break-point:

enter image description here

Once that has been completed:

enter image description here

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

According to the logs :

[06-Feb-2016 22:38:48 Europe/Berlin] PHP Warning:  require(/Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/autoload.php on line 17
[06-Feb-2016 22:38:48 Europe/Berlin] PHP Fatal error:  require(): Failed opening required '/Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/../vendor/autoload.php' (include_path='.:/Applications/MAMP/bin/php/php7.0.0/lib/php') in /Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/autoload.php on line 17
[06-Feb-2016 22:43:37 Europe/Berlin] PHP Warning:  require(/Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/autoload.php on line 17
[06-Feb-2016 22:43:37 Europe/Berlin] PHP Fatal error:  require(): Failed opening required '/Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/../vendor/autoload.php' (include_path='.:/Applications/MAMP/bin/php/php7.0.0/lib/php') in /Users/tomsihap/Documents/Development/mamp/partie_1_exo/bootstrap/autoload.php on line 17

There are some failures opening files into the /vendor folder.

By installing and updating via composer, I was able to finally solve the issue.

sudo composer install
sudo composer update

Android replace the current fragment with another fragment

it's very simple how to replace with Fragment.

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Code:

if [[ -e $1 && ! -e $2 ]]; then
   mkdir --parents --verbose -- "$(dirname -- "$2")"
fi
mv --verbose -- "$1" "$2"

Example:

arguments: "d1" "d2/sub"

mkdir: created directory 'd2'
renamed 'd1' -> 'd2/sub'

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

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

SQL get the last date time record

SELECT TOP 1 * FROM foo ORDER BY Dates DESC

Will return one result with the latest date.

SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)

Will return all results that have the same maximum date, to the milissecond.

This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

How do you get the current page number of a ViewPager for Android?

in the latest packages you can also use

vp.getCurrentItem()

or

vp is the viewPager ,

pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);

you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.

private int currentPage;

    private static class PageListener extends SimpleOnPageChangeListener{
            public void onPageSelected(int position) {
                Log.i(TAG, "page selected " + position);
                   currentPage = position;
        }
    }

PowerShell To Set Folder Permissions

Another example using PowerShell for set permissions (File / Directory) :

Verify permissions

Get-Acl "C:\file.txt" | fl *

Apply full permissions for everyone

$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "C:\file.txt"

Screenshots: enter image description here enter image description here

Hope this helps

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

AppFabric installation failed because installer MSI returned with error code : 1603

I had this same error. Just had to install IIS and everything worked.

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

Connecting to Microsoft SQL server using Python

here's the one that works for me:

from sqlalchemy import create_engine
import urllib

conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')

quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))

Setting the JVM via the command line on Windows

If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH

This eliminates the ambiguity.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

How to check whether a file is empty or not?

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty

What's the difference between Perl's backticks, system, and exec?

exec

executes a command and never returns. It's like a return statement in a function.

If the command is not found exec returns false. It never returns true, because if the command is found it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

system

executes a command and your Perl script is continued after the command has finished.

The return value is the exit status of the command. You can find documentation about it in perlfunc.

backticks

like system executes a command and your perl script is continued after the command has finished.

In contrary to system the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and execit is an operator.


Other ways

What is missing from the above is a way to execute a command asynchronously. That means your perl script and your command run simultaneously. This can be accomplished with open. It allows you to read STDOUT/STDERR and write to STDIN of your command. It is platform dependent though.

There are also several modules which can ease this tasks. There is IPC::Open2 and IPC::Open3 and IPC::Run, as well as Win32::Process::Create if you are on windows.

How do I execute a command and get the output of the command within C++ using POSIX?

Assuming POSIX, simple code to capture stdout:

#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>

std::string qx(const std::vector<std::string>& args) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  pipe(stderr_fds);

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    close(stdout_fds[1]);

    close(stderr_fds[0]);
    dup2(stderr_fds[1], 2);
    close(stderr_fds[1]);

    std::vector<char*> vc(args.size() + 1, 0);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    exit(0);
  }

  close(stdout_fds[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    const ssize_t r = read(stdout_fds[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  close(stderr_fds[1]);
  close(stderr_fds[0]);

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  return out;
}

Code contributions are welcome for more functionality:

https://github.com/ericcurtin/execxx

How do I pass variables and data from PHP to JavaScript?

myPlugin.start($val); // Tried this, didn't work

It doesn't work because $val is undefined as far as JavaScript is concerned, i.e. the PHP code did not output anything for $val. Try viewing the source in your browser and here is what you'll see:

myPlugin.start(); // I tried this, and it didn't work

And

<?php myPlugin.start($val); ?> // This didn't work either

This doesn't work because PHP will try to treat myPlugin as a constant and when that fails it will try to treat it as the string 'myPlugin' which it will try to concatenate with the output of the PHP function start() and since that is undefined it will produce a fatal error.

And

 myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails

While this is most likely to work, since the PHP code is producing valid JavaScript with the expected arguments, if it fails, chances are it's because myPlugin isn't ready yet. Check your order of execution.

Also you should note that the PHP code output is insecure and should be filtered with json_encode().

EDIT

Because I didn't notice the missing parenthesis in myPlugin.start(<?=$val?> :-\

As @Second Rikudo points out, for it to work correctly $val would need to contain the closing parenthesis, for example: $val="42);"

Meaning that the PHP will now produce myPlugin.start(42); and will work as expected when executed by the JavaScript code.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

Where are shared preferences stored?

SharedPreferences are stored in an xml file in the app data folder, i.e.

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

or the default preferences at:

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

SharedPreferences added during runtime are not stored in the Eclipse project.

Note: Accessing /data/data/<package_name> requires superuser privileges

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

HTML form submit to PHP script

Try this:

<form method="post" action="check.php">
    <select name="website_string">
        <option value="" selected="selected"></option>
        <option VALUE="abc"> ABC</option>
        <option VALUE="def"> def</option>
        <option VALUE="hij"> hij</option>
    </select>
    <input TYPE="submit" name="submit" />
</form>

Both your select control and your submit button had the same name attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.

check.php

<?php
    echo $_POST['website_string'];
?>

Obligatory disclaimer about using raw $_POST data. Sanitize anything you'll actually be using in application logic.

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

Resize font-size according to div size

In regards to your code, see @Coulton. You'll need to use JavaScript.

Checkout either FitText (it does work in IE, they just ballsed their site somehow) or BigText.

FitText will allow you to scale some text in relation to the container it is in, while BigText is more about resizing different sections of text to be the same width within the container.

BigText will set your string to exactly the width of the container, whereas FitText is less pixel perfect. It starts by setting the font-size at 1/10th of the container element's width. It doesn't work very well with all fonts by default, but it has a setting which allows you to decrease or increase the 'power' of the re-size. It also allows you to set a min and max font-size. It will take a bit of fiddling to get working the first time, but does work great.

http://marabeas.io <- playing with it currently here. As far as I understand, BigText wouldn't work in my context at all.

For those of you using Angularjs, here's an Angular version of FitText I've made.


Here's a LESS mixin you can use to make @humanityANDpeace's solution a little more pretty:

@mqIterations: 19;
.fontResize(@i) when (@i > 0) {
    @media all and (min-width: 100px * @i) { body { font-size:0.2em * @i; } }
    .fontResize((@i - 1));
}
.fontResize(@mqIterations);

And an SCSS version thanks to @NIXin!

$mqIterations: 19;
@mixin fontResize($iterations) { 
    $i: 1; 
    @while $i <= $iterations { 
        @media all and (min-width: 100px * $i) { body { font-size:0.2em * $i; } } 
        $i: $i + 1; 
    }
} 
@include fontResize($mqIterations);

How to set a value for a span using jQuery

You are using jQuery(document).ready(function($) {} means here you are using jQuery instead of $. So to resolve your issue use following code.

jQuery("#submittername").text(submitter_name);

This will resolve your problem.

Is iterating ConcurrentHashMap values thread safe?

This might give you a good insight

ConcurrentHashMap achieves higher concurrency by slightly relaxing the promises it makes to callers. A retrieval operation will return the value inserted by the most recent completed insert operation, and may also return a value added by an insertion operation that is concurrently in progress (but in no case will it return a nonsense result). Iterators returned by ConcurrentHashMap.iterator() will return each element once at most and will not ever throw ConcurrentModificationException, but may or may not reflect insertions or removals that occurred since the iterator was constructed. No table-wide locking is needed (or even possible) to provide thread-safety when iterating the collection. ConcurrentHashMap may be used as a replacement for synchronizedMap or Hashtable in any application that does not rely on the ability to lock the entire table to prevent updates.

Regarding this:

However, iterators are designed to be used by only one thread at a time.

It means, while using iterators produced by ConcurrentHashMap in two threads are safe, it may cause an unexpected result in the application.

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

I totally understand your problem about duplicated field names.

I needed that too until I coded my own function to solve it. If you are using PHP you can use it, or code yours in the language you are using for if you have this following facilities.

The trick here is that mysql_field_table() returns the table name and mysql_field_name() the field for each row in the result if it's got with mysql_num_fields() so you can mix them in a new array.

This prefixes all columns ;)

Regards,

function mysql_rows_with_columns($query) {
    $result = mysql_query($query);
    if (!$result) return false; // mysql_error() could be used outside
    $fields = mysql_num_fields($result);
    $rows = array();
    while ($row = mysql_fetch_row($result)) { 
        $newRow = array();
        for ($i=0; $i<$fields; $i++) {
            $table = mysql_field_table($result, $i);
            $name = mysql_field_name($result, $i);
            $newRow[$table . "." . $name] = $row[$i];
        }
        $rows[] = $newRow;
    }
    mysql_free_result($result);
    return $rows;
}

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

All of the answers above may work for the time being but whenever you run maven on the command line or Maven → Update project… the JDK will be reset, this was also the question as I understand it.

To fix this for good add the following code to your pom file. Remember to do a Maven → Update project… afterwards or mvn clean compile at the command line.

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>

    </pluginManagement>
</build>

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

Document has already explain the usage. So I am using SQL to explain these methods

Example:


Assuming there is an Order (orders) has many OrderItem (order_items).

And you have already build the relationship between them.

// App\Models\Order:
public function orderItems() {
    return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}

These three methods are all based on a relationship.

With


Result: with() return the model object and its related results.

Advantage: It is eager-loading which can prevent the N+1 problem.

When you are using the following Eloquent Builder:

Order::with('orderItems')->get();

Laravel change this code to only two SQL:

// get all orders:
SELECT * FROM orders; 

// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);

And then laravel merge the results of the second SQL as different from the results of the first SQL by foreign key. At last return the collection results.

So if you selected columns without the foreign_key in closure, the relationship result will be empty:

Order::with(['orderItems' => function($query) { 
           // $query->sum('quantity');
           $query->select('quantity'); // without `order_id`
       }
])->get();

#=> result:
[{  id: 1,
    code: '00001',
    orderItems: [],    // <== is empty
  },{
    id: 2,
    code: '00002',
    orderItems: [],    // <== is empty
  }...
}]

Has


Has will return the model's object that its relationship is not empty.

Order::has('orderItems')->get();

Laravel change this code to one SQL:

select * from `orders` where exists (
    select * from `order_items` where `order`.`id` = `order_item`.`order_id`
)

whereHas


whereHas and orWhereHas methods to put where conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint.

Order::whereHas('orderItems', function($query) {
   $query->where('status', 1);
})->get();

Laravel change this code to one SQL:

select * from `orders` where exists (
    select * 
    from `order_items` 
    where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

Python: printing a file to stdout

f = open('file.txt', 'r')
print f.read()
f.close()

From http://docs.python.org/tutorial/inputoutput.html

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

Asp.net Validation of viewstate MAC failed

I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

Limit Decimal Places in Android EditText

More elegant way would be using a regular expression ( regex ) as follows:

public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
    mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }

}

To use it do:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

Submit a form using jQuery

Note that if you already installed a submit event listener for your form, the innner call to submit()

jQuery('#<form-id>').submit( function(e){ 
    e.preventDefault();
    // maybe some validation in here
    if ( <form-is-valid> ) jQuery('#<form-id>').submit();
});

won't work as it tries to install a new event listener for this form's submit event (which fails). So you have to acces the HTML Element itself (unwrap from jQquery) and call submit() on this element directly:

    jQuery('#<form-id>').submit( function(e){ 
      e.preventDefault();
      // note the [0] array access:
      if ( <form-is-valid> ) jQuery('#<form-id>')[0].submit();
    });

How can I install pip on Windows?

You have to get the get_pip.py file. Search it on google. Copy from there and save it locally on C drive in the pip directory.

The equivalent of a GOTO in python

Forgive me - I couldn't resist ;-)

def goto(linenum):
    global line
    line = linenum

line = 1
while True:
    if line == 1:
        response = raw_input("yes or no? ")
        if response == "yes":
            goto(2)
        elif response == "no":
            goto(3)
        else:
            goto(100)
    elif line == 2:
        print "Thank you for the yes!"
        goto(20)
    elif line == 3:
        print "Thank you for the no!"
        goto(20)
    elif line == 20:
        break
    elif line == 100:
        print "You're annoying me - answer the question!"
        goto(1)

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Put quotes around $username. String values, as opposed to numeric values, must be enclosed in quotes.

$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

Also, there is no point in using the LIKE condition if you're not using wildcards: if you need an exact match use = instead of LIKE.

Set value of hidden input with jquery

You should use val instead of value.

<script type="text/javascript" language="javascript">
$(document).ready(function () { 
    $('input[name="testing"]').val('Work!');
});
</script>

How to create a property for a List<T>

Simple and effective alternative:

public class ClassName
{
    public List<dynamic> MyProperty { get; set; }
}

or

public class ClassName
{
    public List<object> MyProperty { get; set; }
}

For differences see this post: List<Object> vs List<dynamic>

how to convert date to a format `mm/dd/yyyy`

Are you looking for something like this?

SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]' 
            THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts,   1), 101)
            ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
      END created_ts
  FROM table1

Output:

| CREATED_TS |
|------------|
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 11/16/2011 |
| 02/20/2012 |
| 11/29/2012 |

Here is SQLFiddle demo

Matplotlib 2 Subplots, 1 Colorbar

To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow instead of pcolormesh because of the 1:1 aspect ratio imposed by imshow.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
    im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.flat)
plt.show()

enter image description here

get list of pandas dataframe columns based on data type

You can use boolean mask on the dtypes attribute:

In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])

In [12]: df.dtypes
Out[12]: 
0      int64
1    float64
2     object
dtype: object

In [13]: msk = df.dtypes == np.float64  # or object, etc.

In [14]: msk
Out[14]: 
0    False
1     True
2    False
dtype: bool

You can look at just those columns with the desired dtype:

In [15]: df.loc[:, msk]
Out[15]: 
        1
0  2.3456

Now you can use round (or whatever) and assign it back:

In [16]: np.round(df.loc[:, msk], 2)
Out[16]: 
      1
0  2.35

In [17]: df.loc[:, msk] = np.round(df.loc[:, msk], 2)

In [18]: df
Out[18]: 
   0     1  2
0  1  2.35  c

Sending multipart/formdata with jQuery.ajax

Look at my code, it does the job for me

$( '#formId' )
  .submit( function( e ) {
    $.ajax( {
      url: 'FormSubmitUrl',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );

How can I tell what edition of SQL Server runs on the machine?

I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:

SELECT  
    SERVERPROPERTY('productversion') as 'Product Version', 
    SERVERPROPERTY('productlevel') as 'Product Level',  
    SERVERPROPERTY('edition') as 'Product Edition',
    SERVERPROPERTY('buildclrversion') as 'CLR Version',
    SERVERPROPERTY('collation') as 'Default Collation',
    SERVERPROPERTY('instancename') as 'Instance',
    SERVERPROPERTY('lcid') as 'LCID',
    SERVERPROPERTY('servername') as 'Server Name'

That gives you an output something like this:

Product Version   Product Level   Product Edition             CLR Version   
10.0.2531.0       SP1             Developer Edition (64-bit)    v2.0.50727  

Default Collation     Instance   LCID   Server Name 
Latin1_General_CI_AS     NULL    1033   *********       

How to capture the "virtual keyboard show/hide" event in Android?

Nebojsa's solution almost worked for me. When I clicked inside a multi-line EditText it knew the keyboard was displayed, but when I started typing inside the EditText, the actualHeight and proposedHeight were still the same so it did not know they keyboard was still displayed. I made a slight modification to store the max height and it works fine. Here is the revised subclass:

public class CheckinLayout extends RelativeLayout {

    private int largestHeight;

    public CheckinLayout(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.checkin, this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
        largestHeight = Math.max(largestHeight, getHeight());

        if (largestHeight > proposedheight)
            // Keyboard is shown
        else
            // Keyboard is hidden

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

Create a HTML table where each TR is a FORM

If you can use javascript and strictly require it on your web, you can put textboxes, checkboxes and whatever on each row of your table and at the end of each row place button (or link of class rowSubmit) "save". Without any FORM tag. Form than will be simulated by JS and Ajax like this:

<script type="text/javascript">
$(document).ready(function(){
  $(".rowSubmit").click(function()
  {
     var form = '<form><table><tr>' + $(this).closest('tr').html() + '</tr></table></form>';
     var serialized = $(form).serialize(); 
     $.get('url2action', serialized, function(data){
       // ... can be empty
     }); 
   });
});        
</script>

What do you think?

PS: If you write in jQuery this:

$("valid HTML string")
$(variableWithValidHtmlString)

It will be turned into jQuery object and you can work with it as you are used to in jQuery.

Long press on UITableView

Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.

Rails: Get Client IP address

request.remote_ip is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.

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);
}

Set cursor position on contentEditable <div>

You can leverage selectNodeContents which is supported by modern browsers.

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

Conveniently map between enum and int / String

Seems the answer(s) to this question are outdated with the release of Java 8.

  1. Don't use ordinal as ordinal is unstable if persisted outside the JVM such as a database.
  2. It is relatively easy to create a static map with the key values.

public enum AccessLevel {
  PRIVATE("private", 0),
  PUBLIC("public", 1),
  DEFAULT("default", 2);

  AccessLevel(final String name, final int value) {
    this.name = name;
    this.value = value;
  }

  private final String name;
  private final int value;

  public String getName() {
    return name;
  }

  public int getValue() {
    return value;
  }

  static final Map<String, AccessLevel> names = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getName, Function.identity()));
  static final Map<Integer, AccessLevel> values = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getValue, Function.identity()));

  public static AccessLevel fromName(final String name) {
    return names.get(name);
  }

  public static AccessLevel fromValue(final int value) {
    return values.get(value);
  }
}

Example on ToggleButton

Just remove the line toggle.toggle(); from your click listener toggle() method will always reset your toggle button value.

And as you are trying to take the value of EditText in string variable which always remains same as you are getting value in onCreate() so better directly use the EditText to get the value of it in your onClick listener.

Just change your code as below its working fine now.

  btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                       //toggle.toggle();
            if ( ed.getText().toString().equalsIgnoreCase("1")) {

                toggle.setTextOff("TOGGLE ON");
                toggle.setChecked(true);
            } else if ( ed.getText().toString().equalsIgnoreCase("0")) {

                toggle.setTextOn("TOGGLE OFF");
                toggle.setChecked(false);

            }
        }
    });

Changing password with Oracle SQL Developer

Try this solution if the Reset Password option (of SQL Developer) did not work:

Step 1: Open Run SQL Command Line (from the start menu, which comes with SQL Developer installation package)

Step 2: Run the following commands:

enter image description here

Note: If password has already expired, Changing password for <user> option will automatically come.

Job for mysqld.service failed See "systemctl status mysqld.service"

I had the same error, the problem was because I no longer had disk space. to check the space run this:

$ df -h

disk space

Then delete some files that you didn't need.

After this commands:

service mysql start
systemctl status mysql.service
mysql -u root -p

After entering with the root password verify that the mysql service was active

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

Opacity of div's background without affecting contained element in IE 8?

It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.

CSS: How can I set image size relative to parent height?

If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.

.img-fill > img {
  min-height: 100%;
  min-width: 100%;  
}

What does T&& (double ampersand) mean in C++11?

It declares an rvalue reference (standards proposal doc).

Here's an introduction to rvalue references.

Here's a fantastic in-depth look at rvalue references by one of Microsoft's standard library developers.

CAUTION: the linked article on MSDN ("Rvalue References: C++0x Features in VC10, Part 2") is a very clear introduction to Rvalue references, but makes statements about Rvalue references that were once true in the draft C++11 standard, but are not true for the final one! Specifically, it says at various points that rvalue references can bind to lvalues, which was once true, but was changed.(e.g. int x; int &&rrx = x; no longer compiles in GCC) – drewbarbs Jul 13 '14 at 16:12

The biggest difference between a C++03 reference (now called an lvalue reference in C++11) is that it can bind to an rvalue like a temporary without having to be const. Thus, this syntax is now legal:

T&& r = T();

rvalue references primarily provide for the following:

Move semantics. A move constructor and move assignment operator can now be defined that takes an rvalue reference instead of the usual const-lvalue reference. A move functions like a copy, except it is not obliged to keep the source unchanged; in fact, it usually modifies the source such that it no longer owns the moved resources. This is great for eliminating extraneous copies, especially in standard library implementations.

For example, a copy constructor might look like this:

foo(foo const& other)
{
    this->length = other.length;
    this->ptr = new int[other.length];
    copy(other.ptr, other.ptr + other.length, this->ptr);
}

If this constructor was passed a temporary, the copy would be unnecessary because we know the temporary will just be destroyed; why not make use of the resources the temporary already allocated? In C++03, there's no way to prevent the copy as we cannot determine we were passed a temporary. In C++11, we can overload a move constructor:

foo(foo&& other)
{
   this->length = other.length;
   this->ptr = other.ptr;
   other.length = 0;
   other.ptr = nullptr;
}

Notice the big difference here: the move constructor actually modifies its argument. This would effectively "move" the temporary into the object being constructed, thereby eliminating the unnecessary copy.

The move constructor would be used for temporaries and for non-const lvalue references that are explicitly converted to rvalue references using the std::move function (it just performs the conversion). The following code both invoke the move constructor for f1 and f2:

foo f1((foo())); // Move a temporary into f1; temporary becomes "empty"
foo f2 = std::move(f1); // Move f1 into f2; f1 is now "empty"

Perfect forwarding. rvalue references allow us to properly forward arguments for templated functions. Take for example this factory function:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1& a1)
{
    return std::unique_ptr<T>(new T(a1));
}

If we called factory<foo>(5), the argument will be deduced to be int&, which will not bind to a literal 5, even if foo's constructor takes an int. Well, we could instead use A1 const&, but what if foo takes the constructor argument by non-const reference? To make a truly generic factory function, we would have to overload factory on A1& and on A1 const&. That might be fine if factory takes 1 parameter type, but each additional parameter type would multiply the necessary overload set by 2. That's very quickly unmaintainable.

rvalue references fix this problem by allowing the standard library to define a std::forward function that can properly forward lvalue/rvalue references. For more information about how std::forward works, see this excellent answer.

This enables us to define the factory function like this:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1&& a1)
{
    return std::unique_ptr<T>(new T(std::forward<A1>(a1)));
}

Now the argument's rvalue/lvalue-ness is preserved when passed to T's constructor. That means that if factory is called with an rvalue, T's constructor is called with an rvalue. If factory is called with an lvalue, T's constructor is called with an lvalue. The improved factory function works because of one special rule:

When the function parameter type is of the form T&& where T is a template parameter, and the function argument is an lvalue of type A, the type A& is used for template argument deduction.

Thus, we can use factory like so:

auto p1 = factory<foo>(foo()); // calls foo(foo&&)
auto p2 = factory<foo>(*p1);   // calls foo(foo const&)

Important rvalue reference properties:

  • For overload resolution, lvalues prefer binding to lvalue references and rvalues prefer binding to rvalue references. Hence why temporaries prefer invoking a move constructor / move assignment operator over a copy constructor / assignment operator.
  • rvalue references will implicitly bind to rvalues and to temporaries that are the result of an implicit conversion. i.e. float f = 0f; int&& i = f; is well formed because float is implicitly convertible to int; the reference would be to a temporary that is the result of the conversion.
  • Named rvalue references are lvalues. Unnamed rvalue references are rvalues. This is important to understand why the std::move call is necessary in: foo&& r = foo(); foo f = std::move(r);

Handling optional parameters in javascript

I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.

I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)

This is what the implementation looks like:

function displayOverlay(/*message, timeout, callback*/) {
  return arrangeArgs(arguments, String, Number, Function, 
    function(message, timeout, callback) {
      /* ... your code ... */
    });
};

For clarity, here is what is going on:

function displayOverlay(/*message, timeout, callback*/) {
  //arrangeArgs is the proxy
  return arrangeArgs(
           //first pass in the original arguments
           arguments, 
           //then pass in the type for each argument
           String,  Number,  Function, 
           //lastly, pass in your function and the proxy will do the rest!
           function(message, timeout, callback) {

             //debug output of each argument to verify it's working
             console.log("message", message, "timeout", timeout, "callback", callback);

             /* ... your code ... */

           }
         );
};

You can view the arrangeArgs proxy code in my GitHub repository here:

https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js

Here is the utility function with some comments copied from the repository:

/*
 ****** Overview ******
 * 
 * Strongly type a function's arguments to allow for any arguments to be optional.
 * 
 * Other resources:
 * http://ejohn.org/blog/javascript-method-overloading/
 * 
 ****** Example implementation ******
 * 
 * //all args are optional... will display overlay with default settings
 * var displayOverlay = function() {
 *   return Sysmo.optionalArgs(arguments, 
 *            String, [Number, false, 0], Function, 
 *            function(message, timeout, callback) {
 *              var overlay = new Overlay(message);
 *              overlay.timeout = timeout;
 *              overlay.display({onDisplayed: callback});
 *            });
 * }
 * 
 ****** Example function call ******
 * 
 * //the window.alert() function is the callback, message and timeout are not defined.
 * displayOverlay(alert);
 * 
 * //displays the overlay after 500 miliseconds, then alerts... message is not defined.
 * displayOverlay(500, alert);
 * 
 ****** Setup ******
 * 
 * arguments = the original arguments to the function defined in your javascript API.
 * config = describe the argument type
 *  - Class - specify the type (e.g. String, Number, Function, Array) 
 *  - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
 *                                         The "boolean" indicates if the first value should be treated as a function.
 *                                         The "default" is an optional default value to use instead of undefined.
 * 
 */
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
  //config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
  //config doesn't need a default value.
  //config can also be classes instead of an array if not required and no default value.

  var configs = Sysmo.makeArray(arguments),
      values = Sysmo.makeArray(configs.shift()),
      callback = configs.pop(),
      args = [],
      done = function() {
        //add the proper number of arguments before adding remaining values
        if (!args.length) {
          args = Array(configs.length);
        }
        //fire callback with args and remaining values concatenated
        return callback.apply(null, args.concat(values));
      };

  //if there are not values to process, just fire callback
  if (!values.length) {
    return done();
  }

  //loop through configs to create more easily readable objects
  for (var i = 0; i < configs.length; i++) {

    var config = configs[i];

    //make sure there's a value
    if (values.length) {

      //type or validator function
      var fn = config[0] || config,
          //if config[1] is true, use fn as validator, 
          //otherwise create a validator from a closure to preserve fn for later use
          validate = (config[1]) ? fn : function(value) {
            return value.constructor === fn;
          };

      //see if arg value matches config
      if (validate(values[0])) {
        args.push(values.shift());
        continue;
      }
    }

    //add a default value if there is no value in the original args
    //or if the type didn't match
    args.push(config[2]);
  }

  return done();
}

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

How to compute the similarity between two text documents?

Here's a little app to get you started...

import difflib as dl

a = file('file').read()
b = file('file1').read()

sim = dl.get_close_matches

s = 0
wa = a.split()
wb = b.split()

for i in wa:
    if sim(i, wb):
        s += 1

n = float(s) / float(len(wa))
print '%d%% similarity' % int(n * 100)

How do I watch a file for changes?

Have you already looked at the documentation available on http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html? If you only need it to work under Windows the 2nd example seems to be exactly what you want (if you exchange the path of the directory with one of the files you want to watch).

Otherwise, polling will probably be the only really platform-independent option.

Note: I haven't tried any of these solutions.

Another git process seems to be running in this repository

If you are on PowerShell, use

rm -Force .git/index.lock

Local variable referenced before assignment?

When Python parses the body of a function definition and encounters an assignment such as

feed = ...

Python interprets feed as a local variable by default. If you do not wish for it to be a local variable, you must put

global feed

in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes feed a global variable everywhere in the function.

Without the global statement, since feed is taken to be a local variable, when Python executes

feed = feed + 1,

Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds feed is undefined. Hence the error.

The shortest way to patch up the code is to add global feed to the beginning of onLoadFinished. The nicer way is to use a class:

class Page(object):
    def __init__(self):
        self.feed = 0
    def onLoadFinished(self, result):
        ...
        self.feed += 1

The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand.

By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.

How to make the Facebook Like Box responsive?

Colin's example for me clashed with the like button. So I adapted it to only target the Like Box.

.fb-like-box, .fb-like-box span, .fb-like-box span iframe[style] { width: 100% !important; }

Tested in most modern browsers.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

You can try this way:

open('u.item', encoding='utf8', errors='ignore')

Passing javascript variable to html textbox

document.getElementById("txtBillingGroupName").value = groupName;

How to use null in switch

You can't. You can use primitives (int, char, short, byte) and String (Strings in java 7 only) in switch. primitives can't be null.
Check i in separate condition before switch.

How do I enable saving of filled-in fields on a PDF form?

If you are using Adobe Acrobat X to make the form, set all the fields as you want them, then click File, Save As, Reader Extended PDF, Enable Additional Features. The resulting PDF form can be saved when filled in, if opened in versions of Adobe Reader before XI.

Mapping object to dictionary and vice versa

Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:

[TestMethod]
public void DictionaryTest()
{
    var item = new SomeCLass { Id = "1", Name = "name1" };
    IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
    var obj = ObjectFromDictionary<SomeCLass>(dict);
}

private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
    where T : class 
{
    Type type = typeof(T);
    T result = (T)Activator.CreateInstance(type);
    foreach (var item in dict)
    {
        type.GetProperty(item.Key).SetValue(result, item.Value, null);
    }
    return result;
}

private IDictionary<string, object> ObjectToDictionary<T>(T item)
    where T: class
{
    Type myObjectType = item.GetType();
    IDictionary<string, object> dict = new Dictionary<string, object>();
    var indexer = new object[0];
    PropertyInfo[] properties = myObjectType.GetProperties();
    foreach (var info in properties)
    {
        var value = info.GetValue(item, indexer);
        dict.Add(info.Name, value);
    }
    return dict;
}

Mocking python function based on input arguments

Just to show another way of doing it:

def mock_isdir(path):
    return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']

with mock.patch('os.path.isdir') as os_path_isdir:
    os_path_isdir.side_effect = mock_isdir

How can I perform a reverse string search in Excel without using VBA?

Imagine the string could be reversed. Then it is really easy. Instead of working on the string:

"My little cat" (1)

you work with

"tac elttil yM" (2)

With =LEFT(A1;FIND(" ";A1)-1) in A2 you get "My" with (1) and "tac" with (2), which is reversed "cat", the last word in (1).

There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString.

Install the above as described. Then with your string in A1, e.g., "My little cat" and this function in A2:

=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
  LEN(A1);(FIND(" ";ReverseString(A1))-1))))

you'll see "cat" in A2.

The method above assumes that words are separated by blanks. The IF clause is for cells containing single words = no blanks in cell. Note: TRIM and CLEAN the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "). LEFT picks this word and another string reversal reconstitutes the original order of the word (" cat"). The -1 at the end of the FIND statement removes the blank.

The idea is that it is easy to extract the first(!) word in a string with LEFT and FINDing the first blank. However, for the last(!) word the RIGHT function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.

Therefore the whole string is simply reversed. LEFT and FIND work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString statement in the formula does this job.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Escaping a forward slash in a regular expression

If the delimiter is /, you will need to escape.

Inline instantiation of a constant List

You'll need to use a static readonly list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T> rather than List<T>.

private static readonly ReadOnlyCollection<string> _metrics =
    new ReadOnlyCollection<string>(new[]
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        });

public static ReadOnlyCollection<string> Metrics
{
    get { return _metrics; }
}

Templated check for the existence of a class member function?

There are a lot of answers here, but I failed, to find a version, that performs real method resolution ordering, while not using any of the newer c++ features (only using c++98 features).
Note: This version is tested and working with vc++2013, g++ 5.2.0 and the onlline compiler.

So I came up with a version, that only uses sizeof():

template<typename T> T declval(void);

struct fake_void { };
template<typename T> T &operator,(T &,fake_void);
template<typename T> T const &operator,(T const &,fake_void);
template<typename T> T volatile &operator,(T volatile &,fake_void);
template<typename T> T const volatile &operator,(T const volatile &,fake_void);

struct yes { char v[1]; };
struct no  { char v[2]; };
template<bool> struct yes_no:yes{};
template<> struct yes_no<false>:no{};

template<typename T>
struct has_awesome_member {
 template<typename U> static yes_no<(sizeof((
   declval<U>().awesome_member(),fake_void()
  ))!=0)> check(int);
 template<typename> static no check(...);
 enum{value=sizeof(check<T>(0)) == sizeof(yes)};
};


struct foo { int awesome_member(void); };
struct bar { };
struct foo_void { void awesome_member(void); };
struct wrong_params { void awesome_member(int); };

static_assert(has_awesome_member<foo>::value,"");
static_assert(!has_awesome_member<bar>::value,"");
static_assert(has_awesome_member<foo_void>::value,"");
static_assert(!has_awesome_member<wrong_params>::value,"");

Live demo (with extended return type checking and vc++2010 workaround): http://cpp.sh/5b2vs

No source, as I came up with it myself.

When running the Live demo on the g++ compiler, please note that array sizes of 0 are allowed, meaning that the static_assert used will not trigger a compiler error, even when it fails.
A commonly used work-around is to replace the 'typedef' in the macro with 'extern'.

How to retrieve the dimensions of a view?

Even though the proposed solution works, it might not be the best solution for every case because based on the documentation for ViewTreeObserver.OnGlobalLayoutListener

Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

which means it gets called many times and not always the view is measured (it has its height and width determined)

An alternative is to use ViewTreeObserver.OnPreDrawListener which gets called only when the view is ready to be drawn and has all of its measurements.

final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {

    @Override
    public void onPreDraw() {
        tv.getViewTreeObserver().removeOnPreDrawListener(this);
        // Your view will have valid height and width at this point
        tv.getHeight();
        tv.getWidth();
    }

});

Post to another page within a PHP script

Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).

Sample snippet:

//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
                      'lname'=>urlencode($last_name),
                      'fname'=>urlencode($first_name),
                      'email'=>urlencode($email)
               );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

Credits go to http://php.dzone.com. Also, don't forget to visit the appropriate page(s) in the PHP Manual

An attempt was made to access a socket in a way forbidden by its access permissions

Not surprisingly, this error can arise when another process is listening on the desired port. This happened today when I started an instance of the Apache Web server, listening on its default port (80), having forgotten that I already had IIS 7 running, and listening on that port. This is well explained in Port 80 is being used by SYSTEM (PID 4), what is that? Better yet, that article points to Stop http.sys from listening on port 80 in Windows, which explains a very simple way to resolve it, with just a tad of help from an elevated command prompt and a one-line edit of my hosts file.

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}