Programs & Examples On #Django pyodbc

A 3rd-party database backend for Django that uses ODBC to query Microsoft SQL Server. The typical driver stack is django-pyodbc -> pyodbc -> unixodbc -> freetds on Linux. As for 5/2014, this fork is most active maintained: https://github.com/lionheart/django-pyodbc/

Java: Get first item from a collection

Functional way:

public static <T> Optional<T> findFirst(List<T> result) {
    return Optional.ofNullable(result)
            .map(List::stream)
            .flatMap(Stream::findFirst);
}

above code snippet preserve from NullPointerException and IndexOutOfBoundsException

How big can a MySQL database get before performance starts to degrade

In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.

I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.

The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.

The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.

There's a lot to this issues and as in a lot of cases the devil is in the details.

HTML table with fixed headers and a fixed column?

You might be looking for this.

It has some known issues though.

PNG transparency issue in IE8

Dan Tello fix worked well for me.

One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.

Correcting the width and height CSS or removing them altogether fixed.

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

To summarize the conversation in the comments:

  • There is no need to use simplejson library, the same library is included with Python as the json module.

  • There is no need to decode a response from UTF8 to unicode, the simplejson / json .loads() method can handle UTF8 encoded data natively.

  • pycurl has a very archaic API. Unless you have a specific requirement for using it, there are better choices.

requests offers the most friendly API, including JSON support. If you can, replace your call with:

import requests

return requests.get(url).json()

Angular-cli from css to scss

CSS Preprocessor integration for Angular CLI: 6.0.3

When generating a new project you can also define which extension you want for style files:

ng new sassy-project --style=sass

Or set the default style on an existing project:

ng config schematics.@schematics/angular:component.styleext scss

Angular CLI Documentation for all major CSS preprocessors

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix : 

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

AngularJS: How do I manually set input to $valid in controller?

to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

Remove file extension from a file name string

There's a method in the framework for this purpose, which will keep the full path except for the extension.

System.IO.Path.ChangeExtension(path, null);

If only file name is needed, use

System.IO.Path.GetFileNameWithoutExtension(path);

access key and value of object using *ngFor

From Angular 6.1 you can use the keyvalue pipe:

<div *ngFor="let item of testObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

But it has the inconvenient that sorts the resulting list by the key value. If you need something neutral:

@Pipe({ name: 'keyValueUnsorted', pure: false  })
export class KeyValuePipe implements PipeTransform {
  transform(input: any): any {
    let keys = [];
    for (let key in input) {
      if (input.hasOwnProperty(key)) {
        keys.push({ key: key, value: input[key]});
      }
    }
    return keys;
  }
}

Don't forget to specify the pure:false pipe attribute. In this case, the pipe is invoked on each change-detection cycle, even if the input reference has not changed (so is the case when you add properties to an object).

Correct way to write line to file?

You can also try filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

Writes into my_file.txt

Takes an iterable or an object with __str__ support.

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

You should write textcolor in xml as

android:textColor="@color/text_color"

or

android:textColor="#FFFFFF"

Append integer to beginning of list in Python

Alternative:

>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

[NOTE]:

collections.deque is faster than Python pure list in a loop Relevant-Post.

Modifying location.hash without page scrolling

If on your page you use id as sort of an anchor point, and you have scenarios where you want to have users to append #something to the end of the url and have the page scroll to that #something section by using your own defined animated javascript function, hashchange event listener will not be able to do that.

If you simply put a debugger immediate after hashchange event, for example, something like this(well, I use jquery, but you get the point):

$(window).on('hashchange', function(){debugger});

You will notice that as soon as you change your url and hit the enter button, the page stops at the corresponding section immediately, only after that, your own defined scrolling function will get triggered, and it sort of scrolls to that section, which looks very bad.

My suggestion is:

  1. do not use id as your anchor point to the section you want to scroll to.

  2. If you must use ID, like I do. Use 'popstate' event listener instead, it will not automatically scroll to the very section you append to the url, instead, you can call your own defined function inside the popstate event.

    $(window).on('popstate', function(){myscrollfunction()});

Finally you need to do a bit trick in your own defined scrolling function:

    let hash = window.location.hash.replace(/^#/, '');
    let node = $('#' + hash);
    if (node.length) {
        node.attr('id', '');
    }
    if (node.length) {
        node.attr('id', hash);
    }

delete id on your tag and reset it.

This should do the trick.

How to change the default encoding to UTF-8 for Apache?

In httpd.conf add (or change if it's already there):

AddDefaultCharset utf-8

keycode 13 is for which key

The Enter key should have the keycode 13. Is it not working?

Use own username/password with git and bitbucket

Run

git remote -v

and check whether your origin's URL has your co-worker's username hardcoded in there. If so, substitute it with your own:

git remote set-url origin <url-with-your-username>

Python: Continuing to next iteration in outer loop

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don't risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

How to create a multi line body in C# System.Net.Mail.MailMessage

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

How can I override Bootstrap CSS styles?

To reset the styles defined for legend in bootstrap, you can do following in your css file:

legend {
  all: unset;
}

Ref: https://css-tricks.com/almanac/properties/a/all/

The all property in CSS resets all of the selected element's properties, except the direction and unicode-bidi properties that control text direction.

Possible values are: initial, inherit & unset.

Side note: clear property is used in relation with float (https://css-tricks.com/almanac/properties/c/clear/)

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

See code example below:

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);

SQL-Server: The backup set holds a backup of a database other than the existing

I was just trying to solve this issue.

I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.

Hopefully this helps somebody else.

How to create an on/off switch with Javascript/CSS?

Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:

<style type="text/css">
.toggleSwitch {
    width: ...;
    height: ...;
    /* add other styling as appropriate to position element */
    position: relative;
}
.slider {
    background-image: url(...);
    position: absolute;
    width: ...;
    height: ...;
}
.slider.on {
    right: 0;
}
.slider.off {
    left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
    var oldRE = RegExp('\\b'+oldClass+'\\b');
    elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
    var onRE = RegExp('\\b'+on+'\\b');
    if (onRE.test(elt.className)) {
        elt.className = elt.className.replace(onRE, off);
    } else {
        replaceClass(elt, off, on);
    }
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>

Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.

Does functional programming replace GoF design patterns?

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

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

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

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

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

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

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Under normal conditions, at least 3379 MB of disk space is needed. If you do not have that much space, to lower this requirement;

mongod.exe --smallfiles

This is not the only requirement. But this may be your problem.

What is JNDI? What is its basic use? When is it used?

I will use one example to explain how JNDI can be used to configure database without any application developer knowing username and password of the database.

1) We have configured the data source in JBoss server's standalone-full.xml. Additionally, we can configure pool details also.

 <datasource jta="false" jndi-name="java:/DEV.DS" pool-name="DEV" enabled="true" use-ccm="false">
                <connection-url>jdbc:oracle:thin:@<IP>:1521:DEV</connection-url>
                <driver-class>oracle.jdbc.OracleDriver</driver-class>
                <driver>oracle</driver>
                <security>
                    <user-name>usname</user-name>
                    <password>pass</password>
                    </security>
                    <security>

 <security-domain>encryptedSecurityDomain</security-domain>
                    </security>

                <validation>
                    <validate-on-match>false</validate-on-match>
                    <background-validation>false</background-validation>
                    <background-validation-millis>1</background-validation-millis>
                </validation>
                <statement>
                    <prepared-statement-cache-size>0</prepared-statement-cache-size>
                    <share-prepared-statements>false</share-prepared-statements>
                    <pool>
                        <min-pool-size>5</min-pool-size>
                        <max-pool-size>10</max-pool-size>
                    </pool>
                </statement>
            </datasource>

enter image description here

Now, this jndi-name and its associated datasource object will be available for our application.application.

2) We can retrieve this datasource object using JndiDataSourceLookup class.

enter image description here

Spring will instantiate the datasource bean, after we provide the jndi-name.

Now, we can change the pool size, user name or password as per our environment or requirement, but it will not impact the application.

Note : encryptedSecurityDomain, we need to configure it separately in JBoss server like

<security-domain name="encryptedSecurityDomain" cache-type="default">
                    <authentication>
                        <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                            <module-option name="username" value="<usernamefordb>"/>
                            <module-option name="password" value="894c8a6aegc8d028ce169c596d67afd0"/>
                        </login-module>
                    </authentication>
                </security-domain>

This is one of the use cases. Hope it clarifies.

Serialize JavaScript object into JSON string

You can use a named function on the constructor.

MyClass1 = function foo(id, member) {
    this.id = id;
    this.member = member;
}

var myobject = new MyClass1("5678999", "text");

console.log( myobject.constructor );

//function foo(id, member) {
//    this.id = id;
//    this.member = member;
//}

You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

How to use jQuery to call an ASP.NET web service?

$.ajax({
 type: 'POST',
 url: 'data.asmx/getText',
 data: {'argInput' : 'input arg(s)'},
 complete: function(xData, status) {
 $('#txt').html($(xData.responseXML).text()); // result
 }
});

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In the middle of the stack trace, lost in the "reflection" junk, you can find the root cause:

The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH. Please check your CLASSPATH specification, and the name of the driver.

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Open window in JavaScript with HTML inserted

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

PHP header() redirect with POST variables

Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:

if(correct){
    header("Location: passed.php");
} else {
    $smarty->assign("variables", $_POST);
    $smarty->display("register_error.php");
    exit;
}

I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.

If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it

ex.

register.php?name=mr_jones&address==......
echo $_GET[name];

Get the size of the screen, current web page and browser window

Here is a cross browser solution with pure JavaScript (Source):

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

echo that outputs to stderr

Here is a function for checking the exit status of the last command, showing error and terminate the script.

or_exit() {
    local exit_status=$?
    local message=$*

    if [ "$exit_status" -gt 0 ]
    then
        echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
        exit "$exit_status"
    fi
}

Usage:

gzip "$data_dir"
    or_exit "Cannot gzip $data_dir"

rm -rf "$junk"
    or_exit Cannot remove $junk folder

The function prints out the script name and the date in order to be useful when the script is called from crontab and logs the errors.

59 23 * * * /my/backup.sh 2>> /my/error.log

How to support placeholder attribute in IE8 and 9

if you use jquery you can do like this. from this site Placeholder with Jquery

$('[placeholder]').parents('form').submit(function() {
  $(this).find('[placeholder]').each(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
    }
  })
});

