Programs & Examples On #Netbeans6.1

It is the version 6.1 of Netbeans IDE for java application development.

How to upgrade docker container after its image changed

Make sure you are using volumes for all the persistent data (configuration, logs, or application data) which you store on the containers related to the state of the processes inside that container. Update your Dockerfile and rebuild the image with the changes you wanted, and restart the containers with your volumes mounted at their appropriate place.

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

Pandas every nth row

I'd use iloc, which takes a row/column slice, both based on integer position and following normal python syntax. If you want every 5th row:

df.iloc[::5, :]

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

php - How do I fix this illegal offset type error

Use trim($source) before $s[$source].

Sleep function in C++

Recently I was learning about chrono library and thought of implementing a sleep function on my own. Here is the code,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

We can use it with any std::chrono::duration type (By default it takes std::chrono::seconds as argument). For example,

#include <cmath>
#include <chrono>

template <typename rep = std::chrono::seconds::rep, 
          typename period = std::chrono::seconds::period>
void sleep(std::chrono::duration<rep, period> sec)
{
    using sleep_duration = std::chrono::duration<long double, std::nano>;

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

    long double elapsed_time = 
    std::chrono::duration_cast<sleep_duration>(end - start).count();

    long double sleep_time = 
    std::chrono::duration_cast<sleep_duration>(sec).count();

    while (std::isgreater(sleep_time, elapsed_time)) {
        end = std::chrono::steady_clock::now();
        elapsed_time = std::chrono::duration_cast<sleep_duration>(end - start).count(); 
    }
}

using namespace std::chrono_literals;
int main (void) {
    std::chrono::steady_clock::time_point start1 = std::chrono::steady_clock::now();
    
    sleep(5s);  // sleep for 5 seconds
    
    std::chrono::steady_clock::time_point end1 = std::chrono::steady_clock::now();
    
    std::cout << std::setprecision(9) << std::fixed;
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::seconds>(end1-start1).count() << "s\n";
    
    std::chrono::steady_clock::time_point start2 = std::chrono::steady_clock::now();

    sleep(500000ns);  // sleep for 500000 nano seconds/500 micro seconds
    // same as writing: sleep(500us)
    
    std::chrono::steady_clock::time_point end2 = std::chrono::steady_clock::now();
    
    std::cout << "Elapsed time was: " << std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count() << "us\n";
    return 0;
}

For more information, visit https://en.cppreference.com/w/cpp/header/chrono and see this cppcon talk of Howard Hinnant, https://www.youtube.com/watch?v=P32hvk8b13M. He has two more talks on chrono library. And you can always use the library function, std::this_thread::sleep_for

Note: Outputs may not be accurate. So, don't expect it to give exact timings.

Access is denied when attaching a database

A SQL2005 database can be attached in this way in Windows 7:

start menu >
 all program >
  Microsoft sql server 2005 >
   sql server management studio >
    right click >
     run as administrator >
      click ok

And then attached database successfully completed.

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

Best way to parse RSS/Atom feeds with PHP

The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.

NSArray + remove item from array

Made a category like mxcl, but this is slightly faster.

My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

- (NSArray *)prefix_arrayByRemovingObject:(id)object 
{
    if (!object) {
        return self;
    }

    NSUInteger indexOfObject = [self indexOfObject:object];
    NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
    NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
    NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];

    return newArray;
}

Select records from today, this week, this month php mysql

Well, this solution will help you select only current month, current week and only today

SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;

For Weekly added posts:

WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())

For Monthly added posts:

MONTH(addedon_gm) = MONTH(NOW())

For Yearly added posts:

YEAR(addedon_gm) = YEAR(NOW())

you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.

declaring a priority_queue in c++ with a custom comparator

In case this helps anyone :

static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);

Get the date (a day before current time) in Bash

Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

I find out I can get the previous date with little trick on timezone.

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

Remove an entire column from a data.frame in R

The posted answers are very good when working with data.frames. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory errors. Package data.table helps address this problem with the := operator:

library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
     b c
[1,] 1 1

I should put together a bigger example to show the differences. I'll update this answer at some point with that.

How to change the default background color white to something else in twitter bootstrap

The colors changed due to the order of CSS files.

Place the custom CSS under the bootstrap CSS.

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

Laravel: Auth::user()->id trying to get a property of a non-object

For Laravel 6.X you can do the following:

$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

A lot of the above answers are correct. However, there seems to be more than one possible error when dealing with this.

The one I had was a capitalization issue with my App ID. My App ID for some reason wasn't capitalized but my app was. Once I recreated the App ID with correct capitalization, it all worked smoothly. Hope this helps. Frustrating as hell though.

P.S. if it still doesn't work, try editing the Code Signing Identity Field manually with "edit". Change the second line with the name of the correct provisioning profile name.

postgresql duplicate key violates unique constraint

The primary key is already protecting you from inserting duplicate values, as you're experiencing when you get that error. Adding another unique constraint isn't necessary to do that.

The "duplicate key" error is telling you that the work was not done because it would produce a duplicate key, not that it discovered a duplicate key already commited to the table.

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

Angular bootstrap datepicker date format does not format ng-model value

Defining a new directive to work around a bug is not really ideal.

Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:

$scope.dt = null;
$timeout( function(){
    $scope.dt = new Date();
},100);

Java: how to import a jar file from command line

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

How do I bind to list of checkbox values with AngularJS?

If you have multiple checkboxes on the same form

The controller code

vm.doYouHaveCheckBox = ['aaa', 'ccc', 'bbb'];
vm.desiredRoutesCheckBox = ['ddd', 'ccc', 'Default'];
vm.doYouHaveCBSelection = [];
vm.desiredRoutesCBSelection = [];

View code

<div ng-repeat="doYouHaveOption in vm.doYouHaveCheckBox">
    <div class="action-checkbox">
        <input id="{{doYouHaveOption}}" type="checkbox" value="{{doYouHaveOption}}" ng-checked="vm.doYouHaveCBSelection.indexOf(doYouHaveOption) > -1" ng-click="vm.toggleSelection(doYouHaveOption,vm.doYouHaveCBSelection)" />
        <label for="{{doYouHaveOption}}"></label>
        {{doYouHaveOption}}
    </div>
</div>

<div ng-repeat="desiredRoutesOption in vm.desiredRoutesCheckBox">
     <div class="action-checkbox">
          <input id="{{desiredRoutesOption}}" type="checkbox" value="{{desiredRoutesOption}}" ng-checked="vm.desiredRoutesCBSelection.indexOf(desiredRoutesOption) > -1" ng-click="vm.toggleSelection(desiredRoutesOption,vm.desiredRoutesCBSelection)" />
          <label for="{{desiredRoutesOption}}"></label>
          {{desiredRoutesOption}}
     </div>
</div>        

LINQ equivalent of foreach for IEnumerable<T>

This "functional approach" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the "ForEach" behavior.

Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)

this is a hack, and should not be used in any production code.

var b = srcDictionary.Select(
                             x=>
                                {
                                  destDictionary[x.Key] = x.Value;
                                  return true;
                                }
                             ).Count();

Determine the path of the executing BASH script

echo Running from `dirname $0`

Difference between SRC and HREF

You should remember when to use everyone and that is it
the href is used with links

<a href="#"></a>
<link rel="stylesheet" href="style.css" />

the src is used with scripts and images

<img src="the_image_link" />
<script type="text/javascript" src="" />

the url is used generally in CSS to include something, for exemple to add a background image

selector { background-image: url('the_image_link'); } 

jQuery: Adding two attributes via the .attr(); method

Should work:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

How do you force a makefile to rebuild a target

It actually depends on what the target is. If it is a phony target (i.e. the target is NOT related to a file) you should declare it as .PHONY.

If however the target is not a phony target but you just want to rebuild it for some reason (an example is when you use the __TIME__ preprocessing macro), you should use the FORCE scheme described in answers here.

Best way to store password in database

I may be slightly off-topic as you did mention the need for a username and password, and my understanding of the issue is admitedly not the best but is OpenID something worth considering?

If you use OpenID then you don't end up storing any credentials at all if I understand the technology correctly and users can use credentials that they already have, avoiding the need to create a new identity that is specific to your application.

