Programs & Examples On #Multiple definition error

Refers to a compiler error for multiple declarations of a variable, function, or class in the same program or project. Often meant to be the same, the programmer just accidentally re-initializes the object.

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

"Multiple definition", "first defined here" errors

I had a similar issue when not using inline for my global function that was included in two places.

Array.push() if does not exist?

My choice was to use .includes() extending the Array.prototype as @Darrin Dimitrov suggested:

Array.prototype.pushIfNotIncluded = function (element) {
    if (!this.includes(element)) {
      array.push(element);
    }
}

Just remembering that includes comes from es6 and does not work on IE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

How to set a default value for an existing column

ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn

"commence before first target. Stop." error

Also, make sure you dont have a space after \ in previous line Else this is the error

How to debug Google Apps Script (aka where does Logger.log log to?)

I've gone through these posts and somehow ended up finding a simple answer, which I'm posting here for those how want short and sweet solutions:

  1. Use console.log("Hello World") in your script.
  2. Go to https://script.google.com/home/my and select your add-on.
  3. Click on the ellipsis menu on Project Details, select Executions.

enter image description here

  1. Click on the header of the latest execution and read the log.

enter image description here

How to delete the top 1000 rows from a table using Sql Server 2008?

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

How to limit the maximum files chosen when using multiple file input

In javascript you can do something like this

<input
  ref="fileInput"
  multiple
  type="file"
  style="display: none"
  @change="trySubmitFile"
>

and the function can be something like this.

trySubmitFile(e) {
  if (this.disabled) return;
  const files = e.target.files || e.dataTransfer.files;
  if (files.length > 5) {
    alert('You are only allowed to upload a maximum of 2 files at a time');
  }
  if (!files.length) return;
  for (let i = 0; i < Math.min(files.length, 2); i++) {
    this.fileCallback(files[i]);
  }
}

I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.

Two div blocks on same line

Try an HTML table or use the following CSS :

<div id="bloc1" style="float:left">...</div>
<div id="bloc2">...</div>

(or use an HTML table)

PermissionError: [Errno 13] Permission denied

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

Resetting a form in Angular 2 after submit

I'm using reactive forms in angular 4 and this approach works for me:

    this.profileEditForm.reset(this.profileEditForm.value);

see reset the form flags in the Fundamentals doc

Common Header / Footer with static HTML

You can do it with javascript, and I don't think it needs to be that fancy.

If you have a header.js file and a footer.js.

Then the contents of header.js could be something like

document.write("<div class='header'>header content</div> etc...")

Remember to escape any nested quote characters in the string you are writing. You could then call that from your static templates with

<script type="text/javascript" src="header.js"></script>

and similarly for the footer.js.

Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

Laravel - Eloquent or Fluent random row

This works just fine,

$model=Model::all()->random(1)->first();

you can also change argument in random function to get more than one record.

Note: not recommended if you have huge data as this will fetch all rows first and then returns random value.

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

How to add fonts to create-react-app based projects?

Here are some ways of doing this:

1. Importing font

For example, for using Roboto, install the package using

yarn add typeface-roboto

or

npm install typeface-roboto --save

In index.js:

import "typeface-roboto";

There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.

2. For fonts hosted by Third party

For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html

screenshot of fonts.google.com

It'll be like

<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Montserrat');
</style>

3. Downloading the font and adding it in your source code.

Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.

Move the font to fonts directory in your src directory