these are the alternate links

  1. Placeholder jquery library
  2. HTML5 polyfills -- go for placeholder section

Measuring the distance between two coordinates in PHP

For exact values do it like that:

public function DistAB()
{
      $delta_lat = $this->lat_b - $this->lat_a ;
      $delta_lon = $this->lon_b - $this->lon_a ;

      $a = pow(sin($delta_lat/2), 2);
      $a += cos(deg2rad($this->lat_a9)) * cos(deg2rad($this->lat_b9)) * pow(sin(deg2rad($delta_lon/29)), 2);
      $c = 2 * atan2(sqrt($a), sqrt(1-$a));

      $distance = 2 * $earth_radius * $c;
      $distance = round($distance, 4);

      $this->measure = $distance;
}

Hmm I think that should do it...

Edit:

For formulars and at least JS-implementations try: http://www.movable-type.co.uk/scripts/latlong.html

Dare me... I forgot to deg2rad all the values in the circle-functions...

Can a PDF file's print dialog be opened with Javascript?

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

YouTube Video Embedded via iframe Ignoring z-index?

I have the same problem on YouTube iframe embeds only in internet explorer though.

Z-index was being ignored totally, or the flash video was just appearing at highest index possible.

This was what I used, slight adapting the above jquery script.

My embed code, straight from YouTube...

<iframe width="560" height="315" src="http://www.youtube.com/embed/QldZiR9eQ_0?rel=0" frameborder="0" allowfullscreen></iframe>


The jQuery slighty adapted from the above answer...

$('iframe').each( function() {
    var url = $(this).attr("src")
    $(this).attr({
        "src" : url.replace('?rel=0', '')+"?wmode=transparent",
        "wmode" : "Opaque"
    })
});


Basically if you don't select Show suggested videos when the video finishes in your embed settings, you have a ?rel=0 at the end of your "src" url. So I've added the replace bit in case ?rel=0 exists. Otherwise ?wmode=transparent won't work.


Java: Retrieving an element from a HashSet

First of all convert your set to Array. Then, get item by index of array .

Set uniqueItem = new HashSet() ;
uniqueItem.add("0");
uniqueItem.add("1");
uniqueItem.add("0");

Object[] arrayItem = uniqueItem.toArray(); 
for(int i = 0; i < uniqueItem.size();i++){
    System.out.println("Item "+i+" "+arrayItem[i].toString());
}

Difference between HttpModule and HttpClientModule

HttpClient is a new API that came with 4.3, it has updated API's with support for progress events, json deserialization by default, Interceptors and many other great features. See more here https://angular.io/guide/http

Http is the older API and will eventually be deprecated.

Since their usage is very similar for basic tasks I would advise using HttpClient since it is the more modern and easy to use alternative.

How can I list all collections in the MongoDB shell?

First you need to use a database to show all collection/tables inside it.

>show dbs
users 0.56787GB
test (empty)
>db.test.help() // this will give you all the function which can be used with this db
>use users
>show tables //will show all the collection in the db

Create excel ranges using column numbers in vba?

Function fncToLetters(vintCol As Integer) As String

        Dim mstrDigits As String

    ' Convert a positive number n to its digit representation in base 26.
    mstrDigits = ""
    Do While vintCol > 0
        mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
        vintCol = Int((vintCol - 1) / 26)
    Loop

    fncToLetters = mstrDigits

End Function

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Bearer authentication in OpenAPI 3.0.0

OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:

openapi: 3.0.0
...

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT  # optional, for documentation purposes only

security:
  - bearerAuth: []

This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).

UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.

Adding Authorization header programmatically (Swagger UI 3.x)

If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x; UI 2.x used a different technique.

// index.html

const ui = SwaggerUIBundle({
  url: "http://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

Using 'sudo apt-get install build-essentials'

I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:

sudo vi /etc/apt/sources.list

and added the following lines:

deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main

If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:

sudo apt-get update
sudo apt-get install build-essential

Hopefully this will help someone who had the same problem that I did.

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

How to delete a module in Android Studio

  1. edit the project's settings.gradle file: delete the module name (, ':xxxxx') where xxxxx is the module name to be deleted

  2. using the file explorer delete the module folder

by the way, the current version of the Android Studio (v3.1.2) throws an exception and exits the removing with an error while I'm removing the module through Module Settings => selected module => - (minus)

Best Regards, thanks)

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

How to remove only 0 (Zero) values from column in excel 2010

Press Control + H, then select Options and check Match entire cell contents and Match case. In the Find what field type a 0, and leave the Replace with field blank. Then Replace All. This will remove all of the zeros that are stand alone.

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

how to properly display an iFrame in mobile safari

This only works if you control both the outside page and the iframe page.

On the outside page, make the iframe unscrollable.

<iframe src="" height=200 scrolling=no></iframe>

On the iframe page, add this.

<!doctype html>
...
<style>
html, body {height:100%; overflow:hidden}
body {overflow:auto; -webkit-overflow-scrolling:touch}
</style>

This works because modern browsers uses html to determine the height, so we just give that a fixed height and turn the body into a scrollable node.

Difference between static, auto, global and local variable in the context of c and c++

When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -

#include<iostream.h>
#include<conio.h>
class test
{
    void fun()
    {
        static int a=0;
        a++;
        cout<<"Value of a = "<<a<<"\n";
    }
};
void main()
{
    clrscr();
    test obj1;
    test obj2;
    test obj3;
    obj1.fun();
    obj2.fun();
    obj3.fun();
    getch();
}

This program will generate the following output: -

Value of a = 1
Value of a = 2
Value of a = 3

The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()

Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -

Value of a = 1
Value of a = 1
Value of a = 1

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I know this is an old post, but this problem still occurs fairly frequently. The simplest way I've found to resolve it is to rename/delete the .svn/all-wcprops file in the affected folder, then run an update and commit.

Error handling in getJSON calls

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

How do I convert datetime to ISO 8601 in PHP

After PHP 5 you can use this: echo date("c"); form ISO 8601 formatted datetime.

http://ideone.com/nD7piL

Note for comments:

Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh].

But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c"). A similar discussion here.

Difference between Subquery and Correlated Subquery

when it comes to subquery and co-related query both have inner query and outer query the only difference is in subquery the inner query doesn't depend on outer query, whereas in co-related inner query depends on outer.

vim line numbers - how to have them on by default?

set nu set ai set tabstop=4 set ls=2 set autoindent

Add the above code in your .vimrc file. if .vimrc file is not present please create in your home directory (/home/name of user)

set nu -> This makes Vim display line numbers

set ai -> This makes Vim enable auto-indentation

set ls=2 -> This makes Vim show a status line

set tabstop=4 -> This makes Vim set tab of length 4 spaces (it is 8 by default)

enter image description here

enter image description here

The filename will also be displayed.

How to run Visual Studio post-build events for debug build only

Visual Studio 2015: The correct syntax is (keep it on one line):

if "$(ConfigurationName)"=="My Debug CFG" ( xcopy "$(TargetDir)test1.tmp" "$(TargetDir)test.xml" /y) else ( xcopy "$(TargetDir)test2.tmp" "$(TargetDir)test.xml" /y)

No error 255 here.

How to have a drop down <select> field in a rails form?

In your model,

class Contact
  self.email_providers = %w[Gmail Yahoo MSN]
  validates :email_provider, :inclusion => email_providers
end

In your form,

<%= f.select :email_provider, 
    options_for_select(Contact.email_providers, @contact.email_provider) %>

the second arg of the options_for_select will have any current email_provider selected.

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.

setting y-axis limit in matplotlib

Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))

How to count TRUE values in a logical vector

I've been doing something similar a few weeks ago. Here's a possible solution, it's written from scratch, so it's kind of beta-release or something like that. I'll try to improve it by removing loops from code...

The main idea is to write a function that will take 2 (or 3) arguments. First one is a data.frame which holds the data gathered from questionnaire, and the second one is a numeric vector with correct answers (this is only applicable for single choice questionnaire). Alternatively, you can add third argument that will return numeric vector with final score, or data.frame with embedded score.