It may not be suitable if the application in question is purely for internal use though

RPX provides a nice easy way to intergrate OpenID support into an application.

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;
Console.WriteLine(d.Name);

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:

d.GetType().GetProperty("Name") 

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

Grouping functions (tapply, by, aggregate) and the *apply family

From slide 21 of http://www.slideshare.net/hadley/plyr-one-data-analytic-strategy:

apply, sapply, lapply, by, aggregate

(Hopefully it's clear that apply corresponds to @Hadley's aaply and aggregate corresponds to @Hadley's ddply etc. Slide 20 of the same slideshare will clarify if you don't get it from this image.)

(on the left is input, on the top is output)

What is HEAD in Git?

There is a, perhaps subtle, but important misconception in a number these answers. I thought I'd add my answer to clear it up.

What is HEAD?

HEAD is YOU

HEADis a symbolic reference pointing to wherever you are in your commit history. It follows you wherever you go, whatever you do, like a shadow. If you make a commit, HEAD will move. If you checkout something, HEAD will move. Whatever you do, if you have moved somewhere new in your commit history, HEAD has moved along with you. To address one common misconception: you cannot detach yourself from HEAD. That is not what a detached HEAD state is. If you ever find yourself thinking: "oh no, i'm in detached HEAD state! I've lost my HEAD!" Remember, it's your HEAD. HEAD is you. You haven't detached from the HEAD, you and your HEAD have detached from something else.

What can HEAD attach to?

HEAD can point to a commit, yes, but typically it does not. Let me say that again. Typically HEAD does not point to a commit. It points to a branch reference. It is attached to that branch, and when you do certain things (e.g., commit or reset), the attached branch will move along with HEAD. You can see what it is pointing to by looking under the hood.

cat .git/HEAD

Normally you'll get something like this:

ref: refs/heads/master

Sometimes you'll get something like this:

a3c485d9688e3c6bc14b06ca1529f0e78edd3f86

That's what happens when HEAD points directly to a commit. This is called a detached HEAD, because HEAD is pointing to something other than a branch reference. If you make a commit in this state, master, no longer being attached to HEAD, will no longer move along with you. It does not matter where that commit is. You could be on the same commit as your master branch, but if HEAD is pointing to the commit rather than the branch, it is detached and a new commit will not be associated with a branch reference.

You can look at this graphically if you try the following exercise. From a git repository, run this. You'll get something slightly different, but they key bits will be there. When it is time to checkout the commit directly, just use whatever abbreviated hash you get from the first output (here it is a3c485d).

git checkout master
git log --pretty=format:"%h:  %d" -1
# a3c485d:   (HEAD -> master)

git checkout a3c485d -q # (-q is for dramatic effect)
git log --pretty=format:"%h:  %d" -1   
# a3c485d:   (HEAD, master)

OK, so there is a small difference in the output here. Checking out the commit directly (instead of the branch) gives us a comma instead of an arrow. What do you think, are we in a detached HEAD state? HEAD is still referring to a specific revision that is associated with a branch name. We're still on the master branch, aren't we?

Now try:

git status
# HEAD detached at a3c485d

Nope. We're in 'detached HEAD' state.

You can see the same representation of (HEAD -> branch) vs. (HEAD, branch) with git log -1.

In conclusion

HEAD is you. It points to whatever you checked out, wherever you are. Typically that is not a commit, it is a branch. If HEAD does point to a commit (or tag), even if it's the same commit (or tag) that a branch also points to, you (and HEAD) have been detached from that branch. Since you don't have a branch attached to you, the branch won't follow along with you as you make new commits. HEAD, however, will.

MongoDB not equal to

Use $ne -- $not should be followed by the standard operator:

An examples for $ne, which stands for not equal:

use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }

And now $not, which takes in predicate ($ne) and negates it ($not):

db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }

Clearing all cookies with JavaScript

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

Note that this code has two limitations:

  • It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript's access to the cookie.
  • It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie, but you can't delete it without specifying the same Path value with which it was set.)

Hashing a file in Python

Here is a Python 3, POSIX solution (not Windows!) that uses mmap to map the object into memory.

import hashlib
import mmap

def sha256sum(filename):
    h  = hashlib.sha256()
    with open(filename, 'rb') as f:
        with mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) as mm:
            h.update(mm)
    return h.hexdigest()

Change background position with jQuery

rebellion's answer above won't actually work, because to CSS, 'background-position' is actually shorthand for 'background-position-x' and 'background-position-y' so the correct version of his code would be:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position-x', newValueX);
        $('#carousel').css('background-position-y', newValue);
    }, function(){
        $('#carousel').css('background-position-x', oldValueX);
        $('#carousel').css('background-position-y', oldValueY);
    });
});

It took about 4 hours of banging my head against it to come to that aggravating realization.

How do I correct the character encoding of a file?

EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252.

Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more.

As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do.

Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion.

Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.

Setting a property by reflection with a string value

I will answer this with a general answer. Usually these answers not working with guids. Here is a working version with guids too.

var stringVal="6e3ba183-89d9-e611-80c2-00155dcfb231"; // guid value as string to set
var prop = obj.GetType().GetProperty("FooGuidProperty"); // property to be setted
var propType = prop.PropertyType;

// var will be type of guid here
var valWithRealType = TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal); 

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

I've made a category from @Abizern answer

@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
    NSError *error;
    NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
    return (!json ? nil : json);
}
@end

Use it like this,

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);

How to escape strings in SQL Server using PHP?

In order to escape single- and double-quotes, you have to double them up:

$value = 'This is a quote, "I said, 'Hi'"';

$value = str_replace( "'", "''", $value ); 

$value = str_replace( '"', '""', $value );

$query = "INSERT INTO TableName ( TextFieldName ) VALUES ( '$value' ) ";

etc...

and attribution: Escape Character In Microsoft SQL Server 2000

How do I find the date a video (.AVI .MP4) was actually recorded?

The existence of that piece of metadata is entirely dependent on the application that wrote the file. It's very common to load up JPG files with metadata (EXIF tags) about the file, such as a timestamp or camera information or geolocation. ID3 tags in MP3 files are also very common. But it's a lot less common to see this kind of metadata in video files.

If you just need a tool to read this data from files manually, GSpot might do the trick: http://www.videohelp.com/tools/Gspot

If you want to read this in code then I imagine each container format is going to have its own standards and each one will take a bit of research and implementation to support.

sed: print only matching group

And for yet another option, I'd go with awk!

echo "foo bar <foo> bla 1 2 3.4" | awk '{ print $(NF-1), $NF; }'