src
|
`----fonts
|      |
|      `-Lato/Lato-Black.ttf
|       -Lato/Lato-BlackItalic.ttf
|       -Lato/Lato-Bold.ttf
|       -Lato/Lato-BoldItalic.ttf
|       -Lato/Lato-Italic.ttf
|       -Lato/Lato-Light.ttf
|       -Lato/Lato-LightItalic.ttf
|       -Lato/Lato-Regular.ttf
|       -Lato/Lato-Thin.ttf
|       -Lato/Lato-ThinItalic.ttf
|
`----App.css

Now, in App.css, add this

@font-face {
  font-family: 'Lato';
  src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}

@font-face {
    font-family: 'Lato';
    font-weight: 900;
    src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
}

@font-face {
    font-family: 'Lato';
    font-weight: 900;
    src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
}

For ttf format, you have to mention format('truetype'). For woff, format('woff')

Now you can use the font in classes.

.modal-title {
    font-family: Lato, Arial, serif;
    font-weight: black;
}

4. Using web-font-loader package

Install package using

yarn add webfontloader

or

npm install webfontloader --save

In src/index.js, you can import this and specify the fonts needed

import WebFont from 'webfontloader';

WebFont.load({
   google: {
     families: ['Titillium Web:300,400,700', 'sans-serif']
   }
});

How to determine when Fragment becomes visible in ViewPager

May be very late. This is working for me. I slightly updated the code from @Gobar and @kris Solutions. We have to update the code in our PagerAdapter.

setPrimaryItem is called every time when a tab is visible and returns its position. If the position are same means we are unmoved. If position changed and current position is not our clicked tab set as -1.

private int mCurrentPosition = -1;

@Override
public void setPrimaryItem(@NotNull ViewGroup container, int position, @NotNull Object object) {
    // This is what calls setMenuVisibility() on the fragments
    super.setPrimaryItem(container, position, object);
    if (position == mCurrentPosition) {
        return;
    }
    if (object instanceof YourFragment) {
        YourFragment fragment = (YourFragment) object;
        if (fragment.isResumed()) {
            mCurrentPosition = position;
            fragment.doYourWork();//Update your function
        }
    } else {
        mCurrentPosition = -1;
    }
}

VB.NET: Clear DataGridView

You can do in this way:

DataGridView1.Enable = false
DataGridView1.DataSource = Nothing
DataGridView1.Enable = true

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

What is the effect of encoding an image in base64?

It will be approximately 37% larger:

Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size

Source: http://en.wikipedia.org/wiki/Base64

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

ASP.NET Core Get Json Array using IConfiguration

You can get the array direct without increment a new level in the configuration:

public void ConfigureServices(IServiceCollection services) {
    services.Configure<List<String>>(Configuration.GetSection("MyArray"));
    //...
}

Compiling an application for use in highly radioactive environments

What could help you is a watchdog. Watchdogs were used extensively in industrial computing in the 1980s. Hardware failures were much more common then - another answer also refers to that period.

A watchdog is a combined hardware/software feature. The hardware is a simple counter that counts down from a number (say 1023) to zero. TTL or other logic could be used.

The software has been designed as such that one routine monitors the correct operation of all essential systems. If this routine completes correctly = finds the computer running fine, it sets the counter back to 1023.

The overall design is so that under normal circumstances, the software prevents that the hardware counter will reach zero. In case the counter reaches zero, the hardware of the counter performs its one-and-only task and resets the entire system. From a counter perspective, zero equals 1024 and the counter continues counting down again.

This watchdog ensures that the attached computer is restarted in a many, many cases of failure. I must admit that I'm not familiar with hardware that is able to perform such a function on today's computers. Interfaces to external hardware are now a lot more complex than they used to be.

An inherent disadvantage of the watchdog is that the system is not available from the time it fails until the watchdog counter reaches zero + reboot time. While that time is generally much shorter than any external or human intervention, the supported equipment will need to be able to proceed without computer control for that timeframe.

Close a MessageBox after several seconds

There is an codeproject project avaliable HERE that provides this functuanility.

Following many threads here on SO and other boards this cant be done with the normal MessageBox.

Edit:

I have an idea that is a bit ehmmm yeah..

Use a timer and start in when the MessageBox appears. If your MessageBox only listens to the OK Button (only 1 possibility) then use the OnTick-Event to emulate an ESC-Press with SendKeys.Send("{ESC}"); and then stop the timer.

Get textarea text with javascript or Jquery

Try .html() instead of .val() :

var text = $('#frame1').contents().find('#area1').html();

How do I get elapsed time in milliseconds in Ruby?

%L gives milliseconds in ruby

require 'time'
puts Time.now.strftime("%Y-%m-%dT%H:%M:%S.%L")

or

puts Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")

will give you current timestamp in milliseconds.

Convert A String (like testing123) To Binary In Java

You can also do this with the ol' good method :

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

SQL, How to convert VARCHAR to bigint?

This is the answer

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

Taking screenshot on Emulator from Android Studio

Click on Camera icon that is there on the right to emulator in action icons list. This is available on latest studio, though I am not sure from which version.

enter image description here

Set focus on <input> element

I'm having same scenario, this worked for me but i'm not having the "hide/show" feature you have. So perhaps you could first check if you get the focus when you have the field always visible, and then try to solve why does not work when you change visibility (probably that's why you need to apply a sleep or a promise)

To set focus, this is the only change you need to do:

your Html mat input should be:

<input #yourControlName matInput>

in your TS class, reference like this in the variables section (

export class blabla...
    @ViewChild("yourControlName") yourControl : ElementRef;

Your button it's fine, calling:

  showSearch(){
       ///blabla... then finally:
       this.yourControl.nativeElement.focus();
}

and that's it. You can check this solution on this post that I found, so thanks to --> https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

How to get the start time of a long-running Linux process?

    ps -eo pid,cmd,lstart | grep YOUR-PID-HERE

Configuring IntelliJ IDEA for unit testing with JUnit

One way of doing this is to do add junit.jar to your $CLASSPATH as an external dependency.

adding junit intellij

So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.

In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.

How to get last items of a list in Python?

The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.

>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]

matching query does not exist Error in Django

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

HTML5 live streaming

Right now it will only work in some browsers, and as far as I can see you haven't actually linked to a file, so that would explain why it is not playing.

but as you want a live stream (which I have not tested with)

check out Streaming via RTSP or RTP in HTML5

and http://www.streamingmedia.com/Articles/Editorial/Featured-Articles/25-HTML5-Video-Resources-You-Might-Have-Missed-74010.aspx

How to remove focus around buttons on click

I just had this same problem on MacOS and Chrome while using a button to trigger a "transition" event. If anyone reading this is already using an event listener, you can solve it by calling .blur() after your actions.

Example:

 nextQuestionButtonEl.click(function(){
    if (isQuestionAnswered()) {
        currentQuestion++;
        changeQuestion();
    } else {
        toggleNotification("invalidForm");
    }
    this.blur();
});

Though if you're not using an event listener already, adding one just to solve this might add unnecessary overhead and a styling solution like previous answers provide is better.

File Upload to HTTP server in iphone programming

ASIHTTPRequest is a great wrapper around the network APIs and makes it very easy to upload a file. Here's their example (but you can do this on the iPhone too - we save images to "disk" and later upload them.

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

Toggle visibility property of div

It's better if you check visibility like this: if($('#video-over').is(':visible'))

Replace all spaces in a string with '+'

Here's an alternative that doesn't require regex:

var str = 'a b c';
var replaced = str.split(' ').join('+');

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case checking the check-box

"Copy project into workspace"

did the trick.

How can I remove time from date with Moment.js?

The correct way would be to specify the input as per your requirement which will give you more flexibility.

The present definition includes the following

LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A'

You can use any of these or change the input passed into moment().format(). For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').

CSS3 transition on click using pure CSS

If you want a css only solution you can use active

.crossRotate:active {
   transform: rotate(45deg);
   -webkit-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
}

But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).

$( ".crossRotate" ).click(function() {
    if (  $( this ).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(45deg)");
    } else {
        $(this).css("transform","" );
    }
});

Fiddle

Python class input argument

Remove the name param from the class declaration. The init method is used to pass arguments to a class at creation.

class Person(object):
  def __init__(self, name):
    self.name = name

me = Person("TheLazyScripter")
print me.name

UITextView that expands to text using auto layout

Here's a quick solution:

This problem may occur if you have set clipsToBounds property to false of your textview. If you simply delete it, the problem goes away.

myTextView.clipsToBounds = false //delete this line

Set up git to pull and push all branches

To see all the branches with out using git branch -a you should execute:

for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all

Now you can see all the branches:

git branch

To push all the branches try:

git push --all

invalid use of incomplete type

You derive B from A<B>, so the first thing the compiler does, once it sees the definition of class B is to try to instantiate A<B>. To do this it needs to known B::mytype for the parameter of action. But since the compiler is just in the process of figuring out the actual definition of B, it doesn't know this type yet and you get an error.

One way around this is would be to declare the parameter type as another template parameter, instead of inside the derived class:

template<typename Subclass, typename Param>
class A {
    public:
        void action(Param var) {
                (static_cast<Subclass*>(this))->do_action(var);
        }
};

class B : public A<B, int> { ... };

How do I get the resource id of an image if I know its name?

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

How to replicate vector in c?

Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:

uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
    printf("%d\n", v.data[i]);
uivector_cleanup(&v);

As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.

nothings/stb gives a simpler implementation that works with any types, but compiles only in C:

double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
    printf("%g\n", v[i]);
sb_free(v);

A lot of C code, however, resorts to managing the memory directly with realloc:

void* newMem = realloc(oldMem, newSize);
if(!newMem) {
    // handle error
}
oldMem = newMem;

Note that realloc returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:

oldMem = realloc(oldMem, newSize);
if(!oldMem) {
    // handle error
}

Compared to std::vector and the C equivalents from above, the simple realloc method does not provide O(1) amortized guarantee, even though realloc may sometimes be more efficient if it happens to avoid moving the memory around.

Get the content of a sharepoint folder with Excel VBA

In addition to:

myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")

also replace space:

myFilePath = replace(myFilePath, " ", "%20")

What's the purpose of git-mv?

As @Charles says, git mv is a shorthand.

The real question here is "Other version control systems (eg. Subversion and Perforce) treat file renames specially. Why doesn't Git?"

Linus explains at http://permalink.gmane.org/gmane.comp.version-control.git/217 with characteristic tact:

Please stop this "track files" crap. Git tracks exactly what matters, namely "collections of files". Nothing else is relevant, and even thinking that it is relevant only limits your world-view. Notice how the notion of CVS "annotate" always inevitably ends up limiting how people use it. I think it's a totally useless piece of crap, and I've described something that I think is a million times more useful, and it all fell out exactly because I'm not limiting my thinking to the wrong model of the world.

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

Git Push ERROR: Repository not found

I ran into the same issue on a MAC trying to pull from a private repo i was previously connected to.

I solved it by including my username in the repo url:

git remote set-url origin https://<YOUR_USER_NAME_HERE>@github.com/<YOUR_USER_NAME_HERE>/<REPO>.git

Then i was able to pull from the repo.

For a new repo you want to clone:

git clone https://<YOUR_USER_NAME_HERE>@github.com/<YOUR_USER_NAME_HERE>/<REPO>.git    

It will prompt you to enter your password to that account, you're good to go afterwards.

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

PHP Checking if the current date is before or after a set date

if( strtotime($database_date) > strtotime('now') ) {
...

Get full URL and query string in Servlet for both HTTP and HTTPS requests

The fact that a HTTPS request becomes HTTP when you tried to construct the URL on server side indicates that you might have a proxy/load balancer (nginx, pound, etc.) offloading SSL encryption in front and forward to your back end service in plain HTTP.

If that's case, check,

  1. whether your proxy has been set up to forward headers correctly (Host, X-forwarded-proto, X-forwarded-for, etc).
  2. whether your service container (E.g. Tomcat) is set up to recognize the proxy in front. For example, Tomcat requires adding secure="true" scheme="https" proxyPort="443" attributes to its Connector
  3. whether your code, or service container is processing the headers correctly. For example, Tomcat automatically replaces scheme, remoteAddr, etc. values when you add RemoteIpValve to its Engine. (see Configuration guide, JavaDoc) so you don't have to process these headers in your code manually.

Incorrect proxy header values could result in incorrect output when request.getRequestURI() or request.getRequestURL() attempts to construct the originating URL.

Android Gradle Apache HttpClient does not exist?

Perfect Answer by Jinu and Daniel

Adding to this I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)

compile ('org.apache.httpcomponents:httpmime:4.3'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'

else if your compileSdkVersion is 23 then use

android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    }
}

Global keyboard capture in C# application

As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT. I've commented most of it.

The Setup

class GlobalKeyboardHookEventArgs : HandledEventArgs
{
    public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
    public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

    public GlobalKeyboardHookEventArgs(
        GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
        GlobalKeyboardHook.KeyboardState keyboardState)
    {
        KeyboardData = keyboardData;
        KeyboardState = keyboardState;
    }
}

//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
    public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

    // EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
    // the logging mechanism.
    /// <summary>
    /// 
    /// </summary>
    /// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
    public GlobalKeyboardHook(Keys[] registeredKeys = null)
    {
        RegisteredKeys = registeredKeys;
        _windowsHookHandle = IntPtr.Zero;
        _user32LibraryHandle = IntPtr.Zero;
        _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

        _user32LibraryHandle = LoadLibrary("User32");
        if (_user32LibraryHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }



        _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
        if (_windowsHookHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // because we can unhook only in the same thread, not in garbage collector thread
            if (_windowsHookHandle != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(_windowsHookHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _windowsHookHandle = IntPtr.Zero;

                // ReSharper disable once DelegateSubtraction
                _hookProc -= LowLevelKeyboardProc;
            }
        }

        if (_user32LibraryHandle != IntPtr.Zero)
        {
            if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
            _user32LibraryHandle = IntPtr.Zero;
        }
    }

    ~GlobalKeyboardHook()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private IntPtr _windowsHookHandle;
    private IntPtr _user32LibraryHandle;
    private HookProc _hookProc;

    delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool FreeLibrary(IntPtr hModule);

    /// <summary>
    /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
    /// You would install a hook procedure to monitor the system for certain types of events. These events are
    /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
    /// </summary>
    /// <param name="idHook">hook type</param>
    /// <param name="lpfn">hook procedure</param>
    /// <param name="hMod">handle to application instance</param>
    /// <param name="dwThreadId">thread identifier</param>
    /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

    /// <summary>
    /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">handle to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);

    /// <summary>
    /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
    /// A hook procedure can call this function either before or after processing the hook information.
    /// </summary>
    /// <param name="hHook">handle to current hook</param>
    /// <param name="code">hook code passed to hook procedure</param>
    /// <param name="wParam">value passed to hook procedure</param>
    /// <param name="lParam">value passed to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

    [StructLayout(LayoutKind.Sequential)]
    public struct LowLevelKeyboardInputEvent
    {
        /// <summary>
        /// A virtual-key code. The code must be a value in the range 1 to 254.
        /// </summary>
        public int VirtualCode;

        // EDT: added a conversion from VirtualCode to Keys.
        /// <summary>
        /// The VirtualCode converted to typeof(Keys) for higher usability.
        /// </summary>
        public Keys Key { get { return (Keys)VirtualCode; } }

        /// <summary>
        /// A hardware scan code for the key. 
        /// </summary>
        public int HardwareScanCode;

        /// <summary>
        /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
        /// </summary>
        public int Flags;

        /// <summary>
        /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
        /// </summary>
        public int TimeStamp;

        /// <summary>
        /// Additional information associated with the message. 
        /// </summary>
        public IntPtr AdditionalInformation;
    }

    public const int WH_KEYBOARD_LL = 13;
    //const int HC_ACTION = 0;

    public enum KeyboardState
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SysKeyDown = 0x0104,
        SysKeyUp = 0x0105
    }

    // EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
    public static Keys[] RegisteredKeys;
    const int KfAltdown = 0x2000;
    public const int LlkhfAltdown = (KfAltdown >> 8);

    public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        bool fEatKeyStroke = false;

        var wparamTyped = wParam.ToInt32();
        if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
        {
            object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
            LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

            var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

            // EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
            // Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
            // has to be null for the event to get fired.
            var key = (Keys)p.VirtualCode;
            if (RegisteredKeys == null || RegisteredKeys.Contains(key))
            {
                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }
        }

        return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
    }
}

The Usage differences can be seen here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private GlobalKeyboardHook _globalKeyboardHook;

    private void buttonHook_Click(object sender, EventArgs e)
    {
        // Hooks only into specified Keys (here "A" and "B").
        _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

        // Hooks into all keys.
        _globalKeyboardHook = new GlobalKeyboardHook();
        _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
    }

    private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
    {
        // EDT: No need to filter for VkSnapshot anymore. This now gets handled
        // through the constructor of GlobalKeyboardHook(...).
        if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
        {
            // Now you can access both, the key and virtual code
            Keys loggedKey = e.KeyboardData.Key;
            int loggedVkCode = e.KeyboardData.VirtualCode;
        }
    }
}

Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.

What is the most effective way to get the index of an iterator of an std::vector?

Here is an example to find "all" occurrences of 10 along with the index. Thought this would be of some help.

void _find_all_test()
{
    vector<int> ints;
    int val;
    while(cin >> val) ints.push_back(val);

    vector<int>::iterator it;
    it = ints.begin();
    int count = ints.size();
    do
    {
        it = find(it,ints.end(), 10);//assuming 10 as search element
        cout << *it << " found at index " << count -(ints.end() - it) << endl;
    }while(++it != ints.end()); 
}

Import a file from a subdirectory?

try this:

from lib import BoxTime

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

Hive: Convert String to Integer

If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work

    hive> select cast('2147483647' as int);
    OK
    2147483647
    
    hive> select cast('2147483648' as int);
    OK
    NULL
    
    hive> select cast('2147483648' as bigint);
    OK
    2147483648

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

Jquery submit form

Try this :

$('#form1').submit();

or

document.form1.submit();

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
                                              func.date(User.birthday) <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59

Read properties file outside JAR file

This works for me. Load your properties file from current directory.

Attention: The method Properties#load uses ISO-8859-1 encoding.

Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + "java.properties"));
properties.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

Make sure, that java.properties is at the current directory . You can just write a little startup script that switches into to the right directory in before, like

#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
cd $scriptdir
java -jar MyExecutable.jar
cd -

In your project just put the java.properties file in your project root, in order to make this code work from your IDE as well.

Left padding a String with Zeros

Here's my solution:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Output: 00000101

How to count the number of occurrences of a character in an Oracle varchar value?

Here's an idea: try replacing everything that is not a dash char with empty string. Then count how many dashes remained.

select length(regexp_replace('123-345-566', '[^-]', '')) from dual

Importing project into Netbeans

If there is already a nbproject folder it means you can open it straight ahead without importing it as a project with existing sources (ctrl+shift+o) or (cmd+shift+o)

Regular expression to remove HTML tags from a string

You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.


The following examples are Java, but the regex will be similar -- if not identical -- for other languages.


String target = someString.replaceAll("<[^>]*>", "");

Assuming your non-html does not contain any < or > and that your input string is correctly structured.

If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:

String target = someString.replaceAll("(?i)<td[^>]*>", "");

Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.

For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();

This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

there are gotchas with this - but ultimately the simplest way will be to use

string s = [yourlongstring];
string[] values = s.Split(',');

If the number of commas and entries isn't important, and you want to get rid of 'empty' values then you can use

string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

One thing, though - this will keep any whitespace before and after your strings. You could use a bit of Linq magic to solve that:

string[] values = s.Split(',').Select(sValue => sValue.Trim()).ToArray();

That's if you're using .Net 3.5 and you have the using System.Linq declaration at the top of your source file.

How to make an HTTP get request with parameters

The WebRequest object seems like too much work for me. I prefer to use the WebClient control.

To use this function you just need to create two NameValueCollections holding your parameters and request headers.

Consider the following function:

    private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
    {
        string ResponseText = null;
        using (WebClient client = new WebClient())
        {
            try
            {
                if (RequestHeaders != null)
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (string header in RequestHeaders.AllKeys)
                            client.Headers.Add(header, RequestHeaders[header]);
                    }
                }
                if (QueryStringParameters != null)
                {
                    if (QueryStringParameters.Count > 0)
                    {
                        foreach (string parm in QueryStringParameters.AllKeys)
                            client.QueryString.Add(parm, QueryStringParameters[parm]);
                    }
                }
                byte[] ResponseBytes = client.DownloadData(URL);
                ResponseText = Encoding.UTF8.GetString(ResponseBytes);
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();

                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Response.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
        }
        return ResponseText;
    }

Add your querystring parameters (if required) as a NameValueCollection like so.

        NameValueCollection QueryStringParameters = new NameValueCollection();
        QueryStringParameters.Add("id", "123");
        QueryStringParameters.Add("category", "A");

Add your http headers (if required) as a NameValueCollection like so.

        NameValueCollection RequestHttpHeaders = new NameValueCollection();
        RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

Getting only Month and Year from SQL DATE

My database doesn't support most of the functions above however I found that this works:

SELECT * FROM table WHERE SUBSTR(datetime_column, starting_position, number_of_strings)=required_year_and_month;

for example: SELECT SUBSTR(created, 1,7) FROM table;

returns the year and month in the format "yyyy-mm"

Access restriction on class due to restriction on required library rt.jar?

I met the same problem. I found the answer in the website:http://www.17ext.com.
First,delete the JRE System Libraries. Then,import JRE System Libraries again.

I don't know why.However it fixed my problem,hope it can help you.

How to wrap text of HTML button with fixed width?

If we have some inner divisions inside <button> tag like this-

<button class="top-container">
    <div class="classA">
       <div class="classB">
           puts " some text to get print." 
       </div>
     </div>
     <div class="class1">
       <div class="class2">
           puts " some text to get print." 
       </div>
     </div>
</button>

Sometime Text of class A get overlap on class1 data because these both are in a single button tag. I try to break the tex using-

 word-wrap: break-word;         /* All browsers since IE 5.5+ */
 overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */ 

But this won't worked then I try this-

white-space: normal;

after removing above css properties and got my task done.

Hope will work for all !!!

login to remote using "mstsc /admin" with password

Same problem but @Angelo answer didn't work for me, because I'm using same server with different credentials. I used the approach below and tested it on Windows 10.

cmdkey /add:server01 /user:<username> /pass:<password>

Then used mstsc /v:server01 to connect to the server.

The point is to use names instead of ip addresses to avoid conflict between credentials. If you don't have a DNS server locally accessible try c:\windows\system32\drivers\etc\hosts file.

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This usually happens if you have entered the wrong details when you created the App in Facebook. Or have you changed a URL's of an existing App?

Can you please recheck the settings of your APP in this page?

https://developers.facebook.com/apps

  1. Select the correct App and click in the edit button;

  2. Check the URLs & paths are correctly entered and are pointing to the site where you have installed Ultimate Facebook plugin.

How to create a numpy array of all True or all False?

>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

Plot a bar using matplotlib using a dictionary

The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label) where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label does the same work as xticks(). One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label). For detailed information please refer the documentation.

import matplotlib.pyplot as plt

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())

#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()

enter image description here

Additionally the same plot can be generated without using range(). But the problem encountered was that tick_label just worked for the last plt.bar() call. Hence xticks() was used for labelling:

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()

enter image description here

Why am I getting error for apple-touch-icon-precomposed.png

An alternative solution is to simply add a route to your routes.rb

It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.

# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/

then add a method 'apple_touch_not_found' to your application_controller.rb

# application_controller.rb
def apple_touch_not_found
  render  plain: 'apple-touch icons not found', status: 404
end

Git Push error: refusing to update checked out branch

It's works for me

  1. git config --global receive.denyCurrentBranch updateInstead

  2. git push origin master

How to use a wildcard in the classpath to add multiple jars?

Basename wild cards were introduced in Java 6; i.e. "foo/*" means all ".jar" files in the "foo" directory.

In earlier versions of Java that do not support wildcard classpaths, I have resorted to using a shell wrapper script to assemble a Classpath by 'globbing' a pattern and mangling the results to insert ':' characters at the appropriate points. This would be hard to do in a BAT file ...

If Else If In a Sql Server Function

I think you'd be better off with a CASE statement, which works a lot more like IF/ELSEIF

DECLARE @this int, @value varchar(10)
SET @this = 200
SET @value = (
SELECT 
CASE
    WHEN @this between 5 and 10 THEN 'foo'
    WHEN @this between 10 and 15 THEN 'bar'
    WHEN @this < 0 THEN 'barfoo'
    ELSE 'foofoo'
    END
)

More info: http://technet.microsoft.com/en-us/library/ms181765.aspx

Remove last character of a StringBuilder?

stringBuilder.Remove(stringBuilder.Length - 1, 1);

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

gnuplot plotting multiple line graphs

Whatever your separator is in your ls.dat, you can specify it to gnuplot:

set datafile separator "\t"

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

How to count the number of lines of a string in javascript

Another short, potentially more performant than split, solution is:

const lines = (str.match(/\n/g) || '').length + 1

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

Removing some unnecessary SQL and then COUNT(*) will be faster than SQL_CALC_FOUND_ROWS. Example:

SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name

Then count without unnecessary part:

SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'

Are there any style options for the HTML5 Date picker?

FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color, fill, etc.

I did eventually figure out that some filter properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:

_x000D_
_x000D_
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
  background: transparent;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
 <input type="date" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

Hopefully this helps some people as for the most part chrome even directly says this is impossible.

Simulating a click in jQuery/JavaScript on a link

All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

Package php5 have no installation candidate (Ubuntu 16.04)

sudo apt-get install php7.0-mysql

for php7.0 works well for me

How to shift a block of code left/right by one space in VSCode?

Recent versions of VSCode (e.g., Version 1.29 at the time of posting this answer) allow you to change the Tab/Space size to 1 (or any number between 1 and 8). You may change the Tab/Space size from the bottom-right corner as shown in the below image:

Change Tab/Space size

Click on Spaces:4. Then, select Indent Using Spaces or Indent Using Tabs and choose the size 1.

Hope it helps.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

How to find the serial port number on Mac OS X?

While entering the serial port name into the code in arduino IDE, enter the whole port address i.e:

/dev/cu.usbmodem*

or

/dev/cu.UG-*

where the * is the port number.

And for the port number in case of mac just open terminal and type

ls /dev/*

and then search for the port that u have set in arduino IDE.

How to get the bluetooth devices as a list?

Find list of Nearby Bluetooth Devices:

Find Screenshot for the same.

enter image description here

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.startDiscovery();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bluetoothdemo.MainActivity" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"/>

</RelativeLayout>

Manifest file:

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

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

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note:

Please make sure that you ask Location permission to your user and turn GPS On.

Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.

More reference:

  1. https://developer.android.com/guide/topics/connectivity/bluetooth
  2. https://getlief.zendesk.com/hc/en-us/articles/360007600233-Why-does-Android-require-Location-Permissions-for-Bluetooth-

Done

How to customise file type to syntax associations in Sublime Text?

I put my customized changes in the User package:

*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage

Which also means it's in JSON format:

{
  "extensions":
  [
    "sbt"
  ]
}

This is the same place the

View -> Syntax -> Open all with current extension as ...

menu item adds it (creating the file if it doesn't exist).

Changing the row height of a datagridview

You also need to change the resizable property to true

    dataGridView1.RowTemplate.Resizable = DataGridViewTriState.True;
    dataGridView1.RowTemplate.Height = 50;

HTML5 Video not working in IE 11

I've been having similar issues of a video not playing in IE11 on Windows 8.1. What I didn't realize was that I was running an N version of Windows, meaning no media features were installed. After installing the Media Feature Pack for N and KN versions of Windows 8.1 and rebooting my PC it was working fine.

As a side-note, the video worked fine in Chrome, Firefox, etc, since those browsers properly fell back to the webm file.

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

Right pad a string with variable number of spaces

The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.

SELECT CAST('Test' AS CHAR(20))

This returns the value 'Test '.

error: request for member '..' in '..' which is of non-class type

Foo foo2();

change to

Foo foo2;

You get the error because compiler thinks of

Foo foo2()

as of function declaration with name 'foo2' and the return type 'Foo'.

But in that case If we change to Foo foo2 , the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous".

Determine which element the mouse pointer is on top of in JavaScript

elementFromPoint() gets only the first element in DOM tree. This is mostly not enough for developers needs. To get more than one element at e.g. the current mouse pointer position, this is the function you need:

document.elementsFromPoint(x, y) . // Mind the 's' in elements

This returns an array of all element objects under the given point. Just pass the mouse X and Y values to this function.

More information is here: DocumentOrShadowRoot.elementsFromPoint()

For very old browsers which are not supported, you may use this answer as a fallback.

How to fast get Hardware-ID in C#?

The following approach was inspired by this answer to a related (more general) question.

The approach is to read the MachineGuid value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography. This value is generated during OS installation.

There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid value.

However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.

public string GetMachineGuid()
{
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
   {
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
       {
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();
       }
   }
}

How to create named and latest tag in Docker?

Just grep the ID from docker images:

docker build -t creack/node:latest .
ID="$(docker images | grep 'creak/node' | head -n 1 | awk '{print $3}')"
docker tag "$ID" creack/node:0.10.24
docker tag "$ID" creack/node:latest

Needs no temporary file and gives full build output. You still can redirect it to /dev/null or a log file.

How many socket connections possible?

I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.

Edit:

I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251

The cost of a connection(with epoll):

  • application need some RAM per connection
  • TCP buffer 2 * 4k ~ 10k, or more
  • epoll need some memory for a file descriptor, from epoll(7)

Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.

What is the difference between 'protected' and 'protected internal'?

public - The members (Functions & Variables) declared as public can be accessed from anywhere.

private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be considered as private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber.

protected - Protected members can be accessed only from the child classes.

internal - It can be accessed only within the same assembly.

protected internal - It can be accessed within the same assembly as well as in derived class.

pandas: filter rows of DataFrame with operator chaining

If you set your columns to search as indexes, then you can use DataFrame.xs() to take a cross section. This is not as versatile as the query answers, but it might be useful in some situations.

import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(3, size=(10, 5)),
    columns=list('ABCDE')
)

df
# Out[55]: 
#    A  B  C  D  E
# 0  0  2  2  2  2
# 1  1  1  2  0  2
# 2  0  2  0  0  2
# 3  0  2  2  0  1
# 4  0  1  1  2  0
# 5  0  0  0  1  2
# 6  1  0  1  1  1
# 7  0  0  2  0  2
# 8  2  2  2  2  2
# 9  1  2  0  2  1

df.set_index(['A', 'D']).xs([0, 2]).reset_index()
# Out[57]: 
#    A  D  B  C  E
# 0  0  2  2  2  2
# 1  0  2  1  1  0

How to convert a set to a list in python?

Simply type:

list(my_set)

This will turn a set in the form {'1','2'} into a list in the form ['1','2'].

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

After installing Postgresql I did the below steps.

  1. open the file pg_hba.conf for Ubuntu it will be in /etc/postgresql/9.x/main and change this line:

    local   all             postgres                                peer

    to

    local   all             postgres                                trust
  2. Restart the server

    $ sudo service postgresql restart
    
  3. Login into psql and set your password

    $ psql -U postgres
    db> ALTER USER postgres with password 'your-pass';
    
  4. Finally change the pg_hba.conf from

    local   all             postgres                                trust

    to

    local   all             postgres                                md5

After restarting the postgresql server, you can access it with your own password

Authentication methods details:

trust - anyone who can connect to the server is authorized to access the database

peer - use client's operating system user name as database user name to access it.

md5 - password-base authentication

for further reference check here

In Linux, how to tell how much memory processes are using?

Getting right memory usage is trickier than one may think. The best way I could find is:

echo 0 $(awk '/TYPE/ {print "+", $2}' /proc/`pidof PROCESS`/smaps) | bc

Where "PROCESS" is the name of the process you want to inspect and "TYPE" is one of:

  • Rss: resident memory usage, all memory the process uses, including all memory this process shares with other processes. It does not include swap;
  • Shared: memory that this process shares with other processes;
  • Private: private memory used by this process, you can look for memory leaks here;
  • Swap: swap memory used by the process;
  • Pss: Proportional Set Size, a good overall memory indicator. It is the Rss adjusted for sharing: if a process has 1MiB private and 20MiB shared between other 10 processes, Pss is 1 + 20/10 = 3MiB

Other valid values are Size (i.e. virtual size, which is almost meaningless) and Referenced (the amount of memory currently marked as referenced or accessed).

You can use watch or some other bash-script-fu to keep an eye on those values for processes that you want to monitor.

For more informations about smaps: http://www.kernel.org/doc/Documentation/filesystems/proc.txt.

Most efficient way to map function over numpy array

squares = squarer(x)

Arithmetic operations on arrays are automatically applied elementwise, with efficient C-level loops that avoid all the interpreter overhead that would apply to a Python-level loop or comprehension.

Most of the functions you'd want to apply to a NumPy array elementwise will just work, though some may need changes. For example, if doesn't work elementwise. You'd want to convert those to use constructs like numpy.where:

def using_if(x):
    if x < 5:
        return x
    else:
        return x**2

becomes

def using_where(x):
    return numpy.where(x < 5, x, x**2)

What is the difference between a string and a byte string?

The only thing that a computer can store is bytes.

To store anything in a computer, you must first encode it, i.e. convert it to bytes. For example:

  • If you want to store music, you must first encode it using MP3, WAV, etc.
  • If you want to store a picture, you must first encode it using PNG, JPEG, etc.
  • If you want to store text, you must first encode it using ASCII, UTF-8, etc.

MP3, WAV, PNG, JPEG, ASCII and UTF-8 are examples of encodings. An encoding is a format to represent audio, images, text, etc in bytes.

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer.

On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable. A character string can't be directly stored in a computer, it has to be encoded first (converted into a byte string). There are multiple encodings through which a character string can be converted into a byte string, such as ASCII and UTF-8.

'I am a string'.encode('ASCII')

The above Python code will encode the string 'I am a string' using the encoding ASCII. The result of the above code will be a byte string. If you print it, Python will represent it as b'I am a string'. Remember, however, that byte strings aren't human-readable, it's just that Python decodes them from ASCII when you print them. In Python, a byte string is represented by a b, followed by the byte string's ASCII representation.

A byte string can be decoded back into a character string, if you know the encoding that was used to encode it.

b'I am a string'.decode('ASCII')

The above code will return the original string 'I am a string'.

Encoding and decoding are inverse operations. Everything must be encoded before it can be written to disk, and it must be decoded before it can be read by a human.

"Are you missing an assembly reference?" compile error - Visual Studio

Are you strong-naming your assemblies? In that case it is not a good idea to auto-increment your build number because with every new build number you will also have to update all your references.

Pytorch reshape tensor dimension

There are multiple ways of reshaping a PyTorch tensor. You can apply these methods on a tensor of any dimensionality.

Let's start with a 2-dimensional 2 x 3 tensor:

x = torch.Tensor(2, 3)
print(x.shape)
# torch.Size([2, 3])

To add some robustness to this problem, let's reshape the 2 x 3 tensor by adding a new dimension at the front and another dimension in the middle, producing a 1 x 2 x 1 x 3 tensor.

Approach 1: add dimension with None

Use NumPy-style insertion of None (aka np.newaxis) to add dimensions anywhere you want. See here.

print(x.shape)
# torch.Size([2, 3])

y = x[None, :, None, :] # Add new dimensions at positions 0 and 2.
print(y.shape)
# torch.Size([1, 2, 1, 3])

Approach 2: unsqueeze

Use torch.Tensor.unsqueeze(i) (a.k.a. torch.unsqueeze(tensor, i) or the in-place version unsqueeze_()) to add a new dimension at the i'th dimension. The returned tensor shares the same data as the original tensor. In this example, we can use unqueeze() twice to add the two new dimensions.

print(x.shape)
# torch.Size([2, 3])

# Use unsqueeze twice.
y = x.unsqueeze(0) # Add new dimension at position 0
print(y.shape)
# torch.Size([1, 2, 3])

y = y.unsqueeze(2) # Add new dimension at position 2
print(y.shape)
# torch.Size([1, 2, 1, 3])

In practice with PyTorch, adding an extra dimension for the batch may be important, so you may often see unsqueeze(0).

Approach 3: view

Use torch.Tensor.view(*shape) to specify all the dimensions. The returned tensor shares the same data as the original tensor.

print(x.shape)
# torch.Size([2, 3])

y = x.view(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])

Approach 4: reshape

Use torch.Tensor.reshape(*shape) (aka torch.reshape(tensor, shapetuple)) to specify all the dimensions. If the original data is contiguous and has the same stride, the returned tensor will be a view of input (sharing the same data), otherwise it will be a copy. This function is similar to the NumPy reshape() function in that it lets you define all the dimensions and can return either a view or a copy.

print(x.shape)
# torch.Size([2, 3])

y = x.reshape(1, 2, 1, 3)
print(y.shape)
# torch.Size([1, 2, 1, 3])

Furthermore, from the O'Reilly 2019 book Programming PyTorch for Deep Learning, the author writes:

Now you might wonder what the difference is between view() and reshape(). The answer is that view() operates as a view on the original tensor, so if the underlying data is changed, the view will change too (and vice versa). However, view() can throw errors if the required view is not contiguous; that is, it doesn’t share the same block of memory it would occupy if a new tensor of the required shape was created from scratch. If this happens, you have to call tensor.contiguous() before you can use view(). However, reshape() does all that behind the scenes, so in general, I recommend using reshape() rather than view().

Approach 5: resize_

Use the in-place function torch.Tensor.resize_(*sizes) to modify the original tensor. The documentation states:

WARNING. This is a low-level method. The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged). For most purposes, you will instead want to use view(), which checks for contiguity, or reshape(), which copies data if needed. To change the size in-place with custom strides, see set_().

print(x.shape)
# torch.Size([2, 3])

x.resize_(1, 2, 1, 3)
print(x.shape)
# torch.Size([1, 2, 1, 3])

My observations

If you want to add just one dimension (e.g. to add a 0th dimension for the batch), then use unsqueeze(0). If you want to totally change the dimensionality, use reshape().

See also:

What's the difference between reshape and view in pytorch?

What is the difference between view() and unsqueeze()?

In PyTorch 0.4, is it recommended to use reshape than view when it is possible?

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Trigger a Travis-CI rebuild without pushing a commit?

I have found another way of forcing re-run CI builds and other triggers:

  1. Run git commit --amend --no-edit without any changes. This will recreate the last commit in the current branch.
  2. git push --force-with-lease origin pr-branch.

Java: Calculating the angle between two points in degrees

Why is everyone complicating this?

The only problem is Math.atan2( x , y)

The corret answer is Math.atan2( y, x)

All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.

All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

passing object by reference in C++

Passing by reference in the above case is just an alias for the actual object.

You'll be referring to the actual object just with a different name.

There are many advantages which references offer compared to pointer references.

Matching a space in regex

If you're looking for a space, that would be " " (one space).

If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).

If you're looking for common spacing, use "[ X]" or "[ X][ X]*" or "[ X]+" where X is the physical tab character (and each is preceded by a single space in all those examples).

These will work in every* regex engine I've ever seen (some of which don't even have the one-or-more "+" character, ugh).

If you know you'll be using one of the more modern regex engines, "\s" and its variations are the way to go. In addition, I believe word boundaries match start and end of lines as well, important when you're looking for words that may appear without preceding or following spaces.

For PHP specifically, this page may help.

From your edit, it appears you want to remove all non valid characters The start of this is (note the space inside the regex):

$newtag = preg_replace ("/[^a-zA-Z0-9 ]/", "", $tag);
#                                    ^ space here

If you also want trickery to ensure there's only one space between each word and none at the start or end, that's a little more complicated (and probably another question) but the basic idea would be:

$newtag = preg_replace ("/ +/", " ", $tag); # convert all multispaces to space
$newtag = preg_replace ("/^ /", "", $tag);  # remove space from start
$newtag = preg_replace ("/ $/", "", $tag);  # and end

C program to check little vs. big endian

Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:


The following program would determine that:

#include <stdio.h>
#include <stdint.h>

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } e = { 0x01000000 };

    return e.c[0];
}

int main(void)
{
    printf("System is %s-endian.\n",
        is_big_endian() ? "big" : "little");

    return 0;
}

You also have this approach; from Quake II:

byte    swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
    bigendien = false;

And !is_big_endian() is not 100% to be little as it can be mixed/middle.

Believe this can be checked using same approach only change value from 0x01000000 to i.e. 0x01020304 giving:

switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE

But not entirely sure about that one ...

anaconda - path environment variable in windows

C:\Users\\Anaconda3

I just added above path , to my path environment variables and it worked. Now, all we have to do is to move to the .py script location directory, open the cmd with that location and run to see the output.

How to generate the whole database script in MySQL Workbench?

In MySQL Workbench 6, commands have been repositioned as the "Server Administration" tab is gone.

You now find the option "Data Export" under the "Management" section when you open a standard server connection.

C++ Pass A String

Well, std::string is a class, const char * is a pointer. Those are two different things. It's easy to get from string to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string.

My recommendation: Functions that take constant strings and don't modify them should always take const char * as an argument. That way, they will always work - with string literals as well as with std::string (via an implicit c_str()).

ASP.NET MVC JsonResult Date Format

0

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

How to re-enable right click so that I can inspect HTML elements in Chrome?

If the page you are on has a text or textarea input, click into this input (as if you want to enter text) then right-click and select 'Inspect element'.

Regex empty string or email

This regex pattern will match an empty string:

^$

And this will match (crudely) an email or an empty string:

(^$|^.*@.*\..*$)

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

aapt dump badging test.apk | grep "VersionName" | sed -e "s/.*versionName='//" -e "s/' .*//"

This answers the question by returning only the version number as a result. However......

The goal as previously stated should be to find out if the apk on the server is newer than the one installed BEFORE attempting to download or install it. The easiest way to do this is include the version number in the filename of the apk hosted on the server eg myapp_1.01.apk

You will need to establish the name and version number of the apps already installed (if it is installed) in order to make the comparison. You will need a rooted device or a means of installing the aapt binary and busybox if they are not already included in the rom.

This script will get the list of apps from your server and compare with any installed apps. The result is a list flagged for upgrade/installation.

#/system/bin/sh
SERVER_LIST=$(wget -qO- "http://demo.server.com/apk/" | grep 'href' | grep '\.apk' | sed 's/.*href="//' | \
              sed 's/".*//' | grep -v '\/' | sed -E "s/%/\\\\x/g" | sed -e "s/x20/ /g" -e "s/\\\\//g")
LOCAL_LIST=$(for APP in $(pm list packages -f | sed -e 's/package://' -e 's/=.*//' | sort -u); do \
              INFO=$(echo -n $(aapt dump badging $APP | grep -e 'package: name=' -e 'application: label=')) 2>/dev/null; \
              PACKAGE=$(echo $INFO | sed "s/.*package: name='//" | sed "s/'.*$//"); \
              LABEL=$(echo $INFO | sed "s/.*application: label='//" | sed "s/'.*$//"); if [ -z "$LABEL" ]; then LABEL="$PACKAGE"; fi; \
              VERSION=$(echo $INFO | sed -e "s/.*versionName='//" -e "s/' .*//"); \
              NAME=$LABEL"_"$VERSION".apk"; echo "$NAME"; \
              done;)
OFS=$IFS; IFS=$'\t\n'
for REMOTE in $SERVER_LIST; do
    INSTALLED=0
    REMOTE_NAME=$(echo $REMOTE | sed 's/_.*//'); REMOTE_VER=$(echo $REMOTE | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
    for LOCAL in $LOCAL_LIST; do
        LOCAL_NAME=$(echo $LOCAL | sed 's/_.*//'); LOCAL_VER=$(echo $LOCAL | sed 's/^[^_]*_//g' | sed 's/[^0-9]*//g')
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ]; then INSTALLED=1; fi
        if [ "$REMOTE_NAME" == "$LOCAL_NAME" ] && [ ! "$REMOTE_VER" == "$LOCAL_VER" ]; then echo remote=$REMOTE ver=$REMOTE_VER local=$LOCAL ver=$LOCAL_VER; fi
    done
    if [ "$INSTALLED" == "0" ]; then echo "$REMOTE"; fi
done
IFS=$OFS

As somebody asked how to do it without using aapt. It is also possible to extract apk info with apktool and a bit of scripting. This way is slower and not simple in android but will work on windows/mac or linux as long as you have working apktool setup.

#!/bin/sh
APK=/path/to/your.apk
TMPDIR=/tmp/apktool
rm -f -R $TMPDIR
apktool d -q -f -s --force-manifest -o $TMPDIR $APK
APK=$(basename $APK)
VERSION=$(cat $TMPDIR/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
LABEL=$(cat $TMPDIR/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
rm -f -R $TMPDIR
echo ${LABEL}_$(echo $V).apk

Also consider a drop folder on your server. Upload apks to it and a cron task renames and moves them to your update folder.

#!/bin/sh
# Drop Folder script for renaming APKs
# Read apk file from SRC folder and move it to TGT folder while changing filename to APKLABEL_APKVERSION.apk
# If an existing version of the APK exists in the target folder then script will remove it
# Define METHOD as "aapt" or "apktool" depending upon what is available on server 

# Variables
METHOD="aapt"
SRC="/home/user/public_html/dropfolders/apk"
TGT="/home/user/public_html/apk"
if [ -d "$SRC" ];then mkdir -p $SRC
if [ -d "$TGT" ]then mkdir -p $TGT

# Functions
get_apk_filename () {
    if [ "$1" = "" ]; then return 1; fi
    local A="$1"
    case $METHOD in
        "apktool")
            local D=/tmp/apktool
            rm -f -R $D
            apktool d -q -f -s --force-manifest -o $D $A
            local A=$(basename $A)
            local V=$(cat $D/apktool.yml | grep "versionName" | sed -e "s/versionName: //")
            local T=$(cat $D/res/values/strings.xml | grep 'string name="title"' | sed -e 's/.*">//' -e 's/<.*//')
            rm -f -R $D<commands>
            ;;
        "aapt")
            local A=$(aapt dump badging $A | grep -e "application-label:" -e "VersionName")
            local V=$(echo $A | sed -e "s/.*versionName='//" -e "s/' .*//")
            local T=$(echo $A | sed -e "s/.*application-label:'//" -e "s/'.*//")
            ;;
        esac
    echo ${T}_$(echo $V).apk
}

# Begin script
for APK in $(ls "$SRC"/*.apk); do
    APKNAME=$(get_apk_filename "$APK")
    rm -f $TGT/$(echo APKNAME | sed "s/_.*//")_*.apk
    mv "$APK" "$TGT"/$APKNAME
done

Git keeps asking me for my ssh key passphrase

I had a similar issue, but the other answers didn't fix my problem. I thought I'd go ahead and post this just in case someone else has a screwy setup like me.

It turns out I had multiple keys and Git was using the wrong one first. It would prompt me for my passphrase, and I would enter it, then Git would use a different key that would work (that I didn't need to enter the passphrase on).

I just deleted the key that it was using to prompt me for a passphrase and now it works!

OSError: [WinError 193] %1 is not a valid Win32 application

For anyone experiencing this on windows after an update

What happened was that Windows Defender made some changes. Possibly cause running data extraction scripts, but python.exe got reduced to 0kb for that project. Copying the python.exe from another project and replacing it solved for now.

How to write a basic swap function in Java

Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

Output:

New values of x and y are 10, 5

Cannot bulk load because the file could not be opened. Operating System Error Code 3

To keep this simple, I just changed the directory from which I was importing the data to a local folder on the server.

I had the file located on a shared folder, I just copied my files to "c:\TEMP\Reports" on my server (updated the query to BULK INSERT from the new folder). The Agent task completed successfully :)

Finally after a long time I'm able to BULK Insert automatically via agent job.

Best regards.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

Pass data from Activity to Service using an Intent

This is a much better and secured way. Working like a charm!

   private void startFloatingWidgetService() {
        startService(new Intent(MainActivity.this,FloatingWidgetService.class)
                .setAction(FloatingWidgetService.ACTION_PLAY));
    }

instead of :

 private void startFloatingWidgetService() {
        startService(new Intent(FloatingWidgetService.ACTION_PLAY));
    }

Because when you try 2nd one then you get an error saying : java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.floatingwidgetchathead_demo.SampleService.ACTION_START }

Then your Service be like this :

static final String ACTION_START = "com.floatingwidgetchathead_demo.SampleService.ACTION_START";
    static final String ACTION_PLAY = "com.floatingwidgetchathead_demo.SampleService.ACTION_PLAY";
    static final String ACTION_PAUSE = "com.floatingwidgetchathead_demo.SampleService.ACTION_PAUSE";
    static final String ACTION_DESTROY = "com.yourcompany.yourapp.SampleService.ACTION_DESTROY";

 @SuppressLint("LogConditional")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String action = intent.getAction();
    //System.out.println("ACTION: "+action);
    switch (action){
        case ACTION_START:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_PLAY:
            Log.d(TAG, "onStartCommand: "+action);
           addRemoveView();
           addFloatingWidgetView();
            break;
        case ACTION_PAUSE:
            Log.d(TAG, "onStartCommand: "+action);
            break;
        case ACTION_DESTROY:
            Log.d(TAG, "onStartCommand: "+action);
            break;
    }
    return START_STICKY;

}

Angular.js directive dynamic templateURL

Thanks to @pgregory, I could resolve my problem using this directive for inline editing

.directive("superEdit", function($compile){
    return{
        link: function(scope, element, attrs){
            var colName = attrs["superEdit"];
            alert(colName);

            scope.getContentUrl = function() {
                if (colName == 'Something') {
                    return 'app/correction/templates/lov-edit.html';
                }else {
                    return 'app/correction/templates/simple-edit.html';
                }
            }

            var template = '<div ng-include="getContentUrl()"></div>';

            var linkFn = $compile(template);
            var content = linkFn(scope);
            element.append(content);
        }
    }
})

Python Dictionary Comprehension

I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

giving

d = {'a': 1, 'b': 2, 'c': 3}

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

1) first remove cordova cmd

npm uninstall -g cordova

2) After that remove ionic

npm uninstall -g ionic

PHP function to get the subdomain of a URL

What I found the best and short solution is

array_shift(explode(".",$_SERVER['HTTP_HOST']));

How to combine two or more querysets in a Django view?

Requirements: Django==2.0.2, django-querysetsequence==0.8

In case you want to combine querysets and still come out with a QuerySet, you might want to check out django-queryset-sequence.

But one note about it. It only takes two querysets as it's argument. But with python reduce you can always apply it to multiple querysets.

from functools import reduce
from queryset_sequence import QuerySetSequence

combined_queryset = reduce(QuerySetSequence, list_of_queryset)

And that's it. Below is a situation I ran into and how I employed list comprehension, reduce and django-queryset-sequence

from functools import reduce
from django.shortcuts import render    
from queryset_sequence import QuerySetSequence

class People(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mentor = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='my_mentees')

class Book(models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(Student, on_delete=models.CASCADE)

# as a mentor, I want to see all the books owned by all my mentees in one view.
def mentee_books(request):
    template = "my_mentee_books.html"
    mentor = People.objects.get(user=request.user)
    my_mentees = mentor.my_mentees.all() # returns QuerySet of all my mentees
    mentee_books = reduce(QuerySetSequence, [each.book_set.all() for each in my_mentees])

    return render(request, template, {'mentee_books' : mentee_books})

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

Soft hyphen in HTML (<wbr> vs. &shy;)

<wbr> and &shy;

Today you can use both.

<wbr> use to break and do not put more information.

Example, use to show links:

 https://stackoverflow.com/questions/226464/soft-hyphen-in-html-wbr-vs-shy

&shy; when necessary, at this point the text will break and add a hyphen.

Example:

"É im&shy;pos&shy;sí&shy;vel pa&shy;ra um ho&shy;mem a&shy;pren&shy;der a&shy;qui&shy;lo que ele acha que já sa&shy;be."

_x000D_
_x000D_
div{_x000D_
  max-width: 130px;_x000D_
  border-width: 2px;_x000D_
  border-style: dashed;_x000D_
  border-color: #f00;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<div>https://<wbr>stackoverflow.com<wbr>/questions/226464<wbr>/soft-hyphen-in-<wbr>html-wbr-vs-shy</div>_x000D_
_x000D_
<div>É im&shy;pos&shy;sí&shy;vel pa&shy;ra um ho&shy;mem a&shy;pren&shy;der a&shy;qui&shy;lo que ele acha que já sa&shy;be.</div>
_x000D_
_x000D_
_x000D_

CSS On hover show another element

You can use axe selectors for this.

There are two approaches:

1. Immediate Parent axe Selector (<)

#a:hover < #content + #b

This axe style rule will select #b, which is the immediate sibling of #content, which is the immediate parent of #a which has a :hover state.

_x000D_
_x000D_
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}

#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}

#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}

#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}

#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}

#a:hover < #content + #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>

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

<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
_x000D_
_x000D_


2. Remote Element axe Selector (\)

#a:hover \ #b

This axe style rule will select #b, which is present in the same document as #a which has a :hover state.

_x000D_
_x000D_
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}

#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}

#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}

#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}

#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}

#a:hover \ #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>

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

<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
_x000D_
_x000D_

Convert HTML + CSS to PDF

Fine rendering doesn't mean anything. Does it validate?

All browsers do the most they can to just show something on the screen, no matter how bad the input. And of course they do not do the same thing. If you want the same rendering as FireFox, you could use its rendering engine. There are pdf generators for it. It is an awful lot of work, though.

Why do multiple-table joins produce duplicate rows?

Ok in this example you are getting duplicates because you are joining both D and S onto M. I assume you should be joining D.id onto S.id like below:

SELECT *
FROM M
INNER JOIN S
    on M.Id = S.Id
INNER JOIN D
    ON S.Id = D.Id
INNER JOIN H
    ON D.Id = H.Id

Searching a string in eclipse workspace

For Mac:

Quick Text Search: Shift + Cmd + L

enter image description here

All other search (like File Search, Git Search, Java Search etc): Ctrl + H

enter image description here

How do I find the length/number of items present for an array?

Do you mean how long is the array itself, or how many customerids are in it?

Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).

But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"

C can't tell you this. You will need to keep a separate variable, int numCustIds (for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.

Get class labels from Keras functional model

UPDATE: This is no longer valid for newer Keras versions. Please use argmax() as in the answer from Emilia Apostolova.

The functional API models have just the predict() function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes() utility function. Example:

y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)

This is equivalent to model.predict_classes(x) on the Sequential model.

The reason for this is that the functional API support more general class of tasks where predict_classes() would not make sense.

More info: https://github.com/fchollet/keras/issues/2524

400 BAD request HTTP error code meaning?

As a complementary, for those who might meet the same issue as mine, I'm using $.ajax to post form data to server and I also got the 400 error at first.

Assume I have a javascript variable,

var formData = {
    "name":"Gearon",
    "hobby":"Be different"
    }; 

Do not use variable formData directly as the value of key data like below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: formData,
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Instead, use JSON.stringify to encapsulate the formData as below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: JSON.stringify(formData),
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I'm just raising a instance at practice. Hope it would be helpful to someone.

Get button click inside UITableViewCell

This should help :-

UITableViewCell* cell = (UITableViewCell*)[sender superview];
NSIndexPath* indexPath = [myTableView indexPathForCell:cell];

Here sender is the UIButton instance that is sending the event. myTableView is the UITableView instance you're dealing with.

Just get the cell reference right and all the work is done.

You may need to remove the buttons from cell's contentView & add them directly to UITableViewCell instance as it's subview.

Or

You can formulate a tag naming scheme for different UIButtons in cell.contentView. Using this tag, later you can know the row & section information as needed.

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had the same problem:

curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json

* About to connect() to localhost port 8081 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
> 
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
< 
* Connection #0 to host localhost left intact
* Closing connection #0

I resolved it by adding the dependency to pom.xml as follows. Please try it.

    <dependency>
        <groupId>com.owlike</groupId>
        <artifactId>genson</artifactId>
        <version>0.98</version>
    </dependency>

How to put an image next to each other

Instead of using position:relative in #icons, you could just take that away and maybe add a z-index or something so the picture won't get covered up. Hope this helps.

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Adding dictionaries together, Python

Here are quite a few ways to add dictionaries.

You can use Python3's dictionary unpacking feature.

ndic = {**dic0, **dic1}

Or create a new dict by adding both items.

ndic = dict(dic0.items() + dic1.items())

If your ok to modify dic0

dic0.update(dic1)

If your NOT ok to modify dic0

ndic = dic0.copy()
ndic.update(dic1)

If all the keys in one dict are ensured to be strings (dic1 in this case, of course args can be swapped)

ndic = dict(dic0, **dic1)

In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.

ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}

Java JDBC - How to connect to Oracle using Service Name instead of SID

This should be working: jdbc:oracle:thin//hostname:Port/ServiceName=SERVICE_NAME

What is a plain English explanation of "Big O" notation?

Definition :- Big O notation is a notation which says how a algorithm performance will perform if the data input increases.

When we talk about algorithms there are 3 important pillars Input , Output and Processing of algorithm. Big O is symbolic notation which says if the data input is increased in what rate will the performance vary of the algorithm processing.

I would encourage you to see this youtube video which explains Big O Notation in depth with code examples.

Algorithm basic pillars

So for example assume that a algorithm takes 5 records and the time required for processing the same is 27 seconds. Now if we increase the records to 10 the algorithm takes 105 seconds.

In simple words the time taken is square of the number of records. We can denote this by O(n ^ 2). This symbolic representation is termed as Big O notation.

Now please note the units can be anything in inputs it can be bytes , bits number of records , the performance can be measured in any unit like second , minutes , days and so on. So its not the exact unit but rather the relationship.

Big O symbols

For example look at the below function "Function1" which takes a collection and does processing on the first record. Now for this function the performance will be same irrespective you put 1000 , 10000 or 100000 records. So we can denote it by O(1).

void Function1(List<string> data)
{
string str = data[0];
}

Now see the below function "Function2()". In this case the processing time will increase with number of records. We can denote this algorithm performance using O(n).

void Function2(List<string> data)
        {
            foreach(string str in data)
            {
                if (str == "shiv")
                {
                    return;
                }
            }
        }

When we see a Big O notation for any algorithm we can classify them in to three categories of performance :-

  1. Log and constant category :- Any developer would love to see their algorithm performance in this category.
  2. Linear :- Developer will not want to see algorithms in this category , until its the last option or the only option left.
  3. Exponential :- This is where we do not want to see our algorithms and a rework is needed.

So by looking at Big O notation we categorize good and bad zones for algorithms.

Bog O classification

I would recommend you to watch this 10 minutes video which discusses Big O with sample code

https://www.youtube.com/watch?v=k6kxtzICG_g

Git pull - Please move or remove them before you can merge

I just faced the same issue and solved it using the following.First clear tracked files by using :

git clean -d -f

then try git pull origin master

You can view other git clean options by typing git clean -help

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Then NumPy sum function takes an optional axis argument that specifies along which axis you would like the sum performed:

>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])

Or, equivalently:

>>> numpy.sum(a, 0)
array([18, 22, 26])

How can I create my own comparator for a map?

Since C++11, you can also use a lambda expression instead of defining a comparator struct:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;

Output:

1
two
three
fouuur

I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

Code on Ideone

Decoding a Base64 string in Java

The following should work with the latest version of Apache common codec

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

How to convert a structure to a byte array in C#?

This is fairly easy, using marshalling.

Top of file

using System.Runtime.InteropServices

Function

byte[] getBytes(CIFSPacket str) {
    int size = Marshal.SizeOf(str);
    byte[] arr = new byte[size];

    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(str, ptr, true);
    Marshal.Copy(ptr, arr, 0, size);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

And to convert it back:

CIFSPacket fromBytes(byte[] arr) {
    CIFSPacket str = new CIFSPacket();

    int size = Marshal.SizeOf(str);
    IntPtr ptr = Marshal.AllocHGlobal(size);

    Marshal.Copy(arr, 0, ptr, size);

    str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
    Marshal.FreeHGlobal(ptr);

    return str;
}

In your structure, you will need to put this before a string

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;

And make sure SizeConst is as big as your biggest possible string.

And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In my case there was no DEFINER or root@localhost mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database->Import->Execute SQL Script menu. That was giving error.

Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.

Google Maps API OVER QUERY LIMIT per second limit


This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365


By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.

I've tested on my onw server and it works!:

var lost_addresses = [];
    geocode_count  = 0;
    resNumber = 0;
    map = new GMaps({
       div: '#gmap_marker',
       lat: 43.921493,
       lng: 12.337646,
    });

function loadMarkerTimeout(timeout) {
    setTimeout(loadMarker, timeout)
}

function loadMarker() { 
    map.setZoom(6);         
    $.ajax({
            url: [Insert here your URL] ,
            type:'POST',
            data: {
                "action":   "loadMarker"
            },
            success:function(result){

                /***************************
                 * Assuming your ajax call
                 * return something like: 
                 *   array(
                 *      'status' => 'success',
                 *      'results'=> $resultsArray
                 *   );
                 **************************/

                var res=JSON.parse(result);
                if(res.status == 'success') {
                    resNumber = res.results.length;
                    //Call the geoCoder function
                    getGeoCodeFor(map, res.results);
                }
            }//success
    });//ajax
};//loadMarker()

$().ready(function(e) {
  loadMarker();
});

//Geocoder function
function getGeoCodeFor(maps, addresses) {
        $.each(addresses, function(i,e){                
                GMaps.geocode({
                    address: e.address,
                    callback: function(results, status) {
                            geocode_count++;        

                            if (status == 'OK') {       

                                //if the element is alreay in the array, remove it
                                lost_addresses = jQuery.grep(lost_addresses, function(value) {
                                    return value != e;
                                });


                                latlng = results[0].geometry.location;
                                map.addMarker({
                                        lat: latlng.lat(),
                                        lng: latlng.lng(),
                                        title: 'MyNewMarker',
                                    });//addMarker
                            } else if (status == 'ZERO_RESULTS') {
                                //alert('Sorry, no results found');
                            } else if(status == 'OVER_QUERY_LIMIT') {

                                //if the element is not in the losts_addresses array, add it! 
                                if( jQuery.inArray(e,lost_addresses) == -1) {
                                    lost_addresses.push(e);
                                }

                            } 

                            if(geocode_count == addresses.length) {
                                //set counter == 0 so it wont's stop next round
                                geocode_count = 0;

                                setTimeout(function() {
                                    getGeoCodeFor(maps, lost_addresses);
                                }, 2500);
                            }
                    }//callback
                });//GeoCode
        });//each
};//getGeoCodeFor()

Example:

_x000D_
_x000D_
map = new GMaps({_x000D_
  div: '#gmap_marker',_x000D_
  lat: 43.921493,_x000D_
  lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = {  _x000D_
   "status":"success",_x000D_
   "results":[  _x000D_
  {  _x000D_
     "customerId":1,_x000D_
     "address":"Via Italia 43, Milano (MI)",_x000D_
     "customerName":"MyAwesomeCustomer1"_x000D_
  },_x000D_
  {  _x000D_
     "customerId":2,_x000D_
     "address":"Via Roma 10, Roma (RM)",_x000D_
     "customerName":"MyAwesomeCustomer2"_x000D_
  }_x000D_
   ]_x000D_
};_x000D_
   _x000D_
function loadMarkerTimeout(timeout) {_x000D_
  setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
  map.setZoom(6);_x000D_
 _x000D_
  $.ajax({_x000D_
    url: '/echo/html/',_x000D_
    type: "POST",_x000D_
    data: jsonData,_x000D_
    cache: false,_x000D_
    success:function(result){_x000D_
_x000D_
      var res=JSON.parse(result);_x000D_
      if(res.status == 'success') {_x000D_
        resNumber = res.results.length;_x000D_
        //Call the geoCoder function_x000D_
        getGeoCodeFor(map, res.results);_x000D_
      }_x000D_
    }//success_x000D_
  });//ajax_x000D_
  _x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
  loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
  $.each(addresses, function(i,e){    _x000D_
    GMaps.geocode({_x000D_
      address: e.address,_x000D_
      callback: function(results, status) {_x000D_
        geocode_count++;  _x000D_
        _x000D_
        console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
        _x000D_
        if (status == 'OK') {  _x000D_
_x000D_
          //if the element is alreay in the array, remove it_x000D_
          lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
            return value != e;_x000D_
          });_x000D_
_x000D_
_x000D_
          latlng = results[0].geometry.location;_x000D_
          map.addMarker({_x000D_
            lat: latlng.lat(),_x000D_
            lng: latlng.lng(),_x000D_
            title: e.customerName,_x000D_
          });//addMarker_x000D_
        } else if (status == 'ZERO_RESULTS') {_x000D_
          //alert('Sorry, no results found');_x000D_
        } else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
          //if the element is not in the losts_addresses array, add it! _x000D_
          if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
            lost_addresses.push(e);_x000D_
          }_x000D_
_x000D_
        } _x000D_
_x000D_
        if(geocode_count == addresses.length) {_x000D_
          //set counter == 0 so it wont's stop next round_x000D_
          geocode_count = 0;_x000D_
_x000D_
          setTimeout(function() {_x000D_
            getGeoCodeFor(maps, lost_addresses);_x000D_
          }, 2500);_x000D_
        }_x000D_
      }//callback_x000D_
    });//GeoCode_x000D_
  });//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
  min-height:250px;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  position: relative; _x000D_
  overflow: hidden;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
_x000D_
_x000D_

Default values and initialization in Java

These are the main factors involved:

  1. member variable (default OK)
  2. static variable (default OK)
  3. final member variable (not initialized, must set on constructor)
  4. final static variable (not initialized, must set on a static block {})
  5. local variable (not initialized)

Note 1: you must initialize final member variables on every implemented constructor!

Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:

private final int memberVar;

public Foo() {
    // Invalid initialization of a final member
    init();
}

private void init() {
    memberVar = 10;
}

Note 3: arrays are Objects in Java, even if they store primitives.

Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.

I am attaching a code example, presenting the aforementioned cases:

public class Foo {
    // Static and member variables are initialized to default values

    // Primitives
    private int a; // Default 0
    private static int b; // Default 0

    // Objects
    private Object c; // Default NULL
    private static Object d; // Default NULL

    // Arrays (note: they are objects too, even if they store primitives)
    private int[] e; // Default NULL
    private static int[] f; // Default NULL

    // What if declared as final?

    // Primitives
    private final int g; // Not initialized. MUST set in the constructor
    private final static int h; // Not initialized. MUST set in a static {}

    // Objects
    private final Object i; // Not initialized. MUST set in constructor
    private final static Object j; // Not initialized. MUST set in a static {}

    // Arrays
    private final int[] k; // Not initialized. MUST set in constructor
    private final static int[] l; // Not initialized. MUST set in a static {}

    // Initialize final statics
    static {
        h = 5;
        j = new Object();
        l = new int[5]; // Elements of l are initialized to 0
    }

    // Initialize final member variables
    public Foo() {
        g = 10;
        i = new Object();
        k = new int[10]; // Elements of k are initialized to 0
    }

    // A second example constructor
    // You have to initialize final member variables to every constructor!
    public Foo(boolean aBoolean) {
        g = 15;
        i = new Object();
        k = new int[15]; // Elements of k are initialized to 0
    }

    public static void main(String[] args) {
        // Local variables are not initialized
        int m; // Not initialized
        Object n; // Not initialized
        int[] o; // Not initialized

        // We must initialize them before use
        m = 20;
        n = new Object();
        o = new int[20]; // Elements of o are initialized to 0
    }
}

Can we set a Git default to fetch all tags during a remote pull?

For me the following seemed to work.

git pull --tags

Disabling swap files creation in vim

You can set backupdir and directory to null in order to completely disable your swap files, but it is generally recommended to simply put them in a centralized directory. Vim takes care of making sure that there aren't name collissions or anything like that; so, this is a completely safe alternative:

set backupdir=~/.vim/backup/
set directory=~/.vim/backup/

pip3: command not found but python3-pip is already installed

You can use python3 -m pip as a synonym for pip3. That has saved me a couple of times.

Where do I find the definition of size_t?

As for "Why not use int or unsigned int?", simply because it's semantically more meaningful not to. There's the practical reason that it can be, say, typedefd as an int and then upgraded to a long later, without anyone having to change their code, of course, but more fundamentally than that a type is supposed to be meaningful. To vastly simplify, a variable of type size_t is suitable for, and used for, containing the sizes of things, just like time_t is suitable for containing time values. How these are actually implemented should quite properly be the implementation's job. Compared to just calling everything int, using meaningful typenames like this helps clarify the meaning and intent of your program, just like any rich set of types does.

If Else in LINQ

This might work...

from p in db.products
    select new
    {
        Owner = (p.price > 0 ?
            from q in db.Users select q.Name :
            from r in db.ExternalUsers select r.Name)
    }

SQL Query Multiple Columns Using Distinct on One Column Only

select * from 
(select 
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Update to Tomcat 7.0.58 (or newer).

See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16

The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.

sql use statement with variable

Use exec sp_execsql @Sql

Example

DECLARE @sql as nvarchar(100)  
DECLARE @paraDOB datetime  
SET @paraDOB = '1/1/1981'  
SET @sql=N'SELECT * FROM EmpMast WHERE DOB >= @paraDOB'  
exec sp_executesql @sql,N'@paraDOB datetime',@paraDOB

How to specify multiple return types using type-hints

In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

More info: How to annotate types of multiple return values?

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

How to add a title to a html select tag

<select>
    <optgroup label = "Choose One">
    <option value ="sydney">Sydney</option>
    <option value ="melbourne">Melbourne</option>
    <option value ="cromwell">Cromwell</option>
    <option value ="queenstown">Queenstown</option>
    </optgroup>
</select>

How can I call controller/view helper methods from the console in Ruby on Rails?

One possible approach for Helper method testing in the Ruby on Rails console is:

Struct.new(:t).extend(YourHelper).your_method(*arg)

And for reload do:

reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

for me , using export PYTHONIOENCODING=UTF-8 before executing python command worked .

How to make an image center (vertically & horizontally) inside a bigger div

Use Flexbox:

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* Centering y-axis */
  align-items :center; /* Centering x-axis */
}

Firebase: how to generate a unique numeric ID for key?

https://firebase.google.com/docs/firestore/manage-data/transactions

Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

How to get the date from the DatePicker widget in Android?

The DatePicker class has methods for getting the month, year, day of month. Or you can use an OnDateChangedListener.

Random state (Pseudo-random number) in Scikit learn

If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

However, if a fixed value is assigned like random_state = 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

How to draw lines in Java

A very simple example of a swing component to draw lines. It keeps internally a list with the lines that have been added with the method addLine. Each time a new line is added, repaint is invoked to inform the graphical subsytem that a new paint is required.

The class also includes some example of usage.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LinesComponent extends JComponent{

private static class Line{
    final int x1; 
    final int y1;
    final int x2;
    final int y2;   
    final Color color;

    public Line(int x1, int y1, int x2, int y2, Color color) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        this.color = color;
    }               
}

private final LinkedList<Line> lines = new LinkedList<Line>();

public void addLine(int x1, int x2, int x3, int x4) {
    addLine(x1, x2, x3, x4, Color.black);
}

public void addLine(int x1, int x2, int x3, int x4, Color color) {
    lines.add(new Line(x1,x2,x3,x4, color));        
    repaint();
}

public void clearLines() {
    lines.clear();
    repaint();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (Line line : lines) {
        g.setColor(line.color);
        g.drawLine(line.x1, line.y1, line.x2, line.y2);
    }
}

public static void main(String[] args) {
    JFrame testFrame = new JFrame();
    testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    final LinesComponent comp = new LinesComponent();
    comp.setPreferredSize(new Dimension(320, 200));
    testFrame.getContentPane().add(comp, BorderLayout.CENTER);
    JPanel buttonsPanel = new JPanel();
    JButton newLineButton = new JButton("New Line");
    JButton clearButton = new JButton("Clear");
    buttonsPanel.add(newLineButton);
    buttonsPanel.add(clearButton);
    testFrame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
    newLineButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int x1 = (int) (Math.random()*320);
            int x2 = (int) (Math.random()*320);
            int y1 = (int) (Math.random()*200);
            int y2 = (int) (Math.random()*200);
            Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
            comp.addLine(x1, y1, x2, y2, randomColor);
        }
    });
    clearButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            comp.clearLines();
        }
    });
    testFrame.pack();
    testFrame.setVisible(true);
}

}