fscore <- function(x, sol, output = 'numeric') {
    if (ncol(x) != length(sol)) {
        stop('Number of items differs from length of correct answers!')
    } else {
        inc <- matrix(ncol=ncol(x), nrow=nrow(x))
        for (i in 1:ncol(x)) {
            inc[,i] <- x[,i] == sol[i]
        }
        if (output == 'numeric') {
            res <- rowSums(inc)
        } else if (output == 'data.frame') {
            res <- data.frame(x, result = rowSums(inc))
        } else {
            stop('Type not supported!')
        }
    }
    return(res)
}

I'll try to do this in a more elegant manner with some *ply function. Notice that I didn't put na.rm argument... Will do that

# create dummy data frame - values from 1 to 5
set.seed(100)
d <- as.data.frame(matrix(round(runif(200,1,5)), 10))
# create solution vector
sol <- round(runif(20, 1, 5))

Now apply a function:

> fscore(d, sol)
 [1] 6 4 2 4 4 3 3 6 2 6

If you pass data.frame argument, it will return modified data.frame. I'll try to fix this one... Hope it helps!

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

Git command to checkout any branch and overwrite local changes

git reset and git clean can be overkill in some situations (and be a huge waste of time).

If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

How to use pagination on HTML tables?

With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page

Code:

$(document).ready(function () {
    $(document).ajaxComplete(function () {
        paginate('#myTableId',10);
        function paginate(tableName,RecordsPerPage) {
            $('#nav').remove();
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        }
    });
});

How can I view live MySQL queries?

Even though an answer has already been accepted, I would like to present what might even be the simplest option:

$ mysqladmin -u bob -p -i 1 processlist

This will print the current queries on your screen every second.

  • -u The mysql user you want to execute the command as
  • -p Prompt for your password (so you don't have to save it in a file or have the command appear in your command history)
  • i The interval in seconds.
  • Use the --verbose flag to show the full process list, displaying the entire query for each process. (Thanks, nmat)

There is a possible downside: fast queries might not show up if they run between the interval that you set up. IE: My interval is set at one second and if there is a query that takes .02 seconds to run and is ran between intervals, you won't see it.

Use this option preferably when you quickly want to check on running queries without having to set up a listener or anything else.

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit returnEXPR.

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

Write to UTF-8 file in Python

Read the following: http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig

Do this

with codecs.open("test_output", "w", "utf-8-sig") as temp:
    temp.write("hi mom\n")
    temp.write(u"This has ?")

The resulting file is UTF-8 with the expected BOM.

Bash array with spaces in elements

I agree with others that it's likely how you're accessing the elements that is the problem. Quoting the file names in the array assignment is correct:

FILES=(
  "2011-09-04 21.43.02.jpg"
  "2011-09-05 10.23.14.jpg"
  "2011-09-09 12.31.16.jpg"
  "2011-09-11 08.43.12.jpg"
)

for f in "${FILES[@]}"
do
  echo "$f"
done

Using double quotes around any array of the form "${FILES[@]}" splits the array into one word per array element. It doesn't do any word-splitting beyond that.

Using "${FILES[*]}" also has a special meaning, but it joins the array elements with the first character of $IFS, resulting in one word, which is probably not what you want.

Using a bare ${array[@]} or ${array[*]} subjects the result of that expansion to further word-splitting, so you'll end up with words split on spaces (and anything else in $IFS) instead of one word per array element.

Using a C-style for loop is also fine and avoids worrying about word-splitting if you're not clear on it:

for (( i = 0; i < ${#FILES[@]}; i++ ))
do
  echo "${FILES[$i]}"
done

Select rows where column is null

I'm not sure if this answers your question, but using the IS NULL construct, you can test whether any given scalar expression is NULL:

SELECT * FROM customers WHERE first_name IS NULL

On MS SQL Server, the ISNULL() function returns the first argument if it's not NULL, otherwise it returns the second. You can effectively use this to make sure a query always yields a value instead of NULL, e.g.:

SELECT ISNULL(column1, 'No value found') FROM mytable WHERE column2 = 23

Other DBMSes have similar functionality available.

If you want to know whether a column can be null (i.e., is defined to be nullable), without querying for actual data, you should look into information_schema.

How to set default value for form field in Symfony2?

Default values are set by configuring corresponding entity. Before binding the entity to form set its color field to "#0000FF":

// controller action
$project = new Project();
$project->setColor('#0000FF');
$form = $this->createForm(new ProjectType(), $project);

How do I change the owner of a SQL Server database?

This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.

This should have nothing to do with the owner of the db.

Finding longest string in array

I see the shortest solution

function findLong(s){
  return Math.max.apply(null, s.split(' ').map(w => w.length));
}

How to calculate distance from Wifi router using Signal Strength?

Don't care if you are a moderator. I wrote my text towards my audience not as a technical writer

All you guys need to learn to navigate with tools that predate GPS. Something like a sextant, octant, backstaff or an astrolabe.

If you have receive the signal from 3 different locations then you only need to measure the signal strength and make a ratio from those locations. Simple triangle calculation where a2+b2=c2. The stronger the signal strength the closer the device is to the receiver.

Check if Cookie Exists

There are a lot of right answers here depending on what you are trying to accomplish; here's my attempt at providing a comprehensive answer:

Both the Request and Response objects contain Cookies properties, which are HttpCookieCollection objects.

Request.Cookies:

  • This collection contains cookies received from the client
  • This collection is read-only
  • If you attempt to access a non-existent cookie from this collection, you will receive a null value.

Response.Cookies:

  • This collection contains only cookies that have been added by the server during the current request.
  • This collection is writeable
  • If you attempt to access a non-existent cookie from this collection, you will receive a new cookie object; If the cookie that you attempted to access DOES NOT exist in the Request.Cookies collection, it will be added (but if the Request.Cookies object already contains a cookie with the same key, and even if it's value is stale, it will not be updated to reflect the changes from the newly-created cookie in the Response.Cookies collection.

Solutions


If you want to check for the existence of a cookie from the client, do one of the following

  • Request.Cookies["COOKIE_KEY"] != null
  • Request.Cookies.Get("COOKIE_KEY") != null
  • Request.Cookies.AllKeys.Contains("COOKIE_KEY")

If you want to check for the existence of a cookie that has been added by the server during the current request, do the following:

  • Response.Cookies.AllKeys.Contains("COOKIE_KEY") (see here)

Attempting to check for a cookie that has been added by the server during the current request by one of these methods...

  • Response.Cookies["COOKIE_KEY"] != null
  • Response.Cookies.Get("COOKIE_KEY") != null (see here)

...will result in the creation of a cookie in the Response.Cookies collection and the state will evaluate to true.

Usage of MySQL's "IF EXISTS"

The accepted answer works well and one can also just use the

If Exists (...) Then ... End If; 

syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert

One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

Adding an onclick event to a div element

Depends in how you are hiding your div, diplay=none is different of visibility=hidden and the opacity=0

  • Visibility then use ...style.visibility='visible'

  • Display then use ...style.display='block' (or others depends how
    you setup ur css, inline, inline-block, flex...)

  • Opacity then use ...style.opacity='1';

jQuery ui dialog change title after load-callback

Even better!

    jQuery( "#dialog" ).attr('title', 'Error');
    jQuery( "#dialog" ).text('You forgot to enter your first name');

What are the applications of binary trees?

BST a kind of binary tree is used in Unix kernels for managing a set of virtual memory areas(VMAs).

How to copy selected lines to clipboard in vim

Install "xclip" if you haven't...

sudo apt-get install xclip

Xclip puts the data into the "selection/highlighted" clipboard that you middle-click to paste as opposed to "ctrl+v"

While in vim use ex commands:

7w !xclip

or

1,7w !xclip

or

%w !xclip

Then just middle-click to paste into any other application...

Vertical Align text in a Label

I had a similar problem and solved it wrapping the label into a div and setting the following styles:

<div style="display: table; vertical-align: middle">
  <label style="display: table-cell;" ... > ... </label>
</div>

Object of class stdClass could not be converted to string - laravel

$data is indeed an array, but it's made up of objects.

Convert its content to array before creating it:

$data = array();
foreach ($results as $result) {
   $result->filed1 = 'some modification';
   $result->filed2 = 'some modification2';
   $data[] = (array)$result;  
   #or first convert it and then change its properties using 
   #an array syntax, it's up to you
}
Excel::create(....

How can I force a long string without any blank to be wrapped?

Use a CSS method to force wrap a string that has no white-spaces. Three methods:

1) Use the CSS white-space property. To cover browser inconsistencies, you have to declare it several ways. So just put your looooong string into some block level element (e.g., div, pre, p) and give that element the following css:

some_block_level_tag {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

2) use the force-wrap mixin from Compass.

3) I was just looking into this as well and I think might also work (but I need to test browser support more completely):

.break-me {
    word-wrap: break-word;
    overflow-wrap: break-word;
}

Reference: wrapping content

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

How to resolve the "ADB server didn't ACK" error?

Similar questions are

First close IDE.

In my case I killed adb via Task Manager(adb kill-server did not work)
then adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

If you see "started successfully" than it is solved, now start IDE.

CSS – why doesn’t percentage height work?

Another option is to add style to div

<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
 //to be scrolled 
</div>

And it means that an element is positioned relative to the nearest positioned ancestor.

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

What does android:layout_weight mean?

With layout_weight you can specify a size ratio between multiple views. E.g. you have a MapView and a table which should show some additional information to the map. The map should use 3/4 of the screen and table should use 1/4 of the screen. Then you will set the layout_weight of the map to 3 and the layout_weight of the table to 1.

To get it work you also have to set the height or width (depending on your orientation) to 0px.

How many parameters are too many?

I'd draw the limit for public functions at 5 parameters myself.

IMHO, long parameter lists are only acceptable in private/local helper functions that are only meant to be called from a few specific places in the code. In those cases, you may need to pass a lot of state information along, but readability isn't as big of a concern since only you (or someone who will maintain your code and should understand the fundamentals of your module) have to care about calling that function.

Input from the keyboard in command line application

I swear to God.. the solution to this utterly basic problem eluded me for YEARS. It's SO simple.. but there is so much vague / bad information out there; hopefully I can save someone from some of the bottomless rabbit holes that I ended up in...

So then, lets's get a "string" from "the user" via "the console", via stdin, shall we?

[NSString.alloc initWithData:
[NSFileHandle.fileHandleWithStandardInput availableData]
                          encoding:NSUTF8StringEncoding];

if you want it WITHOUT the trailing newline, just add...

[ ... stringByTrimmingCharactersInSet:
                       NSCharacterSet.newlineCharacterSet];

Ta Da! ? ??e?

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

How to update a menu item shown in the ActionBar?

in my case: invalidateOptionsMenu just re-setted the text to the original one, but directly accessing the menu item and re-writing the desire text worked without problems:

if (mnuTopMenuActionBar_ != null) {
    MenuItem mnuPageIndex = mnuTopMenuActionBar_
        .findItem(R.id.menu_magazin_pageOfPage_text);

    if (mnuPageIndex != null) {
        if (getScreenOrientation() == 1) {
            mnuPageIndex.setTitle((i + 1) + " von " + pages);
        }
        else {
            mnuPageIndex.setTitle(
                (i + 1) + " + " + (i + 2) + " " + " von " + pages);
        }
        // invalidateOptionsMenu();
    }
}

due to the comment below, I was able to access the menu item via the following code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.magazine_swipe_activity, menu);
    mnuTopMenuActionBar_ = menu;
    return true;
}

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

How can I remove the top and right axis in matplotlib?

[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this

That ability was actually just added, and you need the Subversion version for it. You can see the example code here.

I am just updating to say that there's a better example online now. Still need the Subversion version though, there hasn't been a release with this yet.

[edit] Matplotlib 0.99.0 RC1 was just released, and includes this capability.

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How to get the Full file path from URI

The PathUtil method will be only working in below oreo and if it is oreo than it is likely to crash because in oreo we will not get the id but the entire path in data.getData() so all u need to do is create a file from uri and get its path from getPath() and split it.below is the working code:-

Uri uri = data.getData(); 
File file = new File(uri.getPath());//create path from uri
final String[] split = file.getPath().split(":");//split the path.
filePath = split[1];//assign it to a string(your choice).

The above code will work in oreo and if it is below oreo than PathUtil will work.Thanks!

String filePath=PathUtil.getPath(context,yourURI);

PathUtil.java

import android.annotation.SuppressLint; 
import android.content.ContentUris; 
import android.content.Context; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Build; 
import android.os.Environment; 
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.net.URISyntaxException;

/**
 * Created by Aki on 1/7/2017.
 */

public class PathUtil {
    /*
     * Gets the file path of the given Uri.
     */
    @SuppressLint("NewApi")
    public static String getPath(Context context, Uri uri) throws URISyntaxException {
        final boolean needToCheckUri = Build.VERSION.SDK_INT >= 19;
        String selection = null;
        String[] selectionArgs = null;
        // Uri is different in versions after KITKAT (Android 4.4), we need to
        // deal with different Uris.
        if (needToCheckUri && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{ split[1] };
            }
        }
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}

Plotting lines connecting points

You can just pass a list of the two points you want to connect to plt.plot. To make this easily expandable to as many points as you want, you could define a function like so.

import matplotlib.pyplot as plt

x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]

plt.plot(x,y, 'ro')

def connectpoints(x,y,p1,p2):
    x1, x2 = x[p1], x[p2]
    y1, y2 = y[p1], y[p2]
    plt.plot([x1,x2],[y1,y2],'k-')

connectpoints(x,y,0,1)
connectpoints(x,y,2,3)

plt.axis('equal')
plt.show()

enter image description here

Note, that function is a general function that can connect any two points in your list together.

To expand this to 2N points, assuming you always connect point i to point i+1, we can just put it in a for loop:

import numpy as np
for i in np.arange(0,len(x),2):
    connectpoints(x,y,i,i+1)

In that case of always connecting point i to point i+1, you could simply do:

for i in np.arange(0,len(x),2):
    plt.plot(x[i:i+2],y[i:i+2],'k-')

C pointer to array/array of pointers disambiguation

I think we can use the simple rule ..

example int * (*ptr)()[];
start from ptr 

" ptr is a pointer to " go towards right ..its ")" now go left its a "(" come out go right "()" so " to a function which takes no arguments " go left "and returns a pointer " go right "to an array" go left " of integers "

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

Go to the preview version of tomcat e.g. : tomcat 8.3 and copy catalina.jar file and paste into the existing tomcat which you have facing the issue

combining two data frames of different lengths

i had similar problem, i matched the entries in a particular column of two data sets and cbind only if it matched. For two data sets, data1 & data2, i am adding a column in data1 from data2 after comparing first column of both.

for(i in 1:nrow(data1){
  for( j in 1:nrow(data2){
    if (data1[i,1]==data2[j,1]) data1[i,3]<- data2[j,2]
  }
}

Remove ListView items in Android

At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.

private void add(final List<Track> trackList) {
    MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);

    list = (ListView) findViewById(R.id.my_list); // TODO

    list.setAdapter(bindingData);


    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {
            // ShowPlacePref(places, position);
            AlertDialog.Builder showPlace = new AlertDialog.Builder(
                    Favoriler.this);
            showPlace.setMessage("Remove from list?");
            showPlace.setPositiveButton("DELETE", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {    

                    trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
                    list.setAdapter(null); // THEN EMPTY YOUR ADAPTER

                    add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)

                }

            });
            showPlace.setNegativeButton("CANCEL", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            showPlace.show();
        }

    });

}