This will split the input (I'm using STDIN here, but your input could easily be a file) on spaces, and then print out the last-but-one field, and then the last field. The $NF variables hold the number of fields found after exploding on spaces.

The benefit of this is that it doesn't matter if what precedes the last two fields changes, as long as you only ever want the last two it'll continue to work.

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

Clear form fields with jQuery

With Javascript you can simply do it with this syntax getElementById("your-form-id").reset();

you can also use jquery by calling the reset function this way $('#your-form-id')[0].reset();

Remember not to forget [0]. You will get the following error if

TypeError: $(...).reset is not a function

JQuery also provides an event you can use

$('#form_id').trigger("reset");

I tried and it works.

Note: Its important to notice that these methods only reset your form to their initial value set by the server on page load. This means if your input was set on the value 'set value' before you did a random change, the field will be reset to that same value after reset method is called.

Hope it helps

Getting Spring Application Context

If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.

If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.

Remove/ truncate leading zeros by javascript/jquery

You should use the "radix" parameter of the "parseInt" function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt

parseInt('015', 10) => 15

if you don't use it, some javascript engine might use it as an octal parseInt('015') => 0

The shortest possible output from git log containing author and date

git log --pretty=format:"%h%x09%an%x09%ad%x09%s"

did the job. This outputs:

  fbc3503 mads    Thu Dec 4 07:43:27 2008 +0000   show mobile if phone is null...   
  ec36490 jesper  Wed Nov 26 05:41:37 2008 +0000  Cleanup after [942]: Using timezon
  ae62afd tobias  Tue Nov 25 21:42:55 2008 +0000  Fixed #67 by adding time zone supp
  164be7e mads    Tue Nov 25 19:56:43 2008 +0000  fixed tests, and a 'unending appoi
  93f1526 jesper  Tue Nov 25 09:45:56 2008 +0000  adding time.ZONE.now as time zone 
  2f0f8c1 tobias  Tue Nov 25 03:07:02 2008 +0000  Timezone configured in environment
  a33c1dc jesper  Tue Nov 25 01:26:18 2008 +0000  updated to most recent will_pagina

Inspired by stackoverflow question: "git log output like svn ls -v", i found out that I could add the exact params I needed.

To shorten the date (not showing the time) use --date=short

In case you were curious what the different options were:
%h = abbreviated commit hash
%x09 = tab (character for code 9)
%an = author name
%ad = author date (format respects --date= option)
%s = subject
From kernel.org/pub/software/scm/git/docs/git-log.html (PRETTY FORMATS section) by comment of Vivek.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

How to add parameters to an external data query in Excel which can't be displayed graphically?

If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ? where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.

E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.

Sub UpdateQuery
    Dim cn As WorkbookConnection
    Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
    For Each cn In ThisWorkbook.Connections
        If cn.Type = xlConnectionTypeODBC Then
            Set odbcCn = cn.ODBCConnection

            ' If you do have multiple connections you would want to modify  
            ' the line below each time you run through the loop.
            odbcCn.CommandText = "select blah from someTable where blah like ?"

        ElseIf cn.Type = xlConnectionTypeOLEDB Then
            Set oledbCn = cn.OLEDBConnection
            oledbCn.CommandText = "select blah from someTable where blah like ?" 
        End If
    Next
End Sub

How to mock location on device?

There are apps available in the Android Market that allow you to specify a "Mock GPS Location" for your device.

I searched https://market.android.com and found an app called "My Fake Location" that works for me.

The Mock GPS Provider mentioned by Paul above (at http://www.cowlumbus.nl/forum/MockGpsProvider.zip) is another example that includes source code -- although I wasn't able to install the provided APK (it says Failure [INSTALL_FAILED_OLDER_SDK] and may just need a recompile)

In order to use GPS mock locations you need to enable it in your device settings. Go to Settings -> Applications -> Development and check "Allow mock locations"

You can then use an app like the ones described above to set GPS coordinates and Google maps and other apps will use the mock GPS location you specify.

How to determine if one array contains all elements of another array

Depending on how big your arrays are you might consider an efficient algorithm O(n log n)

def equal_a(a1, a2)
  a1sorted = a1.sort
  a2sorted = a2.sort
  return false if a1.length != a2.length
  0.upto(a1.length - 1) do 
    |i| return false if a1sorted[i] != a2sorted[i]
  end
end

Sorting costs O(n log n) and checking each pair costs O(n) thus this algorithm is O(n log n). The other algorithms cannot be faster (asymptotically) using unsorted arrays.

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

Could not find a part of the path ... bin\roslyn\csc.exe

Delete the Bin folder in your solution explorer and Build the solution again. That would solve the problem

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Procedure expects parameter which was not supplied

If Template is not set (i.e. ==null), this error will be raised, too.

More comments:

If you know the parameter value by the time you add parameters, you can also use AddWithValue

The EXEC is not required. You can reference the @template parameter in the SELECT directly.

Failed to find Build Tools revision 23.0.1

I faced the same problem and I solved it doing the following:

Go to /home/[USER]/Android/Sdk/tools and execute:

$android list sdk -a

Which will show a list like:

  1. Android SDK Tools, revision 24.0.2
  2. Android SDK Platform-tools, revision 23.0.2
  3. Android SDK Platform-tools, revision 23.0.1

... and many more

Then, execute the command (attention! at your computer the third option may be different):

$android update sdk -a -u -t 3

It will install the 23.0.1 SDK Platform-tools components.

Try to build your project again.

How to check whether mod_rewrite is enable on server?

  1. To check if mod_rewrite module is enabled, create a new php file in your root folder of your WAMP server. Enter the following

    phpinfo();

  2. Access your created file from your browser.

  3. CtrlF to open a search. Search for 'mod_rewrite'. If it is enabled you see it as 'Loaded Modules'

  4. If not, open httpd.conf (Apache Config file) and look for the following line.

    #LoadModule rewrite_module modules/mod_rewrite.so

  5. Remove the pound ('#') sign at the start and save the this file.

  6. Restart your apache server.

  7. Access the same php file in your browser.

  8. Search for 'mod_rewrite' again. You should be able to find it now.

How to bind a List to a ComboBox?

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

For 2) you will need a list of countries first

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

How to set 'X-Frame-Options' on iframe?

You can't set X-Frame-Options on the iframe. That is a response header set by the domain from which you are requesting the resource (google.com.ua in your example). They have set the header to SAMEORIGIN in this case, which means that they have disallowed loading of the resource in an iframe outside of their domain. For more information see The X-Frame-Options response header on MDN.

A quick inspection of the headers (shown here in Chrome developer tools) reveals the X-Frame-Options value returned from the host.

enter image description here

Is it not possible to define multiple constructors in Python?

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city

How to put a List<class> into a JSONObject and then read that object?

Just to update this thread, here is how to add a list (as a json array) into JSONObject. Plz substitute YourClass with your class name;

List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();

org.codehaus.jackson.map.ObjectMapper objectMapper = new 
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

How can I make visible an invisible control with jquery? (hide and show not work)

.show() and .hide() modify the css display rule. I think you want:

$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element

Convert a String of Hex into ASCII in Java

Easiest way to do it with javax.xml.bind.DatatypeConverter:

    String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
    byte[] s = DatatypeConverter.parseHexBinary(hex);
    System.out.println(new String(s));

tsconfig.json: Build:No inputs were found in config file

I'm not using TypeScript in this project at all so it's quite frustrating having to deal with this. I fixed this by adding a tsconfig.json and an empty file.ts file to the project root. The tsconfig.json contains this:

{
  "compilerOptions": {

    "allowJs": false,
    "noEmit": true // Do not compile the JS (or TS) files in this project on build

  },
  "compileOnSave": false,
  "exclude": [ "src", "wwwroot" ],
  "include": [ "file.ts" ]
}

Which Eclipse version should I use for an Android app?

I would recommend at least Eclipse Indigo (v 3.7) for Android Development because even though a minimum of Helios (v 3.6) is required for ADT 22.0.1 as explained here...

http://developer.android.com/tools/sdk/eclipse-adt.html

... Indigo is required for Android NDK development using CDT, as explained here:

http://tools.android.com/recent/usingthendkplugin

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Target Unreachable, identifier resolved to null in JSF 2.2

I want to share my experience with this Exception. My JSF 2.2 application worked fine with WildFly 8.0, but one time, when I started server, i got this "Target Unreacheable" exception. Actually, there was no problem with JSF annotations or tags.

Only thing I had to do was cleaning the project. After this operation, my app is working fine again.

I hope this will help someone!

convert base64 to image in javascript/jquery

Have to add this based on @Joseph's answer. If someone want to create image object:

var image = new Image();
image.onload = function(){
   console.log(image.width); // image is loaded and we have image width 
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

What's the simplest way to list conflicted files in Git?

you may hit git ls-files -u on your command line it lists down files with conflicts

mat-form-field must contain a MatFormFieldControl

This error appears also when simply by mistake input is placed out of the mat-form-field. To fix it just bring it inside like below:

Bad code:

<mat-form-field class="full-width">
</mat-form-field>
<input matInput placeholder="Title" formControlName="title" #title />

Fix:

<mat-form-field class="full-width">
    <input matInput placeholder="Title" formControlName="title" #title />
</mat-form-field>

How to use double or single brackets, parentheses, curly braces

I just wanted to add these from TLDP:

~:$ echo $SHELL
/bin/bash

~:$ echo ${#SHELL}
9

~:$ ARRAY=(one two three)

~:$ echo ${#ARRAY}
3

~:$ echo ${TEST:-test}
test

~:$ echo $TEST


~:$ export TEST=a_string

~:$ echo ${TEST:-test}
a_string

~:$ echo ${TEST2:-$TEST}
a_string

~:$ echo $TEST2


~:$ echo ${TEST2:=$TEST}
a_string

~:$ echo $TEST2
a_string

~:$ export STRING="thisisaverylongname"

~:$ echo ${STRING:4}
isaverylongname

~:$ echo ${STRING:6:5}
avery

~:$ echo ${ARRAY[*]}
one two one three one four

~:$ echo ${ARRAY[*]#one}
two three four

~:$ echo ${ARRAY[*]#t}
one wo one hree one four

~:$ echo ${ARRAY[*]#t*}
one wo one hree one four

~:$ echo ${ARRAY[*]##t*}
one one one four

~:$ echo $STRING
thisisaverylongname

~:$ echo ${STRING%name}
thisisaverylong

~:$ echo ${STRING/name/string}
thisisaverylongstring

How can I add to a List's first position?

Use List.Insert(0, ...). But are you sure a LinkedList isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

load jquery after the page is fully loaded

Include your scripts at the bottom of the page before closing body tag.

More info HERE.

Bootstrap datepicker hide after selection

I got a perfect solution:

$('#Date_of_Birth').datepicker().on('changeDate', function (e) {
    if(e.viewMode === 'days')
        $(this).blur();
});

How to set an environment variable from a Gradle build?

Please try this one option:

 task RunTest(type: Test) {
         systemProperty "spring.profiles.active", System.getProperty("DEV")
         include 'com/db/project/Test1.class'
     }

Check if a string contains a string in C++

Actually, you can try to use boost library,I think std::string doesn't supply enough method to do all the common string operation.In boost,you can just use the boost::algorithm::contains:

#include <string>
#include <boost/algorithm/string.hpp>

int main() {
    std::string s("gengjiawen");
    std::string t("geng");
    bool b = boost::algorithm::contains(s, t);
    std::cout << b << std::endl;
    return 0;
}

TempData keep() vs peek()

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

With Peek you get the value without marking it for deletion with a single call, see msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

You have 2 good questions about how TempData works here and here

Hope it helps!

CSS styling in Django forms

If you don't want to add any code to the form (as mentioned in the comments to @shadfc's Answer), it is certainly possible, here are two options.

First, you just reference the fields individually in the HTML, rather than the entire form at once:

<form action="" method="post">
    <ul class="contactList">
        <li id="subject" class="contact">{{ form.subject }}</li>
        <li id="email" class="contact">{{ form.email }}</li>
        <li id="message" class="contact">{{ form.message }}</li>
    </ul>
    <input type="submit" value="Submit">
</form>

(Note that I also changed it to a unsorted list.)

Second, note in the docs on outputting forms as HTML, Django:

The Field id, is generated by prepending 'id_' to the Field name. The id attributes and tags are included in the output by default.

All of your form fields already have a unique id. So you would reference id_subject in your CSS file to style the subject field. I should note, this is how the form behaves when you take the default HTML, which requires just printing the form, not the individual fields:

<ul class="contactList">
    {{ form }}  # Will auto-generate HTML with id_subject, id_email, email_message 
    {{ form.as_ul }} # might also work, haven't tested
</ul>

See the previous link for other options when outputting forms (you can do tables, etc).

Note - I realize this isn't the same as adding a class to each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by id in your CSS like this:

#id_subject, #id_email, #email_message 
{color: red;}

From Now() to Current_timestamp in Postgresql

Here is what the MySQL docs say about NOW():

Returns the current date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

Now, you can certainly reduce your smart date to something less...

SELECT (
 date_part('year', NOW())::text
 || date_part('month', NOW())::text
 || date_part('day', NOW())::text
 || date_part('hour', NOW())::text
 || date_part('minute', NOW())::text
 || date_part('second', NOW())::text
)::float8 + foo;

But, that would be a really bad idea, what you need to understand is that times and dates are not stupid unformated numbers, they are their own type with their own set of functions and operators

So the MySQL time essentially lets you treat NOW() as a dumber type, or it overrides + to make a presumption that I can't find in the MySQL docs. Eitherway, you probably want to look at the date and interval types in pg.

Reading Datetime value From Excel sheet

Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value returns a desired DateTime object.


public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
    object cellValue = cell.Value;
    if (cellValue is DateTime result)
    {
        return result;
    }
    return null;
}

Exiting from python Command Line

In my python interpreter exit is actually a string and not a function -- 'Use Ctrl-D (i.e. EOF) to exit.'. You can check on your interpreter by entering type(exit)

In active python what is happening is that exit is a function. If you do not call the function it will print out the string representation of the object. This is the default behaviour for any object returned. It's just that the designers thought people might try to type exit to exit the interpreter, so they made the string representation of the exit function a helpful message. You can check this behaviour by typing str(exit) or even print exit.

Plotting a fast Fourier transform in Python

Just as a complement to the answers already given, I would like to point out that often it is important to play with the size of the bins for the FFT. It would make sense to test a bunch of values and pick the one that makes more sense to your application. Often, it is in the same magnitude of the number of samples. This was as assumed by most of the answers given, and produces great and reasonable results. In case one wants to explore that, here is my code version:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

fig = plt.figure(figsize=[14,4])
N = 600           # Number of samplepoints
Fs = 800.0
T = 1.0 / Fs      # N_samps*T (#samples x sample period) is the sample spacing.
N_fft = 80        # Number of bins (chooses granularity)
x = np.linspace(0, N*T, N)     # the interval
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)   # the signal

# removing the mean of the signal
mean_removed = np.ones_like(y)*np.mean(y)
y = y - mean_removed

# Compute the fft.
yf = scipy.fftpack.fft(y,n=N_fft)
xf = np.arange(0,Fs,Fs/N_fft)

##### Plot the fft #####
ax = plt.subplot(121)
pt, = ax.plot(xf,np.abs(yf), lw=2.0, c='b')
p = plt.Rectangle((Fs/2, 0), Fs/2, ax.get_ylim()[1], facecolor="grey", fill=True, alpha=0.75, hatch="/", zorder=3)
ax.add_patch(p)
ax.set_xlim((ax.get_xlim()[0],Fs))
ax.set_title('FFT', fontsize= 16, fontweight="bold")
ax.set_ylabel('FFT magnitude (power)')
ax.set_xlabel('Frequency (Hz)')
plt.legend((p,), ('mirrowed',))
ax.grid()

##### Close up on the graph of fft#######
# This is the same histogram above, but truncated at the max frequence + an offset. 
offset = 1    # just to help the visualization. Nothing important.
ax2 = fig.add_subplot(122)
ax2.plot(xf,np.abs(yf), lw=2.0, c='b')
ax2.set_xticks(xf)
ax2.set_xlim(-1,int(Fs/6)+offset)
ax2.set_title('FFT close-up', fontsize= 16, fontweight="bold")
ax2.set_ylabel('FFT magnitude (power) - log')
ax2.set_xlabel('Frequency (Hz)')
ax2.hold(True)
ax2.grid()

plt.yscale('log')

the output plots: enter image description here

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

Just use

Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

Else
    'do it another thing
End If

How do I create a file AND any folders, if the folders don't exist?

You will need to check both parts of the path (directory and filename) and create each if it does not exist.

Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.

Remove duplicated rows

For people who have come here to look for a general answer for duplicate row removal, use !duplicated():

a <- c(rep("A", 3), rep("B", 3), rep("C",2))
b <- c(1,1,2,4,1,1,2,2)
df <-data.frame(a,b)

duplicated(df)
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE

> df[duplicated(df), ]
  a b
2 A 1
6 B 1
8 C 2

> df[!duplicated(df), ]
  a b
1 A 1
3 A 2
4 B 4
5 B 1
7 C 2

Answer from: Removing duplicated rows from R data frame

How can I discover the "path" of an embedded resource?

This will get you a string array of all the resources:

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

How to get current user in asp.net core

I know there area lot of correct answers here, with respect to all of them I introduce this hack :

In StartUp.cs

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and then everywhere you need HttpContext you can use :

httpContext = new HttpContextAccessor().HttpContext;

Hope it helps ;)

SVN Commit failed, access forbidden

Actually, I had this problem same as you. My windows is server 2008 and my subversion info is :

TortoiseSVN 1.7.6, Build 22632 - 64 Bit , 2012/03/08 18:29:39 Subversion 1.7.4, apr 1.4.5 apr-utils 1.3.12 neon 0.29.6 OpenSSL 1.0.0g 18 Jan 2012 zlib 1.2.5

I used this way and I solved this problem. I used [group] option. this option makes problem. I rewrite authz file contents. I remove group option. and I set one by one. I use well.

Thanks for reading.

Is it possible to have SSL certificate for IP address, not domain name?

It entirely depends upon the Certificate Authority who issuing a certificate.

As far as Let's Encrypt CA, they wont issue TLS certificate on public IP address. https://community.letsencrypt.org/t/certificate-for-public-ip-without-domain-name/6082

To know your Certificate authority , you can execute following command and look for an entry marked below.

curl -v -u <username>:<password> "https://IPaddress/.."

enter image description here

Is there a way to represent a directory tree in a Github README.md?

I wrote a small script that does the trick:

#!/bin/bash

#File: tree-md

tree=$(tree -tf --noreport -I '*~' --charset ascii $1 |
       sed -e 's/| \+/  /g' -e 's/[|`]-\+/ */g' -e 's:\(* \)\(\(.*/\)\([^/]\+\)\):\1[\4](\2):g')

printf "# Project tree\n\n${tree}"

Example:

Original tree command:

$ tree
.
+-- dir1
¦   +-- file11.ext
¦   +-- file12.ext
+-- dir2
¦   +-- file21.ext
¦   +-- file22.ext
¦   +-- file23.ext
+-- dir3
+-- file_in_root.ext
+-- README.md

3 directories, 7 files

Markdown tree command:

$ ./tree-md .
# Project tree

.
 * [tree-md](./tree-md)
 * [dir2](./dir2)
   * [file21.ext](./dir2/file21.ext)
   * [file22.ext](./dir2/file22.ext)
   * [file23.ext](./dir2/file23.ext)
 * [dir1](./dir1)
   * [file11.ext](./dir1/file11.ext)
   * [file12.ext](./dir1/file12.ext)
 * [file_in_root.ext](./file_in_root.ext)
 * [README.md](./README.md)
 * [dir3](./dir3)

Rendered result:

(Links are not visible in Stackoverflow...)

Project tree
  • tree-md
  • dir2
    • file21.ext
    • file22.ext
    • file23.ext
  • dir1
    • file11.ext
    • file12.ext
  • file_in_root.ext
  • README.md
  • dir3

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

Playing a MP3 file in a WinForm application

1) The most simple way would be using WMPLib

WMPLib.WindowsMediaPlayer Player;

private void PlayFile(String url)
{
    Player = new WMPLib.WindowsMediaPlayer();
    Player.PlayStateChange += Player_PlayStateChange;
    Player.URL = url;
    Player.controls.play();
}

private void Player_PlayStateChange(int NewState)
{
    if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
    {
        //Actions on stop
    }
}

2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.

This is as simple as

using NAudio;
using NAudio.Wave;

IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");

waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();

Don't forget to dispose after the stop

waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();

Using LIKE operator with stored procedure parameters

Your datatype for @location nchar(20) should be @location nvarchar(20), since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

To enable nullable parameters with and AND condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR.

e.g. if you would like to compare for Location AND Date and Time.

@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Anyway, here is how to fix it:

Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:

Variable name: _JAVA_OPTIONS

Variable value: -Xmx512M

taken from this link

Android Facebook integration with invalid key hash

I experienced the same problem. I made a short research on the possible reasons for this strange behavior and I found the following:

  • During the first execution of a new Facebook app, it will allow connection/login even if you don't specify any key hashes.

  • For me, the tutorial which Facebook provided didn't generate the correct key hash, because it was giving the wrong configuration. When executing:

    keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
    base64
    

make sure you check all properties - the HOMEPATH, the existence of the keystore, etc. Maybe you also have to provide password.

  • What generated the proper configuration was the solution suggested by @Mahendran.

  • Also, if you see the error originally posted (http://i.stack.imgur.com/58q3v.png), most probably the key hash you see on the screen is your real one. If nothing else works, try inputting it in Facebook.

I got all those results with: Windows 7 64-bit edition, Android Studio 1.2.2, JDK 7.

select a value where it doesn't exist in another table

SELECT ID 
  FROM A 
 WHERE NOT EXISTS( SELECT 1
                     FROM B
                    WHERE B.ID = A.ID
                 )

right click context menu for datagridview

Simply drag a ContextMenu or ContextMenuStrip component into your form and visually design it, then assign it to the ContextMenu or ContextMenuStrip property of your desired control.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

ggplot2 plot without axes, legends, etc

'opts' is deprecated.

in ggplot2 >= 0.9.2 use

p + theme(legend.position = "none") 

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Order by multiple columns with Doctrine

The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

jQuery get content between <div> tags

Give the div a class or id and do something like this:

$("#example").get().innerHTML;

That works at the DOM level.

Getting command-line password input in Python

import getpass

pswd = getpass.getpass('Password:')

getpass works on Linux, Windows, and Mac.

Comparing floating point number to zero

Simple comparison of FP numbers has it's own specific and it's key is the understanding of FP format (see https://en.wikipedia.org/wiki/IEEE_floating_point)

When FP numbers calculated in a different ways, one through sin(), other though exp(), strict equality won't be working, even though mathematically numbers could be equal. The same way won't be working equality with the constant. Actually, in many situations FP numbers must not be compared using strict equality (==)

In such cases should be used DBL_EPSIPON constant, which is minimal value do not change representation of 1.0 being added to the number more than 1.0. For floating point numbers that more than 2.0 DBL_EPSIPON does not exists at all. Meanwhile, DBL_EPSILON has exponent -16, which means that all numbers, let's say, with exponent -34, would be absolutely equal in compare to DBL_EPSILON.

Also, see example, why 10.0 == 10.0000000000000001

Comparing dwo floating point numbers depend on these number nature, we should calculate DBL_EPSILON for them that would be meaningful for the comparison. Simply, we should multiply DBL_EPSILON to one of these numbers. Which of them? Maximum of course

bool close_enough(double a, double b){
    if (fabs(a - b) <= DBL_EPSILON * std::fmax(fabs(a), fabs(b)))
    {
        return true;
    }
    return false;
}

All other ways would give you bugs with inequality which could be very hard to catch

Can't create project on Netbeans 8.2

Faced same issue with jdk 10. While installing netbeans prompted for jdk default location was taken as jdk 10. This was the issue, it should be jdk8 (1.8).

  1. Close Netbeans
  2. Open below file
    C:\Program Files\NetBeans 8.2\etc\netbeans.conf
  3. Comment jdkhome line jdk9 or jdk10 with # sign:
    # netbeans_jdkhome="C:\Program Files\Java\jdk-10.0.1"
  4. Add new jdkhome line for jdk8:
    netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_171"
  5. Start Netbeans

Note: If the above .conf file is not editable, then use Administrator mode. I use Notepad++, it prompted for restarting Notepad++ in Administrator mode, then save worked fine.

"Fatal error: Cannot redeclare <function>"

I want to add my 2 cent experience that might be helpful for many of you.

If you declare a function inside a loop (for, foreach, while), you will face this error message.

"SSL certificate verify failed" using pip to install packages

If you're using python3, you can try this too:

python3 -m pip install --upgrade Scrapy --trusted-host pypi.org --trusted-host files.pythonhosted.org

Understanding unique keys for array children in React.js

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
   <li key={index}>
      {todo.text}
   </li>
);

Please refer to List and Keys - React

How can I view a git log of just one user's commits?

To pull more details - (Here %an refers to author)

Use this :-

git log --author="username" --pretty=format:"%h - %an, %ar : %s"

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

As others answer 0 meaning success, otherwise.

If you using bat file (window) System.exit(x) will effect.

Code java (myapp):

if (error < 2){
    help();
    System.exit(-1);    
}
else{
    doSomthing();
    System.exit(0);
}

}

bat file:

java -jar myapp.jar
if %errorlevel% neq 0 exit /b %errorlevel%
rem -- next command if myapp is success --

Script Tag - async & defer

HTML5: async, defer

In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.

  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.

  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

How to compare 2 files fast using .NET?

Edit: This method would not work for comparing binary files!

In .NET 4.0, the File class has the following two new methods:

public static IEnumerable<string> ReadLines(string path)
public static IEnumerable<string> ReadLines(string path, Encoding encoding)

Which means you could use:

bool same = File.ReadLines(path1).SequenceEqual(File.ReadLines(path2));

Align DIV to bottom of the page

Right I think I know what you mean so lets see....

HTML:

<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>
</div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
div {
    outline: 1px solid;
}
#con {
   min-height:100%;
   position:relative;
}
#content {
   height: 1000px; /* Changed this height */
   padding-bottom:60px;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
}

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.

DEMO HERE

This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.

DEMO HERE

So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

jQuery Validation using the class instead of the name value

You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:

$(".checkBox").rules("add", { 
  required:true,  
  minlength:3
});

Multiple actions were found that match the request in Web Api

Your route map is probably something like this:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });

Notice that the routeTemplate now includes an action. Lots more info here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Update:

Alright, now that I think I understand what you are after here is another take at this:

Perhaps you don't need the action url parameter and should describe the contents that you are after in another way. Since you are saying that the methods are returning data from the same entity then just let the parameters do the describing for you.

For example your two methods could be turned into:

public HttpResponseMessage Get()
{
    return null;
}

public HttpResponseMessage Get(MyVm vm)
{
    return null;
}

What kind of data are you passing in the MyVm object? If you are able to just pass variables through the URI, I would suggest going that route. Otherwise, you'll need to send the object in the body of the request and that isn't very HTTP of you when doing a GET (it works though, just use [FromBody] infront of MyVm).

Hopefully this illustrates that you can have multiple GET methods in a single controller without using the action name or even the [HttpGet] attribute.

How to escape special characters of a string with single backslashes

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

How to determine whether a given Linux is 32 bit or 64 bit?

With respect to the answer "getconf LONG_BIT".

I wrote a simple function to do it in 'C':

/*
 * check_os_64bit
 *
 * Returns integer:
 *   1 = it is a 64-bit OS
 *   0 = it is NOT a 64-bit OS (probably 32-bit)
 *   < 0 = failure
 *     -1 = popen failed
 *     -2 = fgets failed
 *
 * **WARNING**
 * Be CAREFUL! Just testing for a boolean return may not cut it
 * with this (trivial) implementation! (Think of when it fails,
 * returning -ve; this could be seen as non-zero & therefore true!)
 * Suggestions?
 */