design a stack such that getMinimum( ) should be O(1)

I am posting the complete code here to find min and max in a given stack.

Time complexity will be O(1)..

package com.java.util.collection.advance.datastructure;

/**
 * 
 * @author vsinha
 *
 */
public abstract interface Stack<E> {

    /**
     * Placing a data item on the top of the stack is called pushing it
     * @param element
     * 
     */
    public abstract void push(E element);


    /**
     * Removing it from the top of the stack is called popping it
     * @return the top element
     */
    public abstract E pop();

    /**
     * Get it top element from the stack and it 
     * but the item is not removed from the stack, which remains unchanged
     * @return the top element
     */
    public abstract E peek();

    /**
     * Get the current size of the stack.
     * @return
     */
    public abstract int size();


    /**
     * Check whether stack is empty of not.
     * @return true if stack is empty, false if stack is not empty
     */
    public abstract boolean empty();



}



package com.java.util.collection.advance.datastructure;

@SuppressWarnings("hiding")
public abstract interface MinMaxStack<Integer> extends Stack<Integer> {

    public abstract int min();

    public abstract int max();

}


package com.java.util.collection.advance.datastructure;

import java.util.Arrays;

/**
 * 
 * @author vsinha
 *
 * @param <E>
 */
public class MyStack<E> implements Stack<E> {

    private E[] elements =null;
    private int size = 0;
    private int top = -1;
    private final static int DEFAULT_INTIAL_CAPACITY = 10;


    public MyStack(){
        // If you don't specify the size of stack. By default, Stack size will be 10
        this(DEFAULT_INTIAL_CAPACITY);
    }

    @SuppressWarnings("unchecked")
    public MyStack(int intialCapacity){
        if(intialCapacity <=0){
            throw new IllegalArgumentException("initial capacity can't be negative or zero");
        }
        // Can't create generic type array
        elements =(E[]) new Object[intialCapacity];
    }

    @Override
    public void push(E element) {
        ensureCapacity();
        elements[++top] = element;
        ++size;
    }

    @Override
    public E pop() {
        E element = null;
        if(!empty()) {
            element=elements[top];
            // Nullify the reference
            elements[top] =null;
            --top;
            --size;
        }
        return element;
    }

    @Override
    public E peek() {
        E element = null;
        if(!empty()) {
            element=elements[top];
        }
        return element;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean empty() {
        return size == 0;
    }

    /**
     * Increases the capacity of this <tt>Stack by double of its current length</tt> instance, 
     * if stack is full 
     */
    private void ensureCapacity() {
        if(size != elements.length) {
            // Don't do anything. Stack has space.
        } else{
            elements = Arrays.copyOf(elements, size *2);
        }
    }

    @Override
    public String toString() {
        return "MyStack [elements=" + Arrays.toString(elements) + ", size="
                + size + ", top=" + top + "]";
    }


}


package com.java.util.collection.advance.datastructure;

/**
 * Time complexity will be O(1) to find min and max in a given stack.
 * @author vsinha
 *
 */
public class MinMaxStackFinder extends MyStack<Integer> implements MinMaxStack<Integer> {

    private MyStack<Integer> minStack;

    private MyStack<Integer> maxStack;

    public MinMaxStackFinder (int intialCapacity){
        super(intialCapacity);
        minStack =new MyStack<Integer>();
        maxStack =new MyStack<Integer>();

    }
    public void push(Integer element) {
        // Current element is lesser or equal than min() value, Push the current element in min stack also.
        if(!minStack.empty()) {
            if(min() >= element) {
                minStack.push(element);
            }
        } else{
            minStack.push(element);
        }
        // Current element is greater or equal than max() value, Push the current element in max stack also.
        if(!maxStack.empty()) {
            if(max() <= element) {
                maxStack.push(element);
            }
        } else{
            maxStack.push(element);
        }
        super.push(element);
    }


    public Integer pop(){
        Integer curr = super.pop();
        if(curr !=null) {
            if(min() == curr) {
                minStack.pop();
            } 

            if(max() == curr){
                maxStack.pop();
            }
        }
        return curr;
    }


    @Override
    public int min() {
        return minStack.peek();
    }

    @Override
    public int max() {
        return maxStack.peek();
    }


    @Override
    public String toString() {
        return super.toString()+"\nMinMaxStackFinder [minStack=" + minStack + "\n maxStack="
                + maxStack + "]" ;
    }




}

// You can use the below program to execute it.

package com.java.util.collection.advance.datastructure;

import java.util.Random;

public class MinMaxStackFinderApp {

    public static void main(String[] args) {
        MinMaxStack<Integer> stack =new MinMaxStackFinder(10);
        Random random =new Random();
        for(int i =0; i< 10; i++){
            stack.push(random.nextInt(100));
        }
        System.out.println(stack);
        System.out.println("MAX :"+stack.max());
        System.out.println("MIN :"+stack.min());

        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();

        System.out.println(stack);
        System.out.println("MAX :"+stack.max());
        System.out.println("MIN :"+stack.min());
    }
}

Let me know if you are facing any issue

Thanks, Vikash

How to call Stored Procedures with EntityFramework?

Basically you just have to map the procedure to the entity using Stored Procedure Mapping.

Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.

Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

I was able to solve this in Eclipse Helios by right-clicking on the project, picking "Java Build Path", "Add Library...", "JRE System Library", "Workspace default JRE (jdk1.6.0_17)" and finally "Finish".

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

You need to change the bind-address parameter to 127.0.0.1 in the mysql config file (my.ini or my.cnf) or use the one that is defined there.

If that doesn't work you should check that the mysql service is actually running.

Create parameterized VIEW in SQL Server 2008

no. You can use UDF in which you can pass parameters.

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You can set your href to #! instead of #

For example,

<a href="#!">Link</a>

will not do any scrolling when clicked.

Beware! This will still add an entry to the browser's history when clicked, meaning that after clicking your link, the user's back button will not take them to the page they were previously on. For this reason, it's probably better to use the .preventDefault() approach, or to use both in combination.

Here is a Fiddle illustrating this (just scrunch your browser down until your get a scrollbar):
http://jsfiddle.net/9dEG7/


For the spec nerds - why this works:

This behaviour is specified in the HTML5 spec under the Navigating to a fragment identifier section. The reason that a link with a href of "#" causes the document to scroll to the top is that this behaviour is explicitly specified as the way to handle an empty fragment identifier:

2. If fragid is the empty string, then the indicated part of the document is the top of the document

Using a href of "#!" instead works simply because it avoids this rule. There's nothing magic about the exclamation mark - it just makes a convenient fragment identifier because it's noticeably different to a typical fragid and unlikely to ever match the id or name of an element on your page. Indeed, we could put almost anything after the hash; the only fragids that won't suffice are the empty string, the word 'top', or strings that match name or id attributes of elements on the page.

More exactly, we just need a fragment identifier that will cause us to fall through to step 8 in the following algorithm for determining the indicated part of the document from the fragid:

  1. Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting parsed URL.

  2. If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.

  3. Let fragid bytes be the result of percent-decoding fragid.

  4. Let decoded fragid be the result of applying the UTF-8 decoder algorithm to fragid bytes. If the UTF-8 decoder emits a decoder error, abort the decoder and instead jump to the step labeled no decoded fragid.

  5. If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  6. No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  7. If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.

  8. Otherwise, there is no indicated part of the document.

As long as we hit step 8 and there is no indicated part of the document, the following rule comes into play:

If there is no indicated part ... then the user agent must do nothing.

which is why the browser doesn't scroll.

get client time zone from browser

Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api

_x000D_
_x000D_
fetch("https://worldtimeapi.org/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.timezone,data.datetime,data.dst));
_x000D_
_x000D_
_x000D_

How to describe "object" arguments in jsdoc?

By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.

For objects with a known set of properties (Variant A)

/**
 * @param {{a: number, b: string, c}} myObj description
 */

This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property. It can be used for @returns as well.

For objects with a known set of properties (Variant B)

Very useful is the parameters with properties syntax:

/**
 * @param {Object} myObj description
 * @param {number} myObj.a description
 * @param {string} myObj.b description
 * @param {} myObj.c description
 */

This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property. This can not be used for @returns.

For objects that will be used at more than one point in source

In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param or @returns or other JSDoc tags that can make use of a type.

/**
 * @typedef {Object} Person
 * @property {string} name how the person is called
 * @property {number} age how many years the person lived
 */

You can then use this in a @param tag:

/**
 * @param {Person} p - Description of p
 */

Or in a @returns:

/**
 * @returns {Person} Description
 */

For objects whose values are all the same type

/**
 * @param {Object.<string, number>} dict
 */

The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type. This syntax can be used for @returns as well.

Resources

Useful information about documenting types can be found here:

https://jsdoc.app/tags-type.html

PS:

to document an optional value you can use []:

/**
 * @param {number} [opt_number] this number is optional
 */

or:

/**
 * @param {number|undefined} opt_number this number is optional
 */

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

How to set auto increment primary key in PostgreSQL?

Steps to do it on PgAdmin:

  • CREATE SEQUENCE sequnence_title START 1; // if table exist last id
  • Add this sequense to the primary key, table - properties - columns - column_id(primary key) edit - Constraints - Add nextval('sequnence_title'::regclass) to the field default.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

In my case I have to use something like <username>@<domain> to successfully login.

sample_user@sample_domain

Nesting await in Parallel.ForEach

svick's answer is (as usual) excellent.

However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async-compatible queue.

In your case, a simpler solution is to just use the async-style parallelism:

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

var customerTasks = ids.Select(i =>
  {
    ICustomerRepo repo = new CustomerRepo();
    return repo.GetCustomer(i);
  });
var customers = await Task.WhenAll(customerTasks);

foreach (var customer in customers)
{
  Console.WriteLine(customer.ID);
}

Console.ReadKey();

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

Split string into array of characters?

the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....

Private Function characterArray(ByVal my_string As String) As String()
  'create a temporary string to store a new string of the same characters with spaces
  Dim tempString As String = ""
  'cycle through the characters and rebuild my_string as a string with spaces 
  'and assign the result to tempString.  
  For Each c In my_string
     tempString &= c & " "
  Next
  'return return tempString as a character array.  
  Return tempString.Split()
End Function

How to compare strings in an "if" statement?

You're looking for the function strcmp, or strncmp from string.h.

Since strings are just arrays, you need to compare each character, so this function will do that for you:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}

Further reading: strcmp at cplusplus.com

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

How to get exact browser name and version?

Use 51Degrees.com device detection solution to detect browser name, vendor and version.

First, follow the 4-step guide to incorporate device detector in to your project. When I say incorporate I mean download archive with PHP code and database file, extract them and include 2 files. That's all there is to do to incorporate.

Once that's done you can use the following properties to get browser information:
$_51d['BrowserName'] - Gives you the name of the browser (Safari, Molto, Motorola, MStarBrowser etc).
$_51d['BrowserVendor'] - Gives you the company who created browser.
$_51d['BrowserVersion'] - Version number of the browser

Utility of HTTP header "Content-Type: application/force-download" for mobile?

Content-Type: application/force-download means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".

Use the correct mime type for whatever media you are using (e.g. audio/mpeg for mp3).

Use the Content-Disposition: attachment; etc etc header if you want to encourage the client to download it instead of following the default behaviour.

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

SQL WHERE condition is not equal to?

Best solution is to use

DELETE FROM table WHERE id NOT IN ( 2 )

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

jQuery bind/unbind 'scroll' event on $(window)

Very old question, but in case someone else stumbles across it, I would recommend trying:

$j("html, body").stop(true, true).animate({
        scrollTop: $j('#main').offset().top 
}, 300);

Rename computer and join to domain in one step with PowerShell

Rename-Computer was removed from CTP3 because there are a lot of things done when renaming a computer and MS either didn't want to recreate that process or couldn't include all of the necessary bits. I think Jefferey Snover said to just use netdom.exe instead, as that is the best practice for renaming a computer on the command-line. Not the answer you were looking for, but should point you in the right direction

Setting up Vim for Python

There is a bundled collection of Vim plugins for Python development: http://www.vim.org/scripts/script.php?script_id=3770

C# delete a folder and all files and folders within that folder

public void Empty(System.IO.DirectoryInfo directory)
{
    try
    {
        logger.DebugFormat("Empty directory {0}", directory.FullName);
        foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
        foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
    }
    catch (Exception ex)
    {
        ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));

        throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
    }
}

What is the best way to implement constants in Java?

I prefer to use getters rather than constants. Those getters might return constant values, e.g. public int getMaxConnections() {return 10;}, but anything that needs the constant will go through a getter.

One benefit is that if your program outgrows the constant--you find that it needs to be configurable--you can just change how the getter returns the constant.

The other benefit is that in order to modify the constant you don't have to recompile everything that uses it. When you reference a static final field, the value of that constant is compiled into any bytecode that references it.

Get PHP class property by string

Here is my attempt. It has some common 'stupidity' checks built in, making sure you don't try to set or get a member which isn't available.

You could move those 'property_exists' checks to __set and __get respectively and call them directly within magic().

<?php

class Foo {
    public $Name;

    public function magic($member, $value = NULL) {
        if ($value != NULL) {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            $this->$member = $value;
        } else {
            if (!property_exists($this, $member)) {
                trigger_error('Undefined property via magic(): ' .
                    $member, E_USER_ERROR);
                return NULL;
            }
            return $this->$member;
        }
    }
};

$f = new Foo();

$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";

// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";

?>

What are the most-used vim commands/keypresses?

I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?

I do.

In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.

That's the right way to do it. Start with basic commands and then pick up ones that improve your productivity. I like following this blog for tips on how to improve my productivity with vim.

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

Self Join to get employee manager name

CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName, 
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM   tblEmployeeDetails e1
       JOIN tblEmployeeDetails e2
       ON e1.emp_mgr_id = e2.emp_id

EDIT: Left Join will work if emp_mgr_id is null.

CREATE VIEW AS 
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,  
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName 
FROM   tblEmployeeDetails e1 
       LEFT JOIN tblEmployeeDetails e2 
       ON e1.emp_mgr_id = e2.emp_id

Linux command (like cat) to read a specified quantity of characters

head:

Name

head - output the first part of files

Synopsis

head [OPTION]... [FILE]...

Description

Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file

Add an image in a WPF button

I also had the same issue. I've fixed it by using the following code.

        <Button Width="30" Margin="0,5" HorizontalAlignment="Stretch"  Click="OnSearch" >
            <DockPanel>
                <Image Source="../Resources/Back.jpg"/>
            </DockPanel>
        </Button>

Note: Make sure the build action of the image in the property window, should be Resource.

enter image description here

How to hide the Google Invisible reCAPTCHA badge

I have tested all approaches and:

WARNING: display: none DISABLES the spam checking!

visibility: hidden and opacity: 0 do NOT disable the spam checking.

Code to use:

.grecaptcha-badge { 
    visibility: hidden;
}

When you hide the badge icon, Google wants you to reference their service on your form by adding this:

<small>This site is protected by reCAPTCHA and the Google 
    <a href="https://policies.google.com/privacy">Privacy Policy</a> and
    <a href="https://policies.google.com/terms">Terms of Service</a> apply.
</small>

Example result

concatenate char array in C

I have a char array:

char* name = "hello";

No, you have a character pointer to a string literal. In many usages you could add the const modifier, depending on whether you are more interested in what name points to, or the string value, "hello". You shouldn't attempt to modify the literal ("hello"), because bad things can happen.

The major thing to convey is that C does not have a proper (or first-class) string type. "Strings" are typically arrays of chars (characters) with a terminating null ('\0' or decimal 0) character to signify end of a string, or pointers to arrays of characters.

I would suggest reading Character Arrays, section 1.9 in The C Programming Language (page 28 second edition). I strongly recommend reading this small book ( <300 pages), in order to learn C.

Further to your question, sections 6 - Arrays and Pointers and section 8 - Characters and Strings of the C FAQ might help. Question 6.5, and 8.4 might be good places to start.

I hope that helps you to understand why your excerpt doesn't work. Others have outlined what changes are needed to make it work. Basically you need an char array (an array of characters) big enough to store the entire string with a terminating (ending) '\0' character. Then you can use the standard C library function strcpy (or better yet strncpy) to copy the "Hello" into it, and then you want to concatenate using the standard C library strcat (or better yet strncat) function. You will want to include the string.h header file to declare the functions declarations.

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

int main( int argc, char *argv[] )
{
    char filename[128];
    char* name = "hello";
    char* extension = ".txt";

    if (sizeof(filename) < strlen(name) + 1 ) { /* +1 is for null character */
        fprintf(stderr, "Name '%s' is too long\n", name);
        return EXIT_FAILURE;
    }
    strncpy(filename, name, sizeof(filename));

    if (sizeof(filename) < (strlen(filename) + strlen(extension) + 1) ) {
        fprintf(stderr, "Final size of filename is too long!\n");
        return EXIT_FAILURE;
    }
    strncat(filename, extension, (sizeof(filename) - strlen(filename)) );
    printf("Filename is %s\n", filename);

    return EXIT_SUCCESS;
}

Golang append an item to a slice

Here is a nice implementation of append for slices. I guess its similar to what is going on under the hood:

package main

import "fmt"

func main() {
    slice1 := []int{0, 1, 2, 3, 4}
    slice2 := []int{55, 66, 77}
    fmt.Println(slice1)
    slice1 = Append(slice1, slice2...) // The '...' is essential!
    fmt.Println(slice1)
}

// Append ...
func Append(slice []int, items ...int) []int {
    for _, item := range items {
        slice = Extend(slice, item)
    }
    return slice
}

// Extend ...
func Extend(slice []int, element int) []int {
    n := len(slice)
    if n == cap(slice) {
        // Slice is full; must grow.
        // We double its size and add 1, so if the size is zero we still grow.
        newSlice := make([]int, len(slice), 2*len(slice)+1)
        copy(newSlice, slice)
        slice = newSlice
    }
    slice = slice[0 : n+1]
    slice[n] = element
    return slice
}

Validating URL in Java

There is a way to perform URL validation in strict accordance to standards in Java without resorting to third-party libraries:

boolean isValidURL(String url) {
  try {
    new URI(url).parseServerAuthority();
    return true;
  } catch (URISyntaxException e) {
    return false;
  }
}

The constructor of URI checks that url is a valid URI, and the call to parseServerAuthority ensures that it is a URL (absolute or relative) and not a URN.

Changing Jenkins build number

can be done with the plugin: https://wiki.jenkins-ci.org/display/JENKINS/Next+Build+Number+Plugin

more info: http://www.alexlea.me/2010/10/howto-set-hudson-next-build-number.html

if you don't like the plugin:

If you want to change build number via nextBuildNumber file you should "Reload Configuration from Disk" from "Manage Jenkins" page.

How to fix "unable to write 'random state' " in openssl

just enter this line in the command line :

set RANDFILE=.rnd

Interview Question: Merge two sorted singly linked lists without creating new nodes

private static Node mergeLists(Node L1, Node L2) {

    Node P1 = L1.val < L2.val ? L1 : L2;
    Node P2 = L1.val < L2.val ? L2 : L1;
    Node BigListHead = P1;
    Node tempNode = null;

    while (P1 != null && P2 != null) {
        if (P1.next != null && P1.next.val >P2.val) {
        tempNode = P1.next;
        P1.next = P2;
        P1 = P2;
        P2 = tempNode;
        } else if(P1.next != null) 
        P1 = P1.next;
        else {
        P1.next = P2;
        break;
        }
    }

    return BigListHead;
}

What is the unix command to see how much disk space there is and how much is remaining?

If you want to see how much space each folder ocuppes:

du -sh *

  • s – summarize
  • h – human readable
  • * – list of folders

Why Doesn't C# Allow Static Methods to Implement an Interface?

Assuming you are asking why you can't do this:

public interface IFoo {
    void Bar();
}

public class Foo: IFoo {
    public static void Bar() {}
}

This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.


To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.

public class Animal: IListItem {
    /* Can be tough to come up with a different, yet meaningful name!
     * A different casing convention, like Java has, would help here.
     */
    public const string AnimalScreenName = "Animal";
    public string ScreenName(){ return AnimalScreenName; }
}

For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.

cout is not a member of std

Also remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around

#include <iostream>
#include "stdafx.h"

unable to install pg gem

gem install pg -- --with-pg-config=/usr/pgsql-9.1/bin/pg_config

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

'sudo gem install' or 'gem install' and gem locations

Contrary to all the other posts I suggest NOT using sudo when installing gems.

Instead I recommend you install RVM and start a happy life with portable gem homes and different version of Ruby all living under one roof.

For the uninitiated, from the documentation:

RVM is a command line tool which allows us to easily install, manage and work with multiple ruby environments and sets of gems.

The reason why installing gems with sudo is worse than just gem install is because it installs the gems for ALL USERS as root. This might be fine if you're the only person using the machine, but if you're not it can cause weirdness.

If you decide you want to blow away all your gems and start again it's much easier, and safer, to do so as a non-root user.

If you decide you want to use RVM then using sudo will cause all kinds of weirdness because each Ruby version you install through RVM has its own GEM_HOME.