static int check_os_64bit(void)
{
    FILE *fp=NULL;
    char cb64[3];

    fp = popen ("getconf LONG_BIT", "r");
    if (!fp)
       return -1;

    if (!fgets(cb64, 3, fp))
        return -2;

    if (!strncmp (cb64, "64", 3)) {
        return 1;
    }
    else {
        return 0;
    }
}

Good idea, the 'getconf'!

Force SSL/https using .htaccess and mod_rewrite

Mod-rewrite based solution :

Using the following code in htaccess automatically forwards all http requests to https.

RewriteEngine on

RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

This will redirect your non-www and www http requests to www version of https.

Another solution (Apache 2.4*)

RewriteEngine on

RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

This doesn't work on lower versions of apache as %{REQUEST_SCHEME} variable was added to mod-rewrite since 2.4.

How do I get the HTML code of a web page in PHP?

Also if you want to manipulate the retrieved page somehow, you might want to try some php DOM parser. I find PHP Simple HTML DOM Parser very easy to use.

Combine several images horizontally with Python

You can do something like this:

import sys
from PIL import Image

images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
  new_im.paste(im, (x_offset,0))
  x_offset += im.size[0]

new_im.save('test.jpg')

Test1.jpg

Test1.jpg

Test2.jpg

Test2.jpg