Also, it's nice if you can make your development environment as close to your production environment as possible, and in production you'll most likely install gems as a non-root user.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

XML Schema (XSD) validation tool?

xmlstarlet is a command-line tool which will do this and more:

$ xmlstarlet val --help
XMLStarlet Toolkit: Validate XML document(s)
Usage: xmlstarlet val <options> [ <xml-file-or-uri> ... ]
where <options>
  -w or --well-formed        - validate well-formedness only (default)
  -d or --dtd <dtd-file>     - validate against DTD
  -s or --xsd <xsd-file>     - validate against XSD schema
  -E or --embed              - validate using embedded DTD
  -r or --relaxng <rng-file> - validate against Relax-NG schema
  -e or --err                - print verbose error messages on stderr
  -b or --list-bad           - list only files which do not validate
  -g or --list-good          - list only files which validate
  -q or --quiet              - do not list files (return result code only)

NOTE: XML Schemas are not fully supported yet due to its incomplete
      support in libxml2 (see http://xmlsoft.org)

XMLStarlet is a command line toolkit to query/edit/check/transform
XML documents (for more information see http://xmlstar.sourceforge.net/)

Usage in your case would be along the lines of:

xmlstarlet val --xsd your_schema.xsd your_file.xml

How can I create a product key for my C# application?

There are some tools and API's available for it. However, I do not think you'll find one for free ;)

There is for instance the OLicense suite: http://www.olicense.de/index.php?lang=en

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

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

IllegalArgumentException or NullPointerException for a null parameter?

NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.

IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.

Windows- Pyinstaller Error "failed to execute script " When App Clicked

I was getting this error for a different reason than those listed here, and could not find the solution easily, so I figured I would post here.

Hopefully this is helpful to someone.

My issue was with referencing files in the program. It was not able to find the file listed, because when I was coding it I had the file I wanted to reference in the top level directory and just called

"my_file.png"

when I was calling the files.

pyinstaller did not like this, because even when I was running it from the same folder, it was expecting a full path:

"C:\Files\my_file.png"

Once I changed all of my paths, to the full version of their path, it fixed this issue.

Does Hibernate create tables in the database automatically

add following property in your hibernate.cfg.xml file

<property name="hibernate.hbm2ddl.auto">update</property>

BTW, in your Entity class, you must define your @Id filed like this:

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private long id;

if you use the following definition, it maybe not work:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;

Prevent div from moving while resizing the page

I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.

Or, you can set a min-width on elements like header, navigation, content etc.

How to overcome "'aclocal-1.15' is missing on your system" warning?

2018, yet another solution ...

https://github.com/apereo/mod_auth_cas/issues/97

in some cases simply running

$ autoreconf -f -i

and nothing else .... solves the problem.

You do that in the directory /pcre2-10.30 .

What a nightmare.

(This usually did not solve the problem in 2017, but now usually does seem to solve the problem - they fixed something. Also, it seems your Dockerfile should now usually start with "FROM ibmcom/swift-ubuntu" ; previously you had to give a certain version/dev-build to make it work.)

How do I set up NSZombieEnabled in Xcode 4?

In Xcode > 4.3:

You click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column.

Good Luck !!!

How can I find the number of elements in an array?

The question is simple: given a C++ array (e.g. x as in int x[10]), how would you get the number of elements in it?

An obvious solution is the following macro (definition 1):

#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )

I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have

int * p;

then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).

This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write

class IntArray {
private:
    int * p;
    size_t size;
public:
    int & operator [] ( size_t i );
} x;

then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p. Therefore you won’t get a correct answer by countof( x ).

So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.

What is a better option?

Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.

Some beginners may try this (definition 2):

template <typename T, size_t N>
size_t countof( T array[N] )
{
   return N;
}

They figure, this template function will accept an array of N elements and return N.

Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:

template <typename T, size_t N>
size_t countof( T * array )
{
    return N;
}

It now becomes obvious that the function body has no way of knowing what N is.

However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):

template <typename T, size_t N>
size_t countof( T (&array)[N] )
{
    return N;
}

This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:

int x[10];

int y[ 2*countof(x) ]; // twice as big as x

Can we do anything about it?

Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.

To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.

The implementation of this is:

template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];

#define countof( array ) (sizeof( _ArraySizeHelper( array ) ))

Admittedly, the syntax looks awful. Indeed, some explanation is necessary.

First, the top-level stuff

char ( &_ArraySizeHelper( ... ))[N];

says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.

Next, the function parameter is

T (&array)[N]

which is a reference to a T array of N elements.

Finally, countof is defined as the size of the result of the function _ArraySizeHelper. Note we don’t even need to define _ArraySizeHelper(), -- a declaration is enough.

With this new definition,

int x[10];

int y[ 2*countof(x) ]; // twice as big as x

becomes valid, just as we desire.

Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.

I don’t have a better solution. If you know one, please let me know.

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

PHP compare two arrays and get the matched values not the difference

Simple, use array_intersect() instead:

$result = array_intersect($array1, $array2);

Single selection in RecyclerView

            public class GetStudentAdapter extends 
            RecyclerView.Adapter<GetStudentAdapter.MyViewHolder> {

            private List<GetStudentModel> getStudentList;
            Context context;
            RecyclerView recyclerView;

            public class MyViewHolder extends RecyclerView.ViewHolder {
                TextView textStudentName;
                RadioButton rbSelect;

                public MyViewHolder(View view) {
                    super(view);
                    textStudentName = (TextView) view.findViewById(R.id.textStudentName);
                    rbSelect = (RadioButton) view.findViewById(R.id.rbSelect);
                }


            }

            public GetStudentAdapter(Context context, RecyclerView recyclerView, List<GetStudentModel> getStudentList) {
                this.getStudentList = getStudentList;
                this.recyclerView = recyclerView;
                this.context = context;
            }

            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.select_student_list_item, parent, false);
                return new MyViewHolder(itemView);
            }

            @Override
            public void onBindViewHolder(final MyViewHolder holder, final int position) {
                holder.textStudentName.setText(getStudentList.get(position).getName());
                holder.rbSelect.setChecked(getStudentList.get(position).isSelected());
                holder.rbSelect.setTag(position); // This line is important.
                holder.rbSelect.setOnClickListener(onStateChangedListener(holder.rbSelect, position));

            }

            @Override
            public int getItemCount() {
                return getStudentList.size();
            }
            private View.OnClickListener onStateChangedListener(final RadioButton checkBox, final int position) {
                return new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (checkBox.isChecked()) {
                            for (int i = 0; i < getStudentList.size(); i++) {

                                getStudentList.get(i).setSelected(false);

                            }
                            getStudentList.get(position).setSelected(checkBox.isChecked());

                            notifyDataSetChanged();
                        } else {

                        }

                    }
                };
            }

        }

Can you get the number of lines of code from a GitHub repository?

A shell script, cloc-git

You can use this shell script to count the number of lines in a remote Git repository with one command:

#!/usr/bin/env bash
git clone --depth 1 "$1" temp-linecount-repo &&
  printf "('temp-linecount-repo' will be deleted automatically)\n\n\n" &&
  cloc temp-linecount-repo &&
  rm -rf temp-linecount-repo

Installation

This script requires CLOC (“Count Lines of Code”) to be installed. cloc can probably be installed with your package manager – for example, brew install cloc with Homebrew. There is also a docker image published under mribeiro/cloc.

You can install the script by saving its code to a file cloc-git, running chmod +x cloc-git, and then moving the file to a folder in your $PATH such as /usr/local/bin.

Usage

The script takes one argument, which is any URL that git clone will accept. Examples are https://github.com/evalEmpire/perl5i.git (HTTPS) or [email protected]:evalEmpire/perl5i.git (SSH). You can get this URL from any GitHub project page by clicking “Clone or download”.

Example output:

$ cloc-git https://github.com/evalEmpire/perl5i.git
Cloning into 'temp-linecount-repo'...
remote: Counting objects: 200, done.
remote: Compressing objects: 100% (182/182), done.
remote: Total 200 (delta 13), reused 158 (delta 9), pack-reused 0
Receiving objects: 100% (200/200), 296.52 KiB | 110.00 KiB/s, done.
Resolving deltas: 100% (13/13), done.
Checking connectivity... done.
('temp-linecount-repo' will be deleted automatically)


     171 text files.
     166 unique files.                                          
      17 files ignored.

http://cloc.sourceforge.net v 1.62  T=1.13 s (134.1 files/s, 9764.6 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Perl                           149           2795           1425           6382
JSON                             1              0              0            270
YAML                             2              0              0            198
-------------------------------------------------------------------------------
SUM:                           152           2795           1425           6850
-------------------------------------------------------------------------------

Alternatives

Run the commands manually

If you don’t want to bother saving and installing the shell script, you can run the commands manually. An example:

$ git clone --depth 1 https://github.com/evalEmpire/perl5i.git
$ cloc perl5i
$ rm -rf perl5i

Linguist