Test3.jpg

Test3.jpg

test.jpg

enter image description here


The nested for for i in xrange(0,444,95): is pasting each image 5 times, staggered 95 pixels apart. Each outer loop iteration pasting over the previous.

for elem in list_im:
  for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
  new_im.save('new_' + elem + '.jpg')

enter image description here enter image description here enter image description here

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

<dependency>
     <groupId>org.openrdf.sesame</groupId>
     <artifactId>sesame-runtime</artifactId>
     <version>2.7.2</version>
     <scope> ... </scope>
</dependency>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

Git: See my last commit

By far the simplest command for this is:

git show --name-only

As it lists just the files in the last commit and doesn't give you the entire guts

An example of the output being:

commit  fkh889hiuhb069e44254b4925d2b580a602
Author: Kylo Ren <[email protected]>
Date:   Sat May 4 16:50:32 2168 -0700

Changed shield frequencies to prevent Millennium Falcon landing

 www/controllers/landing_ba_controller.js             
 www/controllers/landing_b_controller.js            
 www/controllers/landing_bp_controller.js          
 www/controllers/landing_h_controller.js          
 www/controllers/landing_w_controller.js  
 www/htdocs/robots.txt                        
 www/htdocs/templates/shields_FAQ.html       

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

Java: int[] array vs int array[]

Both are equivalent. Take a look at the following:

int[] array;

// is equivalent to

int array[];
int var, array[];

// is equivalent to

int var;
int[] array;
int[] array1, array2[];

// is equivalent to

int[] array1;
int[][] array2;
public static int[] getArray()
{
    // ..
}

// is equivalent to

public static int getArray()[]
{
    // ..
}

how to create a Java Date object of midnight today and midnight tomorrow?

Date now= new Date();
// Today midnight
Date todayMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY);

// tomorrow midnight
Date tomorrowMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY + DateUtils.MILLIS_PER_DAY);

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Just:

dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)

So do this:

start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')

end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')

and then use start_time and end_time

Why does the 260 character path length limit exist in Windows?

It does, and it is a default for some reason, but you could easily override it with this registry key:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
"LongPathsEnabled"=dword:00000001

See: https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

Is there a "theirs" version of "git merge -s ours"?

Why doesn't it exist?

While I mention in "git command for making one branch like another" how to simulate git merge -s theirs, note that Git 2.15 (Q4 2017) is now clearer:

The documentation for '-X<option>' for merges was misleadingly written to suggest that "-s theirs" exists, which is not the case.

See commit c25d98b (25 Sep 2017) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 4da3e23, 28 Sep 2017)

merge-strategies: avoid implying that "-s theirs" exists

The description of -Xours merge option has a parenthetical note that tells the readers that it is very different from -s ours, which is correct, but the description of -Xtheirs that follows it carelessly says "this is the opposite of ours", giving a false impression that the readers also need to be warned that it is very different from -s theirs, which in reality does not even exist.

-Xtheirs is a strategy option applied to recursive strategy. This means that recursive strategy will still merge anything it can, and will only fall back to "theirs" logic in case of conflicts.

That debate for the pertinence or not of a theirs merge strategy was brought back recently in this Sept. 2017 thread.
It acknowledges older (2008) threads

In short, the previous discussion can be summarized to "we don't want '-s theirs' as it encourages the wrong workflow".

It mentions the alias:

mtheirs = !sh -c 'git merge -s ours --no-commit $1 && git read-tree -m -u $1' -

Yaroslav Halchenko tries to advocate once more for that strategy, but Junio C. Hamano adds:

The reason why ours and theirs are not symmetric is because you are you and not them---the control and ownership of our history and their history is not symmetric.

Once you decide that their history is the mainline, you'd rather want to treat your line of development as a side branch and make a merge in that direction, i.e. the first parent of the resulting merge is a commit on their history and the second parent is the last bad one of your history. So you would end up using "checkout their-history && merge -s ours your-history" to keep the first-parenthood sensible.

And at that point, use of "-s ours" is no longer a workaround for lack of "-s theirs".
It is a proper part of the desired semantics, i.e. from the point of view of the surviving canonical history line, you want to preserve what it did, nullifying what the other line of history did.

Junio adds, as commented by Mike Beaton:

git merge -s ours <their-ref> effectively says 'mark commits made up to <their-ref> on their branch as commits to be permanently ignored';
and this matters because, if you subsequently merge from later states of their branch, their later changes will be brought in without the ignored changes ever being brought in.

How to detect window.print() finish

It is difficult, due to different browser behavior after print. Desktop Chrome handles the print dialogue internally, so doesn't shift focus after print, however, afterprint event works fine here (As of now, 81.0). On the other hand, Chrome on mobile device and most of the other browsers shifts focus after print and afterprint event doesn't work consistently here. Mouse movement event doesn't work on mobile devices.

So, Detect if it is Desktop Chrome, If Yes, use afterprint event. If No, use focus based detection. You can also use mouse movement event(Works in desktop only) in combination of these, to cover more browsers and more scenarios.

What does a bitwise shift (left or right) do and what is it used for?

Here is an example:

#include"stdio.h"
#include"conio.h"

void main()
{
    int rm, vivek;
    clrscr();
    printf("Enter any numbers\t(E.g., 1, 2, 5");
    scanf("%d", &rm); // rm = 5(0101) << 2 (two step add zero's), so the value is 10100
    printf("This left shift value%d=%d", rm, rm<<4);
    printf("This right shift value%d=%d", rm, rm>>2);
    getch();
}

How to group subarrays by a column value?

1. GROUP BY one key

This function works as GROUP BY for array, but with one important limitation: Only one grouping "column" ($identifier) is possible.

function arrayUniqueByIdentifier(array $array, string $identifier)
{
    $ids = array_column($array, $identifier);
    $ids = array_unique($ids);
    $array = array_filter($array,
        function ($key, $value) use($ids) {
            return in_array($value, array_keys($ids));
        }, ARRAY_FILTER_USE_BOTH);
    return $array;
}

2. Detecting the unique rows for a table (twodimensional array)

This function is for filtering "rows". If we say, a twodimensional array is a table, then its each element is a row. So, we can remove the duplicated rows with this function. Two rows (elements of the first dimension) are equal, if all their columns (elements of the second dimension) are equal. To the comparsion of "column" values applies: If a value is of a simple type, the value itself will be use on comparing; otherwise its type (array, object, resource, unknown type) will be used.

The strategy is simple: Make from the original array a shallow array, where the elements are imploded "columns" of the original array; then apply array_unique(...) on it; and as last use the detected IDs for filtering of the original array.

function arrayUniqueByRow(array $table = [], string $implodeSeparator)
{
    $elementStrings = [];
    foreach ($table as $row) {
        // To avoid notices like "Array to string conversion".
        $elementPreparedForImplode = array_map(
            function ($field) {
                $valueType = gettype($field);
                $simpleTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
                $field = in_array($valueType, $simpleTypes) ? $field : $valueType;
                return $field;
            }, $row
        );
        $elementStrings[] = implode($implodeSeparator, $elementPreparedForImplode);
    }
    $elementStringsUnique = array_unique($elementStrings);
    $table = array_intersect_key($table, $elementStringsUnique);
    return $table;
}

It's also possible to improve the comparing, detecting the "column" value's class, if its type is object.

The $implodeSeparator should be more or less complex, z.B. spl_object_hash($this).


3. Detecting the rows with unique identifier columns for a table (twodimensional array)

This solution relies on the 2nd one. Now the complete "row" doesn't need to be unique. Two "rows" (elements of the first dimension) are equal now, if all relevant "fields" (elements of the second dimension) of the one "row" are equal to the according "fields" (elements with the same key).

The "relevant" "fields" are the "fields" (elements of the second dimension), which have key, that equals to one of the elements of the passed "identifiers".

function arrayUniqueByMultipleIdentifiers(array $table, array $identifiers, string $implodeSeparator = null)
{
    $arrayForMakingUniqueByRow = $removeArrayColumns($table, $identifiers, true);
    $arrayUniqueByRow = $arrayUniqueByRow($arrayForMakingUniqueByRow, $implodeSeparator);
    $arrayUniqueByMultipleIdentifiers = array_intersect_key($table, $arrayUniqueByRow);
    return $arrayUniqueByMultipleIdentifiers;
}

function removeArrayColumns(array $table, array $columnNames, bool $isWhitelist = false)
{
    foreach ($table as $rowKey => $row) {
        if (is_array($row)) {
            if ($isWhitelist) {
                foreach ($row as $fieldName => $fieldValue) {
                    if (!in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            } else {
                foreach ($row as $fieldName => $fieldValue) {
                    if (in_array($fieldName, $columnNames)) {
                        unset($table[$rowKey][$fieldName]);
                    }
                }
            }
        }
    }
    return $table;
}

How to select records from last 24 hours using SQL?

In SQL Server (For last 24 hours):

SELECT  *
FROM    mytable
WHERE   order_date > DateAdd(DAY, -1, GETDATE()) and order_date<=GETDATE()

How do I read a text file of about 2 GB?

Try Glogg. the fast, smart log explorer.

I have opened log file of size around 2 GB, and the search is also very fast.

What's the source of Error: getaddrinfo EAI_AGAIN?

I had a same problem with AWS and Serverless. I tried with eu-central-1 region and it didn't work so I had to change it to us-east-2 for the example.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you want to allow all origins and keep credentials true, this worked for me:

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

Load local images in React.js

In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}

How do I resolve ClassNotFoundException?

If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..

Excel: VLOOKUP that returns true or false?

You still have to wrap it in an ISERROR, but you could use MATCH() instead of VLOOKUP():

Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.

Here's a complete example, assuming you're looking for the word "key" in a range of cells:

=IF(ISERROR(MATCH("key",A5:A16,FALSE)),"missing","found")

The FALSE is necessary to force an exact match, otherwise it will look for the closest value.

JavaScript Array splice vs slice

splice & delete Array item by index

index = 2

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));

console.log("----after-----");
console.log(arr1);
console.log(arr2);

_x000D_
_x000D_
let log = console.log;_x000D_
_x000D_
//splice & will modify the origin array_x000D_
const arr1 = [1,2,3,4,5];_x000D_
_x000D_
//slice & won't modify the origin array_x000D_
const arr2 = [1,2,3,4,5]_x000D_
_x000D_
log("----before-----");_x000D_
log(arr1.splice(2, 1));_x000D_
log(arr2.slice(2, 1));_x000D_
_x000D_
log("----after-----");_x000D_
log(arr1);_x000D_
log(arr2);
_x000D_
_x000D_
_x000D_

enter image description here

Cannot make a static reference to the non-static method fxn(int) from the type Two

Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:

public static int fxn(int y) {
    y = 5;
    return y;
}

or change the code in main to:

Two two = new Two();
x = two.fxn(x);

Read more on static here in the Java Tutorials.

Using StringWriter for XML Serialization

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

Cast IList to List

If you have an IList containing interfaces, you can cast it like this:

List to IList

List<Foo> Foos = new List<Foo>(); 
IList<IFoo> IFoos = Foos.ToList<IFoo>();

IList to List

IList<IFoo> IFoos = new List<IFoo>();
List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));

This assumes Foo has IFoo interfaced.

Hiding axis text in matplotlib plots

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

PHP: Split a string in to an array foreach char

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

How to Sort Multi-dimensional Array by Value?

$sort = array();
$array_lowercase = array_map('strtolower', $array_to_be_sorted);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);

This takes care of both upper and lower case alphabets.

Mock HttpContext.Current in Test Init Method

If your application third party redirect internally, so it is better to mock HttpContext in below way :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

How to kill a running SELECT statement

There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL:

Cancelling a SQL Statement in a Session

You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.

Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.

ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';

If @INST_ID is not specified, the instance ID of the current session is used.

If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

Wrap text in <td> tag

This works really well:

<td><div style = "width:80px; word-wrap: break-word"> your text </div></td> 

You can use the same width for all your <div's, or adjust the width in each case to break your text wherever you like.

This way you do not have to fool around with fixed table widths, or complex css.

How to align input forms in HTML

Well for the very basics you can try aligning them in the table. However the use of table is bad for layout since table is meant for contents.

What you can use is CSS floating techniques.

CSS Code