If you want the results to match GitHub’s language percentages exactly, you can try installing Linguist instead of CLOC. According to its README, you need to gem install linguist and then run linguist. I couldn’t get it to work (issue #2223).

Footnotes for tables in LaTeX

What @dmckee said.

It's not difficult to write your own bespoke footnote-queuing code. What you need to do is:

  1. Write code to queue Latex code — like a hook in emacs: very standard technique, if not every Latex hacker can actually do this right;
  2. Temporarily redefine \footnote to add a footnote macro to your queue;
  3. Ensure that the hook gets called when the table/figure exits and we return to regular vertical mode.

If this is interesting, I show some code that does this.

AWK to print field $2 first, then field $1

Maybe your file contains CRLF terminator. Every lines followed by \r\n.

awk recognizes the $2 actually $2\r. The \r means goto the start of the line.

{print $2\r$1} will print $2 first, then return to the head, then print $1. So the field 2 is overlaid by the field 1.

How to make shadow on border-bottom?

funny, that in the most answer you create a box with the text (or object), instead of it create the text (or object) div and under that a box with 100% width (or at least what it should) and with height what equal with your "border" px... So, i think this is the most simple and perfect answer:

<h3>Your Text</h3><div class="border-shadow"></div>

and the css:

    .shadow {
        width:100%;
        height:1px; // = "border height (without the shadow)!"
        background:#000; // = "border color!"
        -webkit-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        -moz-box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"
        box-shadow: 0px 1px 8px 1px rgba(0,0,0,1); // rbg = "border shadow color!"

}

Here you can experiment with the radius, etc. easy: https://www.cssmatic.com/box-shadow

jquery ui Dialog: cannot call methods on dialog prior to initialization

I got this error when I only updated the jquery library without updating the jqueryui library in parallel. I was using jquery 1.8.3 with jqueryui 1.9.0. However, when I updated jquery 1.8.3 to 1.9.1 I got the above error. When I commented out the offending .close method lines, it then threw an error about not finding .browser in the jquery library which was deprecated in jquery 1.8.3 and removed from jquery 1.9.1. So bascially, the jquery 1.9.1 library was not compatible with the jquery ui 1.9.0 library despite the jquery ui download page saying it works with jquery 1.6+. Essentially, there are unreported bugs when trying to use differing versions of the two. If you use the jquery version that comes bundled with the jqueryui download, I'm sure you'll be fine, but it's when you start using different versions that you off the beaten path and get errors like this. So, in summary, this error is from mis-matched versions (in my case anyway).

best way to get the key of a key/value javascript object

You can access each key individually without iterating as in:

var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second

What are Covering Indexes and Covered Queries in SQL Server?

A covering query is on where all the predicates can be matched using the indices on the underlying tables.

This is the first step towards improving the performance of the sql under consideration.

Save matplotlib file to a directory

The simplest way to do this is as follows:


save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)

The image is going to be saved in the save_results_to directory with name image.png

How to find the difference in days between two dates?

Even if you don't have GNU date, you'll probably have Perl installed:

use Time::Local;
sub to_epoch {
  my ($t) = @_; 
  my ($y, $d, $m) = ($t =~ /(\d{4})-(\d{2})-(\d{2})/);
  return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
}
sub diff_days {
  my ($t1, $t2) = @_; 
  return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
}
print diff_days("2002-20-10", "2003-22-11"), "\n";

This returns 398.041666666667 -- 398 days and one hour due to daylight savings.


The question came back up on my feed. Here's a more concise method using a Perl bundled module

days=$(perl -MDateTime -le '
    sub parse_date { 
        @f = split /-/, shift;
        return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]); 
    }
    print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
' $A $B)
echo $days   # => 398

How to make image hover in css?

Hi you should give parent position relative and child absolute and give to height or width to absolute class as like this

Css

  .nkhome{
    margin-left:260px;
    width:59px;
    height:59px;
    margin-top:170px;
    position:relative;
    z-index:0;
}
.nkhome a:hover img{
    opacity:0.0;
}
.nkhome a:hover{
  background:url('http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg');
    width:100px;
    height:100px;
    position:absolute;
    top:0;
    z-index:1;

}

HTML

 <div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" /></a>
    </div>
?

Live demo http://jsfiddle.net/t5FEX/7/


or this

<div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" onmouseover="this.src='http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg'" 
            onmouseout="this.src='http://dummyimage.com/100/000/fff.jpg'"
            /></a>
    </div>?

Live demo http://jsfiddle.net/t5FEX/9/

Change color of PNG image via CSS?

I've been able to do this using SVG filter. You can write a filter that multiplies the color of source image with the color you want to change to. In the code snippet below, flood-color is the color we want to change image color to (which is Red in this case.) feComposite tells the filter how we're processing the color. The formula for feComposite with arithmetic is (k1*i1*i2 + k2*i1 + k3*i2 + k4) where i1 and i2 are input colors for in/in2 accordingly. So specifying only k1=1 means it will do just i1*i2, which means multiplying both input colors together.

Note: This only works with HTML5 since this is using inline SVG. But I think you might be able to make this work with older browser by putting SVG in a separate file. I haven't tried that approach yet.

Here's the snippet:

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="60" height="90" style="float:left">_x000D_
  <defs>_x000D_
    <filter id="colorMask1">_x000D_
      <feFlood flood-color="#ff0000" result="flood" />_x000D_
      <feComposite in="SourceGraphic" in2="flood" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image width="100%" height="100%" xlink:href="http://i.stack.imgur.com/OyP0g.jpg" filter="url(#colorMask1)" />_x000D_
</svg>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="60" height="90" style="float:left">_x000D_
  <defs>_x000D_
    <filter id="colorMask2">_x000D_
      <feFlood flood-color="#00ff00" result="flood" />_x000D_
      <feComposite in="SourceGraphic" in2="flood" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image width="100%" height="100%" xlink:href="http://i.stack.imgur.com/OyP0g.jpg" filter="url(#colorMask2)" />_x000D_
</svg>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="60" height="90" style="float:left">_x000D_
  <defs>_x000D_
    <filter id="colorMask3">_x000D_
      <feFlood flood-color="#0000ff" result="flood" />_x000D_
      <feComposite in="SourceGraphic" in2="flood" operator="arithmetic" k1="1" k2="0" k3="0" k4="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image width="100%" height="100%" xlink:href="http://i.stack.imgur.com/OyP0g.jpg" filter="url(#colorMask3)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

mysql data directory location

If you are using macOS {mine 'High Sierra'} and Installed XAMPP

You can find mysql data files;

Go to : /Applications/XAMPP/xamppfiles/var/mysql/

Access item in a list of lists

List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num

mysql: see all open connections to a given database?

You can invoke MySQL show status command

show status like 'Conn%';

For more info read Show open database connections

frequent issues arising in android view, Error parsing XML: unbound prefix

As you mention, you need to specify the right namespace. You also see this error with an incorrect namespace.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="10dip">

will not work.

Change:

xmlns="http://schemas.android.com/apk/res/android"

to

xmlns:android="http://schemas.android.com/apk/res/android"

The error message is referring to everything that starts "android:" as the XML does not know what the "android:" namespace is.

xmlns:android defines it.

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

Combine or merge JSON on node.js without jQuery

The below code will help you to merge two JSON object which has nested objects.

function mergeJSON(source1,source2){
    /*
     * Properties from the Souce1 object will be copied to Source2 Object.
     * Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
     * */
    var mergedJSON = Object.create(source2);// Copying Source2 to a new Object

    for (var attrname in source1) {
        if(mergedJSON.hasOwnProperty(attrname)) {
          if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
              /*
               * Recursive call if the property is an object,
               * Iterate the object and set all properties of the inner object.
              */
              mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
          } 

        } else {//else copy the property from source1
            mergedJSON[attrname] = source1[attrname];

        }
      }

      return mergedJSON;
}

"Fatal error: Unable to find local grunt." when running "grunt" command

All is explained quite nicely on gruntjs.com.

Note that installing grunt-cli does not install the grunt task runner! The job of the grunt CLI is simple: run the version of grunt which has been installed next to a Gruntfile. This allows multiple versions of grunt to be installed on the same machine simultaneously.

So in your project folder, you will need to install (preferably) the latest grunt version:

npm install grunt --save-dev

Option --save-dev will add grunt as a dev-dependency to your package.json. This makes it easy to reinstall dependencies.

How to read user input into a variable in Bash?

Use read -p:

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

If you like to confirm:

read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

You should also quote your variables to prevent pathname expansion and word splitting with spaces:

# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

Difference between MEAN.js and MEAN.io

First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.

It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".

Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean

They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.

Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.

In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.

The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.

The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.

According to Linnovate's website:

Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.

From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.

Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.

In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two possible reasons 1. If you are using HttpClient in your service you need to import HttpClientModule in your module file and mention it in the imports array.

import { HttpClientModule } from '@angular/common/http';
  1. If you are using normal Http in your services you need to import HttpModule in your module file and mention it in the imports array.

    import { HttpModule } from '@angular/http'

By default, this is not available in the angular then you need to install @angular/http

If you wish you can use both HttpClientModule and HttpModule in your project.

How do you determine what technology a website is built on?

In Linux/OSX I often use simple command curl -sI www.site.com

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

Regex to test if string begins with http:// or https://

^ for start of the string pattern,

? for allowing 0 or 1 time repeat. ie., s? s can exist 1 time or no need to exist at all.

/ is a special character in regex so it needs to be escaped by a backslash \/

/^https?:\/\//.test('https://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('http://www.bbc.co.uk/sport/cricket'); // true

/^https?:\/\//.test('ftp://www.bbc.co.uk/sport/cricket'); // false