.styleform label{float:left;}
.styleform input{margin-left:200px;} /* this gives space for the label on the left */
.styleform .clear{clear:both;} /* prevent elements from stacking weirdly */

HTML

<div class="styleform">
<form>
<label>First Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Last Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Email:</label><input type="text" name="first" /><div class="clear"></div>
</form>
</div>

An elaborated article I wrote can be found answering the question of IE7 float problem: IE7 float right problems

Escaping quotes and double quotes

I found myself in a similar predicament today while trying to run a command through a Node.js module:

I was using the PowerShell and trying to run:

command -e 'func($a)'

But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:

command -e `"func($a)`"

How can I retrieve the remote git address of a repo?

If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

Nexus 5 USB driver

Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.

The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.

Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.

Open the System Properties box. Via Command line use sysdm.cpl

** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **

  1. Open the Advanced tab, click Environmental Variables.
  2. Under System Variables, click New.
  3. Enter variable name devmgr_show_nonpresent_devices, under value enter 1.
  4. Restart your computer.

Re-open the Device Manager, under view click Show Hidden Devices.

From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.

ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#

How to fix Python indentation

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type

:ret

all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.


If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

Take nth column in a text file

You can use the cut command:

cut -d' ' -f3,5 < datafile.txt

prints

1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

the

  • -d' ' - mean, use space as a delimiter
  • -f3,5 - take and print 3rd and 5th column

The cut is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:

sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5

where the (gnu) sed will replace any tab or space characters with a single space.

For a variant - here is a perl solution too:

perl -lanE 'say "$F[2] $F[4]"' < datafile.txt

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How do I make a redirect in PHP?

try this one

 $url = $_SERVER['HTTP_REFERER'];
 redirect($url);

Rename a dictionary key

In Python 3.6 (onwards?) I would go for the following one-liner

test = {'a': 1, 'old': 2, 'c': 3}
old_k = 'old'
new_k = 'new'
new_v = 4  # optional

print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))

which produces

{'a': 1, 'new': 4, 'c': 3}

May be worth noting that without the print statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...

add column to mysql table if it does not exist

Just tried the stored procedure script. Seems the problem is the ' marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.

So you want:

delimiter //

Instead of:

delimiter '//'

Works for me :)

Remove non-ASCII characters from CSV

I tried all the solutions and nothing worked. The following, however, does:

tr -cd '\11\12\15\40-\176'

Which I found here:

https://alvinalexander.com/blog/post/linux-unix/how-remove-non-printable-ascii-characters-file-unix

My problem needed it in a series of piped programs, not directly from a file, so modify as needed.

Format Float to n decimal places

You can use Decimal format if you want to format number into a string, for example:

String a = "123455";
System.out.println(new 
DecimalFormat(".0").format(Float.valueOf(a)));

The output of this code will be:

123455.0

You can add more zeros to the decimal format, depends on the output that you want.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

I was facing the same issue and just updated the JAVA_HOME worked for me.

previously it was like this: C:\Program Files\Java\jdk1.6.0_45\bin Just removed the \bin and it worked for me.

Read file-contents into a string in C++

Like this:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

can be split into

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

which is useful if you want to just overwrite the value of an existing std::string variable.

Perfect 100% width of parent container for a Bootstrap input?

What about?

    input[type="text"] {
          max-width:none;
   }

Checking that some css file is causing problems. By default bootstrap displays over the entire width. For instance in MVC directory Content is site.css and there is a definition constraining width.

input,select,textarea {
max-width: 280px;}

How can I initialize base class member variables in derived class constructor?

Leaving aside the fact that they are private, since a and b are members of A, they are meant to be initialized by A's constructors, not by some other class's constructors (derived or not).

Try:

class A
{
    int a, b;

protected: // or public:
    A(int a, int b): a(a), b(b) {}
};

class B : public A
{
    B() : A(0, 0) {}
};

Docker - a way to give access to a host USB or serial device?

There are a couple of options. You can use the --device flag that use can use to access USB devices without --privileged mode:

docker run -t -i --device=/dev/ttyUSB0 ubuntu bash

Alternatively, assuming your USB device is available with drivers working, etc. on the host in /dev/bus/usb, you can mount this in the container using privileged mode and the volumes option. For example:

docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash

Note that as the name implies, --privileged is insecure and should be handled with care.

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

Hiding a password in a python script (insecure obfuscation only)

Why not have a simple xor?

Advantages:

  • looks like binary data
  • noone can read it without knowing the key (even if it's a single char)

I get to the point where I recognize simple b64 strings for common words and rot13 as well. Xor would make it much harder.

How can I force input to uppercase in an ASP.NET textbox?

  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">

How do I access (read, write) Google Sheets spreadsheets with Python?

Have a look at GitHub - gspread.

I found it to be very easy to use and since you can retrieve a whole column by

first_col = worksheet.col_values(1)

and a whole row by

second_row = worksheet.row_values(2)

you can more or less build some basic select ... where ... = ... easily.

Error 0x80005000 and DirectoryServices

Just FYI, I had the same error and was using the correct credentials but my LDAP url was wrong :(

I got the exact same error message and code

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

This is a very common problem faced by developers and that is mainly due to Safari's property of not recreating elements defined as position : fixed.

So either change the position property or some hack needs to be applied as mentioned in other answers.

Link1

Link2

How to make child process die after parent exits?

I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.

The trick is:

  • process A is started
  • process A creates a pipe P (and never reads from it)
  • process A forks into process B
  • process B creates a new session
  • process B allocates a virtual terminal for that new session
  • process B installs SIGCHLD handler to die when the child exits
  • process B sets a SIGPIPE handler
  • process B forks into process C
  • process C does whatever it needs (e.g. exec()s the unmodified binary or runs whatever logic)
  • process B writes to pipe P (and blocks that way)
  • process A wait()s on process B and exits when it dies

That way:

  • if process A dies: process B gets a SIGPIPE and dies
  • if process B dies: process A's wait() returns and dies, process C gets a SIGHUP (because when the session leader of a session with a terminal attached dies, all processes in the foreground process group get a SIGHUP)
  • if process C dies: process B gets a SIGCHLD and dies, so process A dies

Shortcomings:

  • process C can't handle SIGHUP
  • process C will be run in a different session
  • process C can't use session/process group API because it'll break the brittle setup
  • creating a terminal for every such operation is not the best idea ever

How to set cookies in laravel 5 independently inside controller

You are going right way my friend.Now if you want retrive cookie anywhere in project just put this code $val = Cookie::get('COOKIE_NAME'); That's it! For more information how can this done click here

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))

How do you run CMD.exe under the Local System Account?

There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands.

CardView Corner Radius

NOTE: This here is a workaround if you want to achieve rounded corners at the bottom only and regular corners at the top. This will not work if you want to have different radius for all four corners of the cardview. You will have to use material cardview for it or use some third party library.

Here's what seemed to work for me:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#F9F9F9">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@drawable/profile_bg"/>

    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:id="@+id/cvProfileHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="32dp">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:orientation="vertical"
            android:background="@drawable/profile_bg"
            android:id="@+id/llProfileHeader"
            android:gravity="center_horizontal">

            <!--Enter your code here-->

        </LinearLayout>
    
    </androidx.cardview.widget.CardView>

</RelativeLayout>

There's two cardview's in all. The second cardview is the one that will have rounded corners (on all sides as usual) and will hold all other subviews under it. The first cardview above it is also at the same level (of elevation), and has the same background but is only about half the height of the second cardview and has no rounded corners (just the usual sharp corners). This way I was able to achieve partially rounded corners on the bottom and normal corners on the top. But for all four sides, you may have to use the material cardview.

You could do the reverse of this to get rounded corners at the top and regular ones at the bottom, i.e. let the first cardview have rounded corners and the second cardview have regular corners.

Android Studio Gradle Already disposed Module

I was having this issue because gradle and Android Studio were using a different path for the jvm. In the Event Log there was an option for AS and gradle to use the same path. Selecting this and then doing an invalidate cache & restart resolved the issue for me.

Get total of Pandas column

Similar to getting the length of a dataframe, len(df), the following worked for pandas and blaze:

Total = sum(df['MyColumn'])

or alternatively

Total = sum(df.MyColumn)
print Total