Programs & Examples On #Terracotta

Terracotta is an open source JVM-level clustering software for Java developed by Terracotta, Inc.

Maven2: Missing artifact but jars are in place

I had the same problem, maven was complaining about a missing artifact, even though it existed in .m2/repository/[...]. In my case the problem was that I forgot to specify the correct repository in the pom.xml from which the package was downloaded originally (download by another project).

Adding the package repository to the pom.xml solved the problem.

<repositories>
  <repository>
    <id>SomeName</id>
    <name>SomeName</name>
    <url>http://url.to.repo</url>
  </repository>
</repositories>

Thanks Maximilianus for the hint to those "*.repositories" files in the package directory.

Decoding a Base64 string in Java

If you don't want to use apache, you can use Java8:

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

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.

R adding days to a date

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)

Python style - line continuation with strings?

I've gotten around this with

mystr = ' '.join(
        ["Why, hello there",
         "wonderful stackoverflow people!"])

in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.

CMake output/build directory

You should not rely on a hard coded build dir name in your script, so the line with ../Compile must be changed.

It's because it should be up to user where to compile.

Instead of that use one of predefined variables: http://www.cmake.org/Wiki/CMake_Useful_Variables (look for CMAKE_BINARY_DIR and CMAKE_CURRENT_BINARY_DIR)

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Popup window in winform c#

Just create another form (let's call it formPopup) using Visual Studio. In a button handler write the following code:

var formPopup = new Form();
formPopup.Show(this); // if you need non-modal window

If you need a non-modal window use: formPopup.Show();. If you need a dialog (so your code will hang on this invocation until you close the opened form) use: formPopup.ShowDialog()

Where is Android Studio layout preview?

In case you want docked mode, (it still visible while editing the xml file), and you, by mistake, clicked and unmarked docked mode. In order to get it back you have focus on preview and click Window > Active Tool Window > Docked Mode.

Clicking HTML 5 Video element to play, pause video, breaks play button

The simplest form is to use the onclick listener:

<video height="auto" controls="controls" preload="none" onclick="this.play()">
 <source type="video/mp4" src="vid.mp4">
</video>

No jQuery or complicated Javascript code needed.

Play/Pause can be done with onclick="this.paused ? this.play() : this.pause();".

C++, how to declare a struct in a header file

Okay so three big things I noticed

  1. You need to include the header file in your class file

  2. Never, EVER place a using directive inside of a header or class, rather do something like std::cout << "say stuff";

  3. Structs are completely defined within a header, structs are essentially classes that default to public

Hope this helps!

Can I use a case/switch statement with two variables?

You could give each position on each slider a different binary value from 1 to 1000000000 and then work with the sum.

How to add composite primary key to table

alter table d add constraint pkc_Name primary key (id, code)

should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

Hide/Show Column in an HTML Table

you could use colgroups:

<table>
    <colgroup>
       <col class="visible_class"/>
       <col class="visible_class"/>
       <col class="invisible_class"/>  
    </colgroup>
    <thead>
        <tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr>
    </thead>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
    <tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

your script then could change just the desire <col> class.

How do I loop through or enumerate a JavaScript object?

It's interesting people in these answers have touched on both Object.keys() and for...of but never combined them:

var map = {well:'hello', there:'!'};
for (let key of Object.keys(map))
    console.log(key + ':' + map[key]);

You can't just for...of an Object because it's not an iterator, and for...index or .forEach()ing the Object.keys() is ugly/inefficient.
I'm glad most people are refraining from for...in (with or without checking .hasOwnProperty()) as that's also a bit messy, so other than my answer above, I'm here to say...


You can make ordinary object associations iterate! Behaving just like Maps with direct use of the fancy for...of
DEMO working in Chrome and FF (I assume ES6 only)

var ordinaryObject = {well:'hello', there:'!'};
for (let pair of ordinaryObject)
    //key:value
    console.log(pair[0] + ':' + pair[1]);

//or
for (let [key, value] of ordinaryObject)
    console.log(key + ':' + value);

So long as you include my shim below:

//makes all objects iterable just like Maps!!! YAY
//iterates over Object.keys() (which already ignores prototype chain for us)
Object.prototype[Symbol.iterator] = function() {
    var keys = Object.keys(this)[Symbol.iterator]();
    var obj = this;
    var output;
    return {next:function() {
        if (!(output = keys.next()).done)
            output.value = [output.value, obj[output.value]];
        return output;
    }};
};

Without having to create a real Map object that doesn't have the nice syntactic sugar.

var trueMap = new Map([['well', 'hello'], ['there', '!']]);
for (let pair of trueMap)
    console.log(pair[0] + ':' + pair[1]);

In fact, with this shim, if you still wanted to take advantage of Map's other functionality (without shimming them all in) but still wanted to use the neat object notation, since objects are now iterable you can now just make a Map from it!

//shown in demo
var realMap = new Map({well:'hello', there:'!'});

For those who don't like to shim, or mess with prototype in general, feel free to make the function on window instead, calling it something like getObjIterator() then;

//no prototype manipulation
function getObjIterator(obj) {
    //create a dummy object instead of adding functionality to all objects
    var iterator = new Object();

    //give it what the shim does but as its own local property
    iterator[Symbol.iterator] = function() {
        var keys = Object.keys(obj)[Symbol.iterator]();
        var output;

        return {next:function() {
            if (!(output = keys.next()).done)
                output.value = [output.value, obj[output.value]];
            return output;
        }};
    };

    return iterator;
}

Now you can just call it as an ordinary function, nothing else is affected

var realMap = new Map(getObjIterator({well:'hello', there:'!'}))

or

for (let pair of getObjIterator(ordinaryObject))

There's no reason why that wouldn't work.

Welcome to the future.

How do you get the selected value of a Spinner?

To get just the string value within the spinner use the following:

spinner.getSelectedItem().toString();

HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

$('#sel').val('bike');

When use getOne and findOne methods Spring Data JPA

The basic difference is that getOne is lazy loaded and findOne is not.

Consider the following example:

public static String NON_EXISTING_ID = -1;
...
MyEntity getEnt = myEntityRepository.getOne(NON_EXISTING_ID);
MyEntity findEnt = myEntityRepository.findOne(NON_EXISTING_ID);

if(findEnt != null) {
     findEnt.getText(); // findEnt is null - this code is not executed
}

if(getEnt != null) {
     getEnt.getText(); // Throws exception - no data found, BUT getEnt is not null!!!
}

How to delete node from XML file using C#

DocumentElement is the root node of the document so childNodes[1] doesn't exist in that document. childNodes[0] would be the <Settings> node

Proper way to make HTML nested list?

Option 2 is correct.

The nested list should be inside a <li> element of the list in which it is nested.

Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.

Link to the HTML5 W3C ul spec: HTML5 ul. Note that a ul element may contain exactly zero or more li elements. The same applies to HTML5 ol. The description list (HTML5 dl) is similar, but allows both dt and dd elements.

More Notes:

  • dl = definition list.
  • ol = ordered list (numbers).
  • ul = unordered list (bullets).

Create database from command line

Try:

sudo -u postgres psql -c 'create database test;'

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

How to check if a file is empty in Bash?

Easiest way for checking file is empty or not:

if [ -s /path-to-file/filename.txt ]
then
     echo "File is not empty"
else
     echo "File is empty"
fi

You can also write it on single line:

[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

How do I alter the position of a column in a PostgreSQL database table?

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.

SELECT DISTINCT on one column

The simplest solution would be to use a subquery for finding the minimum ID matching your query. In the subquery you use GROUP BY instead of DISTINCT:

SELECT * FROM [TestData] WHERE [ID] IN (
   SELECT MIN([ID]) FROM [TestData]
   WHERE [SKU] LIKE 'FOO-%'
   GROUP BY [PRODUCT]
)

How to get a microtime in Node.js?

To work with more precision than Date.now(), but with milliseconds in float precision:

function getTimeMSFloat() {
    var hrtime = process.hrtime();
    return ( hrtime[0] * 1000000 + hrtime[1] / 1000 ) / 1000;
}

Highlighting Text Color using Html.fromHtml() in Android?

To make part of your text underlined and colored

in your strings.xml

<string name="text_with_colored_underline">put the text here and &lt;u>&lt;font color="#your_hexa_color">the underlined colored part here&lt;font>&lt;u></string>

then in the activity

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));

and for clickable links:

<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>

and in your activity:

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Should work for any collection except Map, but it's easy to support, too. Modify code to pass these 3 chars as arguments if needed.

static <T> String seqToString(Iterable<T> items) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    boolean needSeparator = false;
    for (T x : items) {
        if (needSeparator)
            sb.append(' ');
        sb.append(x.toString());
        needSeparator = true;
    }
    sb.append(']');
    return sb.toString();
}

Multiple radio button groups in MVC 4 Razor

You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B

Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);

At View , you can foreach Keys in dataMap and process your action

Removing pip's cache?

(pip maintainer here!)

The specific issue of "installing the wrong version due to caching" issue mentioned in the question was fixed in pip 1.4 (back in 2013!):

Fix a number of issues related to cleaning up and not reusing build directories. (#413, #709, #634, #602, #939, #865, #948)

Since pip 6.0 (back in 2014!), pip install, pip download and pip wheel commands can be told to avoid using the cache with the --no-cache-dir option. (eg: pip install --no-cache-dir <package>)

Since pip 10.0 (back in 2018!), a pip config command was added, which can be used to configure pip to always ignore the cache -- pip config set global.cache-dir false configures pip to not use the cache "globally" (i.e. in all commands).

Since pip 20.1, pip has a pip cache command to manage the contents of pip's cache.

  • pip cache purge removes all the wheel files in the cache.
  • pip cache remove matplotlib selectively removes files related to a matplotlib from the cache.

In summary, pip provides a lot of ways to tweak how it uses the cache:

  • pip install --no-cache-dir <package>: install a package without using the cache, for just this run.
  • pip config set global.cache-dir false: configure pip to not use the cache "globally" (in all commands)
  • pip cache remove matplotlib: removes all wheel files related to matplotlib from pip's cache.
  • pip cache purge: to clear all files from pip's cache.

Use cell's color as condition in if statement (function)

I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL formula, but (at least as of Excel 2003), it doesn't return the cell's color.

It would be pretty easy to implement with VBA:

Public Function myColor(r As Range) As Integer
    myColor = r.Interior.ColorIndex
End Function

Then in the worksheet:

=mycolor(A1)

How do I add a placeholder on a CharField in Django?

Most of the time I just wish to have all placeholders equal to the verbose name of the field defined in my models

I've added a mixin to easily do this to any form that I create,

class ProductForm(PlaceholderMixin, ModelForm):
    class Meta:
        model = Product
        fields = ('name', 'description', 'location', 'store')

And

class PlaceholderMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        field_names = [field_name for field_name, _ in self.fields.items()]
        for field_name in field_names:
            field = self.fields.get(field_name)
            field.widget.attrs.update({'placeholder': field.label})

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

Array to Collection: Optimized code

Arrays.asList(array);    

Example:

 List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

See Arrays.asList class documentation.

Java: Integer equals vs. ==

Integer refers to the reference, that is, when comparing references you're comparing if they point to the same object, not value. Hence, the issue you're seeing. The reason it works so well with plain int types is that it unboxes the value contained by the Integer.

May I add that if you're doing what you're doing, why have the if statement to begin with?

mismatch = ( cdiCt != null && cdsCt != null && !cdiCt.equals( cdsCt ) );

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

How to view the committed files you have not pushed yet?

git diff HEAD origin/master

Where origin is the remote repository and master is the default branch where you will push. Also, do a git fetch before the diff so that you are not diffing against a stale origin/master.

P.S. I am also new to git, so in case the above is wrong, please rectify.

jQuery remove all list items from an unordered list

As noted by others, $('ul').empty() works fine, as does:

$('ul li').remove();

JS Fiddle demo.

What does the CSS rule "clear: both" do?

Mr. Alien's answer is perfect, but anyway I don't recommend to use <div class="clear"></div> because it just a hack which makes your markup dirty. This is useless empty div in terms of bad structure and semantic, this also makes your code not flexible. In some browsers this div causes additional height and you have to add height: 0; which even worse. But real troubles begin when you want to add background or border around your floated elements - it just will collapse because web was designed badly. I do recommend to wrap floated elements into container which has clearfix CSS rule. This is hack as well, but beautiful, more flexible to use and readable for human and SEO robots.

Why do we need virtual functions in C++?

The problem with explanations to virtual functions, is that they don't explain how it is used in practice, and how it helps with maintainability. I've created a virtual function tutorial which people have already found very useful. Plus, it's based on a battlefield premise, which makes it a bit more exciting: https://nrecursions.blogspot.com/2015/06/so-why-do-we-need-virtual-functions.html.

Consider this battlefield application:
enter image description here

#include "iostream"

//This class is created by Gun1's company
class Gun1 {public: void fire() {std::cout<<"gun1 firing now\n";}};
//This class is created by Gun2's company
class Gun2 {public: void shoot() {std::cout<<"gun2 shooting now\n";}};

//We create an abstract class to interface with WeaponController
class WeaponsInterface {
 public:
 virtual void shootTarget() = 0;
};

//A wrapper class to encapsulate Gun1's shooting function
class WeaponGun1 : public WeaponsInterface {
 private:
 Gun1* g;

 public:
 WeaponGun1(): g(new Gun1()) {}
 ~WeaponGun1() { delete g;}
 virtual void shootTarget() { g->fire(); }
};

//A wrapper class to encapsulate Gun2's shooting function
class WeaponGun2 : public WeaponsInterface {
 private:
 Gun2* g;

 public:
 WeaponGun2(): g(new Gun2()) {}
 ~WeaponGun2() { delete g;}
 virtual void shootTarget() { g->shoot(); }
};

class WeaponController {
 private:
 WeaponsInterface* w;
 WeaponGun1* g1;
 WeaponGun2* g2;
 public:
 WeaponController() {g1 = new WeaponGun1(); g2 = new WeaponGun2(); w = g1;}
 ~WeaponController() {delete g1; delete g2;}
 void shootTarget() { w->shootTarget();}
 void changeGunTo(int gunNumber) {//Virtual functions makes it easy to change guns dynamically
   switch(gunNumber) {
     case 1: w = g1; break;
     case 2: w = g2; break;
   }
 }
};


class BattlefieldSoftware {
 private:
 WeaponController* wc;
 public:
 BattlefieldSoftware() : wc(new WeaponController()) {}
 ~BattlefieldSoftware() { delete wc; }

 void shootTarget() { wc->shootTarget(); }
 void changeGunTo(int gunNumber) {wc->changeGunTo(gunNumber); }
};


int main() {
 BattlefieldSoftware* bf = new BattlefieldSoftware();
 bf->shootTarget();
 for(int i = 2; i > 0; i--) {
     bf->changeGunTo(i);
     bf->shootTarget();
 }
 delete bf;
}

I encourage you to first read the post on the blog to get the gist of why the wrapper classes were created.

As visible in the image, there are various guns/missiles that can be connected to a battlefield software, and commands can be issued to those weapons, to fire or re-calibrate etc. The challenge here is to be able to change/replace the guns/missiles without having to make changes to the blue battlefield software, and to be able to switch between weapons during runtime, without having to make changes in the code and re-compile.

The code above shows how the problem is solved, and how virtual functions with well-designed wrapper classes can encapsulate functions and help in assigning derived class pointers during runtime. The creation of class WeaponGun1 ensures that you've completely separated the handling of Gun1 into the class. Whatever changes you do to Gun1, you'll only have to make changes in WeaponGun1, and have the confidence that no other class is affected.

Because of WeaponsInterface class, you can now assign any derived class to the base class pointer WeaponsInterface and because it's functions are virtual, when you call WeaponsInterface's shootTarget, the derived class shootTarget gets invoked.

Best part is, you can change guns during runtime (w=g1 and w=g2). This is the main advantage of virtual functions and this is why we need virtual functions.

So no more necessity to comment out code in various places when changing guns. It's now a simple and clean procedure, and adding more gun classes is also easier because we just have to create a new WeaponGun3 or WeaponGun4 class and we can be confident that it won't mess up BattlefieldSoftware's code or WeaponGun1/WeaponGun2's code.

How to enable SOAP on CentOS

After hours of searching I think my problem was that command yum install php-soap installs the latest version of soap for the latest php version.

My php version was 7.027, but latest php version is 7.2 so I had to search for the right soap version and finaly found it HERE!

yum install rh-php70-php-soap

Now php -m | grep -i soap works, Output: soap

Do not forget to restart httpd service.

Error when deploying an artifact in Nexus

In the rare event that you need to redeploy the SAME STABLE artifact to Nexus, it will fail by default. If you then delete the artifact from Nexus (via the web interface) for the purpose of deploying it again, the deploy will still fail, since just removing the e.g. jar or pom does not clear other files still laying around in the directory. You need to log onto the box and delete the directory in its entirety.

Should I use PATCH or PUT in my REST API?

I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)

according to the RFC5789 (https://tools.ietf.org/html/rfc5789)

The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Also, in more details,

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it
also MAY have side effects on other resources; i.e., new resources
may be created, or existing ones modified, by the application of a
PATCH.

PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.

Clients need to choose when to use PATCH rather than PUT. For
example, if the patch document size is larger than the size of the
new resource data that would be used in a PUT, then it might make
sense to use PUT instead of PATCH. A comparison to POST is even more difficult, because POST is used in widely varying ways and can
encompass PUT and PATCH-like operations if the server chooses. If
the operation does not modify the resource identified by the Request- URI in a predictable way, POST should be considered instead of PATCH
or PUT.

The response code for PATCH is

The 204 response code is used because the response does not carry a message body (which a response with the 200 code would have). Note that other success codes could be used as well.

also refer thttp://restcookbook.com/HTTP%20Methods/patch/

Caveat: An API implementing PATCH must patch atomically. It MUST not be possible that resources are half-patched when requested by a GET.

How can I multiply all items in a list together with Python?

You can use:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

See reduce and operator.mul documentations for an explanation.

You need the import functools line in Python 3+.

Extract text from a string

Using -replace

 $string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
 $program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
 $program

SUB RAD MSD 50R III

Best C++ IDE or Editor for Windows

There are the free "Express" versions of Visual Studio. Given that you like Visual Studio and that the "Express" editions are free, there is no reason to use any other editor.

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

Is there a performance difference between i++ and ++i in C?

In C, the compiler can generally optimize them to be the same if the result is unused.

However, in C++ if using other types that provide their own ++ operators, the prefix version is likely to be faster than the postfix version. So, if you don't need the postfix semantics, it is better to use the prefix operator.

How to fetch the row count for all tables in a SQL SERVER database

I would make a minor change to Frederik's solution. I would use the sp_spaceused system stored procedure which will also include data and index sizes.


declare c_tables cursor fast_forward for 
select table_name from information_schema.tables 

open c_tables 
declare @tablename varchar(255) 
declare @stmt nvarchar(2000) 
declare @rowcount int 
fetch next from c_tables into @tablename 

while @@fetch_status = 0 
begin 

    select @stmt = 'sp_spaceused ' + @tablename 

    exec sp_executesql @stmt

    fetch next from c_tables into @tablename 

end 

close c_tables 
deallocate c_tables 

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

How to label scatterplot points by name?

None of these worked for me. I'm on a mac using Microsoft 360. I found this which DID work: This workaround is for Excel 2010 and 2007, it is best for a small number of chart data points.

Click twice on a label to select it. Click in formula bar. Type = Use your mouse to click on a cell that contains the value you want to use. The formula bar changes to perhaps =Sheet1!$D$3

Repeat step 1 to 5 with remaining data labels.

Simple

Declaring an enum within a class

I prefer following approach (code below). It solves the "namespace pollution" problem, but also it is much more typesafe (you can't assign and even compare two different enumerations, or your enumeration with any other built-in types etc).

struct Color
{
    enum Type
    {
        Red, Green, Black
    };
    Type t_;
    Color(Type t) : t_(t) {}
    operator Type () const {return t_;}
private:
   //prevent automatic conversion for any other built-in types such as bool, int, etc
   template<typename T>
    operator T () const;
};

Usage:

Color c = Color::Red;
switch(c)
{
   case Color::Red:
     //????????? ???
   break;
}
Color2 c2 = Color2::Green;
c2 = c; //error
c2 = 3; //error
if (c2 == Color::Red ) {} //error
If (c2) {} error

I create macro to facilitate usage:

#define DEFINE_SIMPLE_ENUM(EnumName, seq) \
struct EnumName {\
   enum type \
   { \
      BOOST_PP_SEQ_FOR_EACH_I(DEFINE_SIMPLE_ENUM_VAL, EnumName, seq)\
   }; \
   type v; \
   EnumName(type v) : v(v) {} \
   operator type() const {return v;} \
private: \
    template<typename T> \
    operator T () const;};\

#define DEFINE_SIMPLE_ENUM_VAL(r, data, i, record) \
    BOOST_PP_TUPLE_ELEM(2, 0, record) = BOOST_PP_TUPLE_ELEM(2, 1, record),

Usage:

DEFINE_SIMPLE_ENUM(Color,
             ((Red, 1))
             ((Green, 3))
             )

Some references:

  1. Herb Sutter, Jum Hyslop, C/C++ Users Journal, 22(5), May 2004
  2. Herb Sutter, David E. Miller, Bjarne Stroustrup Strongly Typed Enums (revision 3), July 2007

How To: Best way to draw table in console app (C#)

I wanted variable-width columns, and I didn't particularly care about the box characters. Also, I needed to print some extra information for each row.

So in case anyone else needs that, I'll save you few minutes:

public class TestTableBuilder
{

    public interface ITextRow
    {
        String Output();
        void Output(StringBuilder sb);
        Object Tag { get; set; }
    }

    public class TableBuilder : IEnumerable<ITextRow>
    {
        protected class TextRow : List<String>, ITextRow
        {
            protected TableBuilder owner = null;
            public TextRow(TableBuilder Owner)
            {
                owner = Owner;
                if (owner == null) throw new ArgumentException("Owner");
            }
            public String Output()
            {
                StringBuilder sb = new StringBuilder();
                Output(sb);
                return sb.ToString();
            }
            public void Output(StringBuilder sb)
            {
                sb.AppendFormat(owner.FormatString, this.ToArray());
            }
            public Object Tag { get; set; }
        }

        public String Separator { get; set; }

        protected List<ITextRow> rows = new List<ITextRow>();
        protected List<int> colLength = new List<int>();

        public TableBuilder()
        {
            Separator = "  ";
        }

        public TableBuilder(String separator)
            : this()
        {
            Separator = separator;
        }

        public ITextRow AddRow(params object[] cols)
        {
            TextRow row = new TextRow(this);
            foreach (object o in cols)
            {
                String str = o.ToString().Trim();
                row.Add(str);
                if (colLength.Count >= row.Count)
                {
                    int curLength = colLength[row.Count - 1];
                    if (str.Length > curLength) colLength[row.Count - 1] = str.Length;
                }
                else
                {
                    colLength.Add(str.Length);
                }
            }
            rows.Add(row);
            return row;
        }

        protected String _fmtString = null;
        public String FormatString
        {
            get
            {
                if (_fmtString == null)
                {
                    String format = "";
                    int i = 0;
                    foreach (int len in colLength)
                    {
                        format += String.Format("{{{0},-{1}}}{2}", i++, len, Separator);
                    }
                    format += "\r\n";
                    _fmtString = format;
                }
                return _fmtString;
            }
        }

        public String Output()
        {
            StringBuilder sb = new StringBuilder();
            foreach (TextRow row in rows)
            {
                row.Output(sb);
            }
            return sb.ToString();
        }

        #region IEnumerable Members

        public IEnumerator<ITextRow> GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        #endregion
    }



    static void Main(String[] args)
    {
        TableBuilder tb = new TableBuilder();
        tb.AddRow("When", "ID", "Name");
        tb.AddRow("----", "--", "----");

        tb.AddRow(DateTime.Now, "1", "Name1");
        tb.AddRow(DateTime.Now, "1", "Name2");

        Console.Write(tb.Output());
        Console.WriteLine();

        // or

        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (ITextRow tr in tb)
        {
            tr.Output(sb);
            if (i++ > 1) sb.AppendLine("more stuff per line");
        }
        Console.Write(sb.ToString());
    }
}

Output:

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
2/4/2013 8:37:44 PM  1   Name2

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
more stuff per line
2/4/2013 8:37:44 PM  1   Name2
more stuff per line

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

After trial and error comparing the using statements of my controller and the Asp.Net Template controller

using System.Web;

Solved the problem for me. You are also going to need to add:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

To use GetUserManager method.

Microsoft couldn't find a way to resolve this automatically with right click and resolve like other missing using statements?

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

How does the "this" keyword work?

In pseudoclassical terms, the way many lectures teach the 'this' keyword is as an object instantiated by a class or object constructor. Each time a new object is constructed from a class, imagine that under the hood a local instance of a 'this' object is created and returned. I remember it taught like this:

function Car(make, model, year) {
var this = {}; // under the hood, so to speak
this.make = make;
this.model = model;
this.year = year;
return this; // under the hood
}

var mycar = new Car('Eagle', 'Talon TSi', 1993);
// ========= under the hood
var this = {};
this.make = 'Eagle';
this.model = 'Talon TSi';
this.year = 1993;
return this;

Core Data: Quickest way to delete all instances of an entity

Swift 3 solution with iOS 9 'NSBatchDeleteRequest' and fallback to earlier iOS versions implemented as an extension on 'NSManagedObjectContext'. Apple reference https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html

extension NSManagedObjectContext {
    func batchDeleteEntities<T: NSManagedObject>(ofType type: T.Type) throws {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: type.self))
        if #available(iOS 9.0, *) {
            let request = NSBatchDeleteRequest(fetchRequest: fetchRequest)
            let result = try execute(request) as? NSBatchDeleteResult
            if let objectIDArray = result?.result as? [NSManagedObjectID] {
                let changes = [NSDeletedObjectsKey: objectIDArray]
                NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [self])
            }
        } else {
            fetchRequest.includesPropertyValues = false
            let results = try fetch(fetchRequest)
            if let actualResults = results as? [NSManagedObject], !actualResults.isEmpty {
                actualResults.forEach { delete($0) }
            }
        }
    }
}

Purpose of __repr__ method?

Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.

Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/

What is the difference between a Docker image and a container?

From my article on Automating Docker Deployments:

Docker Images vs. Containers

In Dockerland, there are images and there are containers. The two are closely related, but distinct. For me, grasping this dichotomy has clarified Docker immensely.

What's an Image?

An image is an inert, immutable, file that's essentially a snapshot of a container. Images are created with the build command, and they'll produce a container when started with run. Images are stored in a Docker registry such as registry.hub.docker.com. Because they can become quite large, images are designed to be composed of layers of other images, allowing a minimal amount of data to be sent when transferring images over the network.

Local images can be listed by running docker images:

REPOSITORY                TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                    13.10               5e019ab7bf6d        2 months ago        180 MB
ubuntu                    14.04               99ec81b80c55        2 months ago        266 MB
ubuntu                    latest              99ec81b80c55        2 months ago        266 MB
ubuntu                    trusty              99ec81b80c55        2 months ago        266 MB
<none>                    <none>              4ab0d9120985        3 months ago        486.5 MB

Some things to note:

  1. IMAGE ID is the first 12 characters of the true identifier for an image. You can create many tags of a given image, but their IDs will all be the same (as above).
  2. VIRTUAL SIZE is virtual because it's adding up the sizes of all the distinct underlying layers. This means that the sum of all the values in that column is probably much larger than the disk space used by all of those images.
  3. The value in the REPOSITORY column comes from the -t flag of the docker build command, or from docker tag-ing an existing image. You're free to tag images using a nomenclature that makes sense to you, but know that docker will use the tag as the registry location in a docker push or docker pull.
  4. The full form of a tag is [REGISTRYHOST/][USERNAME/]NAME[:TAG]. For ubuntu above, REGISTRYHOST is inferred to be registry.hub.docker.com. So if you plan on storing your image called my-application in a registry at docker.example.com, you should tag that image docker.example.com/my-application.
  5. The TAG column is just the [:TAG] part of the full tag. This is unfortunate terminology.
  6. The latest tag is not magical, it's simply the default tag when you don't specify a tag.
  7. You can have untagged images only identifiable by their IMAGE IDs. These will get the <none> TAG and REPOSITORY. It's easy to forget about them.

More information on images is available from the Docker documentation and glossary.

What's a container?

To use a programming metaphor, if an image is a class, then a container is an instance of a class—a runtime object. Containers are hopefully why you're using Docker; they're lightweight and portable encapsulations of an environment in which to run applications.

View local running containers with docker ps:

CONTAINER ID        IMAGE                               COMMAND                CREATED             STATUS              PORTS                    NAMES
f2ff1af05450        samalba/docker-registry:latest      /bin/sh -c 'exec doc   4 months ago        Up 12 weeks         0.0.0.0:5000->5000/tcp   docker-registry

Here I'm running a dockerized version of the docker registry, so that I have a private place to store my images. Again, some things to note:

  1. Like IMAGE ID, CONTAINER ID is the true identifier for the container. It has the same form, but it identifies a different kind of object.
  2. docker ps only outputs running containers. You can view all containers (running or stopped) with docker ps -a.
  3. NAMES can be used to identify a started container via the --name flag.

How to avoid image and container buildup

One of my early frustrations with Docker was the seemingly constant buildup of untagged images and stopped containers. On a handful of occasions this buildup resulted in maxed out hard drives slowing down my laptop or halting my automated build pipeline. Talk about "containers everywhere"!

We can remove all untagged images by combining docker rmi with the recent dangling=true query:

docker images -q --filter "dangling=true" | xargs docker rmi

Docker won't be able to remove images that are behind existing containers, so you may have to remove stopped containers with docker rm first:

docker rm `docker ps --no-trunc -aq`

These are known pain points with Docker and may be addressed in future releases. However, with a clear understanding of images and containers, these situations can be avoided with a couple of practices:

  1. Always remove a useless, stopped container with docker rm [CONTAINER_ID].
  2. Always remove the image behind a useless, stopped container with docker rmi [IMAGE_ID].

Convert bytes to bits in python

The other answers here provide the bits in big-endian order ('\x01' becomes '00000001')

In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:

def bits_little_endian_from_bytes(s):
    return ''.join(bin(ord(x))[2:].rjust(8,'0')[::-1] for x in s)

And for the other direction:

def bytes_from_bits_little_endian(s):
    return ''.join(chr(int(s[i:i+8][::-1], 2)) for i in range(0, len(s), 8))

Transmitting newline character "\n"

late to the party, but if anyone comes across this, javascript has a encodeURI method

SQL Query Where Date = Today Minus 7 Days

Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()

Batch file to move files to another directory

/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting

Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get

Try:

move files\*.txt \ 

Edit: Try:

move \files\*.txt \ 

Edit 2:

move C:\files\*.txt C:\txt

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

jQuery: select an element's class and id at the same time?

In the end the same rules as for css apply.

So I think this reference could be of some valuable use.

adding noise to a signal in python

You can generate a noise array, and add it to your signal

import numpy as np

noise = np.random.normal(0,1,100)

# 0 is the mean of the normal distribution you are choosing from
# 1 is the standard deviation of the normal distribution
# 100 is the number of elements you get in array noise

Change bullets color of an HTML list without using span

I managed this without adding markup, but instead using li:before. This obviously has all the limitations of :before (no old IE support), but it seems to work with IE8, Firefox and Chrome after some very limited testing. The bullet style is also limited by what's in unicode.

_x000D_
_x000D_
li {_x000D_
  list-style: none;_x000D_
}_x000D_
li:before {_x000D_
  /* For a round bullet */_x000D_
  content: '\2022';_x000D_
  /* For a square bullet */_x000D_
  /*content:'\25A0';*/_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  max-width: 0;_x000D_
  max-height: 0;_x000D_
  left: -10px;_x000D_
  top: 0;_x000D_
  color: green;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo</li>_x000D_
  <li>bar</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to read a file and write into a text file?

It far easier to use the scripting runtime which is installed by default on Windows

Just go project Reference and check Microsoft Scripting Runtime and click OK.

Then you can use this code which is way better than the default file commands

Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

As for what is wrong with your original code here you are reading each line of the text file.

Input #iFileNo, sFileText

Then here you write it out

Write #iFileNo, sFileText

sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.

So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.

Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo

iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo

Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).

If you need to process the incoming data then you need to do something like this.

Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection

iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
  C.Add sFileText
Loop
Close #iFileNo

For Each vTemp in C
     Process vTemp
Next sTemp

iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
   Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

How to round up with excel VBA round()?

I am introducing Two custom library functions to be used in vba, which will serve the purpose of rounding the double value instead of using WorkSheetFunction.RoundDown and WorkSheetFunction.RoundUp

Function RDown(Amount As Double, digits As Integer) As Double
    RDown = Int((Amount + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function

Function RUp(Amount As Double, digits As Integer) As Double
    RUp = RDown(Amount + (5 / (10 ^ (digits + 1))), digits)
End Function

Thus function Rdown(2878.75 * 31.1,2) will return 899529.12 and function RUp(2878.75 * 31.1,2) will return 899529.13 Whereas The function Rdown(2878.75 * 31.1,-3) will return 89000 and function RUp(2878.75 * 31.1,-3) will return 90000

How to Correctly Check if a Process is running and Stop it

Thanks @Joey. It's what I am looking for.

I just bring some improvements:

  • to take into account multiple processes
  • to avoid reaching the timeout when all processes have terminated
  • to package the whole in a function

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    $processList = Get-Process $processName -ErrorAction SilentlyContinue
    if ($processList) {
        # Try gracefully first
        $processList.CloseMainWindow() | Out-Null

        # Wait until all processes have terminated or until timeout
        for ($i = 0 ; $i -le $timeout; $i ++){
            $AllHaveExited = $True
            $processList | % {
                $process = $_
                If (!$process.HasExited){
                    $AllHaveExited = $False
                }                    
            }
            If ($AllHaveExited){
                Return
            }
            sleep 1
        }
        # Else: kill
        $processList | Stop-Process -Force        
    }
}

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

How to access to a child method from the parent in vue.js

To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

this.$refs.childMethod()

And from the another child I've called the root method:

this.$root.theRootMethod()

It worked for me.

Java: Sending Multiple Parameters to Method

You can use varargs

public function yourFunction(Parameter... parameters)

See also

Java multiple arguments dot notation - Varargs

Custom ImageView with drop shadow

Use this class to draw shadow on bitmaps

public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mIconSize = Utils.convertDpToPixel(context,63);
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }



    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}

How can I return the current action in an ASP.NET MVC view?

In the RC you can also extract route data like the action method name like this

ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue

Update for MVC 3

ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue

Update for MVC 4

ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]

Update for MVC 4.5

ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]

Populating a razor dropdownlist from a List<object> in MVC

One way might be;

    <select name="listbox" id="listbox">
    @foreach (var item in Model)
           {

                   <option value="@item.UserRoleId">
                      @item.UserRole 
                   </option>                  
           }
    </select>

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

Numpy where function multiple conditions

One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.

When we use 'and':

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)

Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When we use Ampersand(&):

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)

Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')

And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.

UPDATE

A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.

Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".

Case1:

np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)

Since there are no brackets here, the bitwise operator(&) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, & is given precedence over < or > operators. Here's the table from from lowest precedence to highest precedence.

enter image description here

It's not even performing the < and > operation and being asked to perform a logical AND operation. So that's why it gives that error.

One can check out the following link to learn more about: operator precedence

Now to Case 2:

If you do use the bracket, you clearly see what happens.

np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False,  True,  True,  True, False,  True, False,  True])) & (array([ True,  True,  True, False,  True,  True,  True, False])), 'yo', ar)

Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:

np.where( array([False,  True,  True, False, False,  True, False, False]),  'yo', ar)

And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).

That's all. I hope I explained the query well.

How do I change the text of a span element using JavaScript?

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
    $("#myspan").text("This is span");
  });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="myspan"> hereismytext </span>
_x000D_
_x000D_
_x000D_

user text() to change span text.

Bash or KornShell (ksh)?

Available in most UNIX system, ksh is standard-comliant, clearly designed, well-rounded. I think books,helps in ksh is enough and clear, especially the O'Reilly book. Bash is a mass. I keep it as root login shell for Linux at home only.

For interactive use, I prefer zsh on Linux/UNIX. I run scripts in zsh, but I'll test most of my scripts, functions in AIX ksh though.

Throwing exceptions in a PHP Try Catch block

To rethrow do

 throw $e;

not the message.

Excel telling me my blank cells aren't blank

If you don't have formatting or formulas you want to keep, you can try saving your file as a tab delimited text file, closing it, and reopening it with excel. This worked for me.

How to convert Blob to String and String to Blob in java

To convert Blob to String in Java:

byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Change x axes scale in matplotlib

Try using matplotlib.pyplot.ticklabel_format:

import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

How would I access variables from one class to another?

Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.

class a:
    def func1(self):
        a.var1 = "Stack "

class b:
    def func2(self):
        b.var2 = "Overflow"

class c(a,b):
    def func3(self):
        c.var3 = a.var1 + b.var2
        print(c.var3)

a().func1()
b().func2()
c().func3()

HTTP Ajax Request via HTTPS Page

Still, this can be done with the following steps:

  1. send an https ajax request to your web-site (the same domain)

    jQuery.ajax({
        'url'      : '//same_domain.com/ajax_receiver.php',
        'type'     : 'get',
        'data'     : {'foo' : 'bar'},
        'success'  : function(response) {
            console.log('Successful request');
        }
    }).fail(function(xhr, err) {
        console.error('Request error');
    });
    
  2. get ajax request, for example, by php, and make a CURL get request to any desired website via http.

    use linslin\yii2\curl;
    $curl = new curl\Curl();
    $curl->get('http://example.com');
    

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

Comparison of C++ unit test frameworks

I've just pushed my own framework, CATCH, out there. It's still under development but I believe it already surpasses most other frameworks. Different people have different criteria but I've tried to cover most ground without too many trade-offs. Take a look at my linked blog entry for a taster. My top five features are:

  • Header only
  • Auto registration of function and method based tests
  • Decomposes standard C++ expressions into LHS and RHS (so you don't need a whole family of assert macros).
  • Support for nested sections within a function based fixture
  • Name tests using natural language - function/ method names are generated

It also has Objective-C bindings. The project is hosted on Github

Java, return if trimmed String in List contains String

You may be able to use an approximate string matching library to do this, e.g. SecondString, but that is almost certainly overkill - just use one of the for-loop answers provided instead.

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How to change ProgressBar's progress indicator color in Android

With the Material Components Library you can use the LinearProgressIndicator with the app:indicatorColor attribute to change the color:

  <com.google.android.material.progressindicator.LinearProgressIndicator
      app:indicatorColor="@color/..."
      app:trackThickness="..."
      app:trackColor="@color/..."
      />

enter image description here

Note: it requires at least the version 1.3.0-alpha04.

With the ProgressBar you can override the color using:

<ProgressBar
    android:theme="@style/CustomProgressBarTheme"
    ..>

with:

<style name="CustomProgressBarTheme">
    <item name="colorAccent">@color/primaryDarkColor</item>
</style>

enter image description here

How to convert an Array to a Set in Java

There has been a lot of great answers already, but most of them won't work with array of primitives (like int[], long[], char[], byte[], etc.)

In Java 8 and above, you can box the array with:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

Then convert to set using stream:

Stream.of(boxedArr).collect(Collectors.toSet());

Bootstrap full responsive navbar with logo or brand name text

I checked and it worked for me.

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

Make sure you're passing a selector to jQuery, not some form of data:

$( '.my-selector' )

not:

$( [ 'my-data' ] )

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

Get selected value from combo box in C# WPF

private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index

I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)

Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.

enter image description here

VBA collection: list of keys

You can create a small class to hold the key and value, and then store objects of that class in the collection.

Class KeyValue:

Public key As String
Public value As String
Public Sub Init(k As String, v As String)
    key = k
    value = v
End Sub

Then to use it:

Public Sub Test()
    Dim col As Collection, kv As KeyValue
    Set col = New Collection
    Store col, "first key", "first string"
    Store col, "second key", "second string"
    Store col, "third key", "third string"
    For Each kv In col
        Debug.Print kv.key, kv.value
    Next kv
End Sub

Private Sub Store(col As Collection, k As String, v As String)
    If (Contains(col, k)) Then
        Set kv = col(k)
        kv.value = v
    Else
        Set kv = New KeyValue
        kv.Init k, v
        col.Add kv, k
    End If
End Sub

Private Function Contains(col As Collection, key As String) As Boolean
    On Error GoTo NotFound
    Dim itm As Object
    Set itm = col(key)
    Contains = True
MyExit:
    Exit Function
NotFound:
    Contains = False
    Resume MyExit
End Function

This is of course similar to the Dictionary suggestion, except without any external dependencies. The class can be made more complex as needed if you want to store more information.

How do I prevent Conda from activating the base environment by default?

To disable auto activation of conda base environment in terminal:

conda config --set auto_activate_base false

To activate conda base environment:

conda activate

Appending to an existing string

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true

np.mean() vs np.average() in Python NumPy?

In your invocation, the two functions are the same.

average can compute a weighted average though.

Doc links: mean and average

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

How do I copy directories recursively with gulp?

Turns out that to copy a complete directory structure gulp needs to be provided with a base for your gulp.src() method.

So gulp.src( [ files ], { "base" : "." }) can be used in the structure above to copy all the directories recursively.

If, like me, you may forget this then try:

gulp.copy=function(src,dest){
    return gulp.src(src, {base:"."})
        .pipe(gulp.dest(dest));
};

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

Passing a string array as a parameter to a function java

I believe this should be the way this is done...

public void function(String [] array){
....
}

And the calling will be done like...

public void test(){
    String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
    function(stringArray);
}

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to define the css :hover state in a jQuery selector?

I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this

$("div.myclass").hover(function() {
  $(this).css("background-color","red")
});

You can change your selector as per your need.

As commented by @A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this

$(".myclass, .myclass2").hover(function(e) { 
    $(this).css("background-color",e.type === "mouseenter"?"red":"transparent") 
})

Js Fiddle Demo

How can I make content appear beneath a fixed DIV element?

#nav{
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
    margin: 0 auto;
    z-index: 9999;
    background-color: white;
}

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Check if checkbox is NOT checked on click - jQuery

Try this:

if(!$(this).is(':checked'))

demo

How to get current time in milliseconds in PHP?

This works even if you are on 32-bit PHP:

list($msec, $sec) = explode(' ', microtime());

$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'

Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.


If you need integers, 64-bit PHP is mandatory.

Then you can reuse the above code and cast to (int):

list($msec, $sec) = explode(' ', microtime());

// these parentheses are mandatory otherwise the precedence is wrong!
//                  ?                        ?
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300

Or you can use the good ol' one-liners:

$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

What is the difference between printf() and puts() in C?

In my experience, printf() hauls in more code than puts() regardless of the format string.

If I don't need the formatting, I don't use printf. However, fwrite to stdout works a lot faster than puts.

static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);

Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char) as indicated by the comments.

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

How can I delete all of my Git stashes at once?

if you want to remove the latest stash or at any particular index -

git stash drop type_your_index

> git stash list

  stash@{0}: abc
  stash@{1}: xyz
  stash@{1}: pqr

> git stash drop 0

  Dropped refs/stash@{0}

> git stash list

  stash@{0}: xyz
  stash@{1}: pqr

if you want to remove all the stash at once -

> git stash clear
>

> git stash list
>

Warning : Once done you can not revert back your stash

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>

Keep Rest of the code as it is.

How do I run a program from command prompt as a different user and as an admin

The easiest is to create a batch file (.bat) and run that as administrator.

Right click and 'Run as administrator'

Select columns in PySpark dataframe

You can use an array and unpack it inside the select:

cols = ['_2','_4','_5']
df.select(*cols).show()

How to control size of list-style-type disc in CSS?

I'm surprised that no one has mentioned the list-style-image property

ul {
    list-style-image: url('images/ico-list-bullet.png');
}

Java: How to insert CLOB into oracle database

The easiest way is to simply use the

stmt.setString(position, xml);

methods (for "small" strings which can be easily kept in Java memory), or

try {
  java.sql.Clob clob = 
    oracle.sql.CLOB.createTemporary(
      connection, false, oracle.sql.CLOB.DURATION_SESSION);

  clob.setString(1, xml);
  stmt.setClob(position, clob);
  stmt.execute();
}

// Important!
finally {
  clob.free();
}

Connection Strings for Entity Framework

Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:

<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:

var context = new Entity("EntityV2");

Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.

Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).

// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);

How about something like this:

Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection = 
    string.Format(
        "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
        contextType.Name,
        innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities; 

... with the following in your machine.config:

<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

This way, you can use a single connection string for every context in every project on the machine.

Map a network drive to be used by a service

You could us the 'net use' command:

var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);

If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2

Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).

SimpleDateFormat and locale based format string

Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat.

How can I give access to a private GitHub repository?

Struggled to find this as well.

Heres a screenshot of how to do it:

enter image description here

Search all the occurrences of a string in the entire project in Android Studio

In Android Studio on a Windows or Linux based machine use shortcut Ctrl + Shift + R to search and replace any string in the whole project.

Execute function after Ajax call is complete

You should set async = false in head. Use post/get instead of ajax.

jQuery.ajaxSetup({ async: false });

    $.post({
        url: 'api.php',
        data: 'id1=' + q + '',
        dataType: 'json',
        success: function (data) {

            id = data[0];
            vname = data[1];

        }
    });

Simple Deadlock Examples

Here's a code example from the computer science department of a university in Taiwan showing a simple java example with resource locking. That's very "real-life" relevant to me. Code below:

/**
 * Adapted from The Java Tutorial
 * Second Edition by Campione, M. and
 * Walrath, K.Addison-Wesley 1998
 */

/**
 * This is a demonstration of how NOT to write multi-threaded programs.
 * It is a program that purposely causes deadlock between two threads that
 * are both trying to acquire locks for the same two resources.
 * To avoid this sort of deadlock when locking multiple resources, all threads
 * should always acquire their locks in the same order.
 **/
public class Deadlock {
  public static void main(String[] args){
    //These are the two resource objects 
    //we'll try to get locks for
    final Object resource1 = "resource1";
    final Object resource2 = "resource2";
    //Here's the first thread.
    //It tries to lock resource1 then resource2
    Thread t1 = new Thread() {
      public void run() {
        //Lock resource 1
        synchronized(resource1){
          System.out.println("Thread 1: locked resource 1");
          //Pause for a bit, simulating some file I/O or 
          //something. Basically, we just want to give the 
          //other thread a chance to run. Threads and deadlock
          //are asynchronous things, but we're trying to force 
          //deadlock to happen here...
          try{ 
            Thread.sleep(50); 
          } catch (InterruptedException e) {}

          //Now wait 'till we can get a lock on resource 2
          synchronized(resource2){
            System.out.println("Thread 1: locked resource 2");
          }
        }
      }
    };

    //Here's the second thread.  
    //It tries to lock resource2 then resource1
    Thread t2 = new Thread(){
      public void run(){
        //This thread locks resource 2 right away
        synchronized(resource2){
          System.out.println("Thread 2: locked resource 2");
          //Then it pauses, for the same reason as the first 
          //thread does
          try{
            Thread.sleep(50); 
          } catch (InterruptedException e){}

          //Then it tries to lock resource1.  
          //But wait!  Thread 1 locked resource1, and 
          //won't release it till it gets a lock on resource2.  
          //This thread holds the lock on resource2, and won't
          //release it till it gets resource1.  
          //We're at an impasse. Neither thread can run, 
          //and the program freezes up.
          synchronized(resource1){
            System.out.println("Thread 2: locked resource 1");
          }
        }
      }
    };

    //Start the two threads. 
    //If all goes as planned, deadlock will occur, 
    //and the program will never exit.
    t1.start(); 
    t2.start();
  }
}

How do I extract data from JSON with PHP?

You can use json_decode() to convert a json string to a PHP object/array.

Eg.

Input:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Few Points to remember:

  • json_decode requires the string to be a valid json else it will return NULL.
  • In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
  • Make sure you pass in utf8 content, or json_decode may error out and just return a NULL value.

Why should hash functions use a prime number modulus?

Just to provide an alternate viewpoint there's this site:

http://www.codexon.com/posts/hash-functions-the-modulo-prime-myth

Which contends that you should use the largest number of buckets possible as opposed to to rounding down to a prime number of buckets. It seems like a reasonable possibility. Intuitively, I can certainly see how a larger number of buckets would be better, but I'm unable to make a mathematical argument of this.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

python: after installing anaconda, how to import pandas

The cool thing about anaconda is, that you can manage virtual environments for several projects. Those also have the benefit of keeping several python installations apart. This could be a problem when several installations of a module or package are interfering with each other.

Try the following:

  1. Create a new anaconda environment with user@machine:~$ conda create -n pandas_env python=2.7
  2. Activate the environment with user@machine:~$ source activate pandas_env on Linux/OSX or $ activate pandas_env on Windows. On Linux the active environment is shown in parenthesis in front of the user name in the shell. (I am not sure how windows handles this, but you can see it by typing $ conda info -e. The one with the * next to it is the active one)
  3. Type (pandas_env)user@machine:~$ conda list to show a list of all installed modules.
  4. If pandas is missing from this list, install it (while still inside the pandas_env environment) with (pandas_env)user@machine:~$ conda install pandas, as @Fiabetto suggested.
  5. Open python (pandas_env)user@machine:~$ python and try to load pandas again.

Note that now you are working in a python environment, that only knows the modules installed inside the pandas_env environment. Every time you want to use it you have to activate the environment. This might feel a little bit clunky at first, but really shines once you have to manage different versions of python (like 2.7 or 3.4) or you need a specific version of a module (like numpy 1.7).

Edit:

If this still does not work you have several options:

  1. Check if the right pandas module is found:

    `(pandas_env)user@machine:~$ python`
    Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
    >>> import imp
    >>> imp.find_module("pandas")
    (None, '/path/to/miniconda3/envs/foo/lib/python2.7/site-packages/pandas', ('', '', 5))
    
    # See what this returns on your system.
    
  2. Reinstall pandas in your environment with $ conda install -f pandas. This might help if you files have been corrupted somehow.

  3. Install pandas from a different source (using pip). To do this, create a new environment like above (make sure to pick a different name to avoid clashes here) but replace point 4 by (pandas_env)user@machine:~$ pip install pandas.
  4. Reinstall anaconda (make sure you pick the right version 32bit / 64bit depending on your OS, this can sometimes lead to problems). It could be possible, that your 'normal' and your anaconda python are clashing. As a last resort you could try to uninstall your 'normal' python before you reinstall anaconda.

Installing SetupTools on 64-bit Windows

Yes, you are correct, the issue is with 64-bit Python and 32-bit installer for setuptools.

The best way to get 64-bit setuptools installed on Windows is to download ez_setup.py to C:\Python27\Scripts and run it. It will download appropriate 64-bit .egg file for setuptools and install it for you.

Source: http://pypi.python.org/pypi/setuptools

P.S. I'd recommend against using 3rd party 64-bit .exe setuptools installers or manipulating registry

How to get div height to auto-adjust to background size?

Another, perhaps inefficient, solution would be to include the image under an img element set to visibility: hidden;. Then make the background-image of the surrounding div the same as the image.

This will set the surrounding div to the size of the image in the img element but display it as a background.

<div style="background-image: url(http://your-image.jpg);">
 <img src="http://your-image.jpg" style="visibility: hidden;" />
</div>

How to create duplicate table with new name in SQL Server 2008

I have used this query it is created new table with existing data.

Query : select * into [newtablename] from [existingtable]

Here is the link Microsoft instructions. https://docs.microsoft.com/en-us/sql/relational-databases/tables/duplicate-tables?view=sql-server-2017

Convert int to a bit array in .NET

int value = 3;

var array = Convert.ToString(value, 2).PadLeft(8, '0').ToArray();

How can I confirm a database is Oracle & what version it is using SQL?

SQL> SELECT version FROM v$instance;
VERSION
-----------------
11.2.0.3.0

How can I match a string with a regex in Bash?

shopt -s nocasematch

if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
 then exit 0 
fi

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

How can I close a login form and show the main form without my application closing?

Try this:

public void ShowMain()
    {
        if(auth()) // a method that returns true when the user exists.
        { 
            this.Close();
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
            t.Start();
        }
        else
        {
            MessageBox.Show("Invalid login details.");
        }         
    }
   [STAThread]
   public void Main()
   {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Main());

   }

You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.

One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.

Hope this helps.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

This is an informational message only. What the message is telling you is that the chromedriver executable will only accept connections from the local machine.

Most driver implementations (the Chrome driver and the IE driver for sure) create a HTTP server. The language bindings (Java, Python, Ruby, .NET, etc.) all use a JSON-over-HTTP protocol to communicate with the driver and automate the browser. Since the HTTP server is simply listening on an open port for HTTP requests generated by the language bindings, connections to the HTTP server started by the language bindings are only allowed to come from other processes on the same host. Note carefully that this limitation does not apply to connections the browser can make to outside websites; rather it simply prevents incoming connections from other websites.

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Excel VBA code to copy a specific string to clipboard

If the url is in a cell in your workbook, you can simply copy the value from that cell:

Private Sub CommandButton1_Click()
    Sheets("Sheet1").Range("A1").Copy
End Sub

(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)

If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216

After you've added the API calls below, change the code behind the button to copy to the clipboard:

Private Sub CommandButton1_Click()
    ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub

Add a new module to your workbook and paste in the following code:

Option Explicit

Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
   ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
   As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
   ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
   As Long, ByVal hMem As Long) As Long

Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096

Function ClipBoard_SetData(MyString As String)
   Dim hGlobalMemory As Long, lpGlobalMemory As Long
   Dim hClipMemory As Long, X As Long

   ' Allocate moveable global memory.
   '-------------------------------------------
   hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)

   ' Lock the block to get a far pointer
   ' to this memory.
   lpGlobalMemory = GlobalLock(hGlobalMemory)

   ' Copy the string to this global memory.
   lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)

   ' Unlock the memory.
   If GlobalUnlock(hGlobalMemory) <> 0 Then
      MsgBox "Could not unlock memory location. Copy aborted."
      GoTo OutOfHere2
   End If

   ' Open the Clipboard to copy data to.
   If OpenClipboard(0&) = 0 Then
      MsgBox "Could not open the Clipboard. Copy aborted."
      Exit Function
   End If

   ' Clear the Clipboard.
   X = EmptyClipboard()

   ' Copy the data to the Clipboard.
   hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)

OutOfHere2:

   If CloseClipboard() = 0 Then
      MsgBox "Could not close Clipboard."
   End If

End Function

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

IIS_IUSRS and IUSR permissions in IIS8

I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).

Specific User setting is specifically meant for accessing local resources.

default value for struct member in C

I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.

In C,

 struct s {
        int i;
        int j;
    };

    struct s s_instance = { 10 ,20 };

in C++ its possible to give direct value in definition of structure shown as below

struct s {
    int i;

    s(): i(10)
    {
    }
};

Calling multiple JavaScript functions on a button click

That's because, it gets returned after validateView();;

Use this:

OnClientClick="var ret = validateView();ShowDiv1(); return ret;"

how to add value to combobox item

Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.

How do I serialize an object and save it to a file in Android?

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

How to do multiline shell script in Ansible

Adding a space before the EOF delimiter allows to avoid cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF

TSQL DATETIME ISO 8601

Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.

{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.

The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.

My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.

How to Edit a row in the datatable

You can find that row with

DataRow row = table.Select("Product_id=2").FirstOrDefault();

and update it

row["Product_name"] = "cde";

How to run Pip commands from CMD

In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps

On your desktop right click Computer and select Properties

Select Advanced Systems Settings

In popup which you see select Advanced tab and then click Environment Variables

In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.

In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32

Now in my command prompt i moved to above location and gave pip install Flask

enter image description here

How to change the href for a hyperlink using jQuery

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

How can I parse a time string containing milliseconds in it with python?

I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn't support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string "2010-10-06 09:42:52.266000"

Change the jquery show()/hide() animation?

There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...

https://api.jquery.com/category/effects/

You can use slideDown just like this:

$("test").slideDown("slow");

And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.

Symfony2 Setting a default choice field selection

Setting default choice for symfony2 radio button

            $builder->add('range_options', 'choice', array(
                'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
                'data'=>'day', //set default value 
                'required'=>true,
                'empty_data'=>null,
                'multiple'=>false,
                'expanded'=> true                   
        ))

angularjs make a simple countdown

$scope.countDown = 30;
var timer;
$scope.countTimer = function () {
    var time = $timeout(function () {
         timer = setInterval(function () {
             if ($scope.countDown > 0) {
                 $scope.countDown--;
            } else {
                clearInterval(timer);
                $window.location.href = '/Logoff';
            }
            $scope.$apply();
        }, 1000);
    }, 0);
}

$scope.stop= function () {
    clearInterval(timer);
    
}

IN HTML:

<button type="submit" ng-click="countTimer()">Start</button>
<button type="submit" ng-click="stop()">Clear</button>
                 
                
              

SQL Server: combining multiple rows into one row

I believe for databases which support listagg function, you can do:

select id, issue, customfield, parentkey, listagg(stingvalue, ',') within group (order by id)
from jira.customfieldvalue
where customfield = 12534 and issue = 19602
group by id, issue, customfield, parentkey

Playing mp3 song on python

For anyone still finding this in 2020: after a search longer than I expected, I just found the simpleaudio library, which appears well-maintained, is MIT licensed, works on Linux, macOS, and Windows, and only has very few dependencies (only python3-dev and libasound2-dev on Linux).

It supports playing data directly from buffers (e.g. Numpy arrays) in-memory, has a convenient audio test function:

import simpleaudio.functionchecks as fc
fc.LeftRightCheck.run()

and you can play a file from disk as follows:

import simpleaudio as sa

wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()

Installation instructions are basically pip install simpleaudio.

curl: (60) SSL certificate problem: unable to get local issuer certificate

Try reinstalling curl in Ubuntu, and updating my CA certs with sudo update-ca-certificates --fresh which updated the certs

How to join multiple lines of file names into one with custom delimiter?

Quick Perl version with trailing slash handling:

ls -1 | perl -E 'say join ", ", map {chomp; $_} <>'

To explain:

  • perl -E: execute Perl with features supports (say, ...)
  • say: print with a carrier return
  • join ", ", ARRAY_HERE: join an array with ", "
  • map {chomp; $_} ROWS: remove from each line the carrier return and return the result
  • <>: stdin, each line is a ROW, coupling with a map it will create an array of each ROW

Get today date in google appScript

Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

How can I get the current class of a div with jQuery?

Simply by

var divClass = $("#div1").attr("class")

You can do some other stuff to manipulate element's class

$("#div1").addClass("foo"); // add class 'foo' to div1
$("#div1").removeClass("foo"); // remove class 'foo' from div1
$("#div1").toggleClass("foo"); // toggle class 'foo'

OperationalError: database is locked

I've got the same error! One of the reasons was the DB connection was not closed. Therefore, check for unclosed DB connections. Also, check if you have committed the DB before closing the connection.

How stable is the git plugin for eclipse?

EGit is still in eclipse incubation. You can install it using the Eclipse update manager.

  1. Select Help -> Install New Software...
  2. You probably do not have the JGit update URL in your list of sites so in the 'Work with:' field enter this url: http://www.jgit.org/updates
  3. Click Add...
  4. You should now see Eclipse Git Plugin - Integration Build (Incubation) listed as available software to install. Check it and click Next.
  5. Click Next and agree to the license and it should be installed.

Image resolution for mdpi, hdpi, xhdpi and xxhdpi

Your inputs lack one important information of device dimension. Suppose now popular phone is 6 inch(the diagonal of the display), you will have following results

enter image description here

DPI: Dots per inch - number of dots(pixels) per segment(line) of 1 inch. DPI=Diagonal/Device size

Scaling Ratio= Real DPI/160. 160 is basic density (MHDPI)

DP: (Density-independent Pixel)=1/160 inch, think of it as a measurement unit

how to create a list of lists

Create your list before your loop, else it will be created at each loop.

>>> list1 = []
>>> for i in range(10) :
...   list1.append( range(i,10) )
...
>>> list1
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]]

ImportError in importing from sklearn: cannot import name check_build

no need to uninstall & then re-install sklearn

try this:

from sklearn.model_selection import train_test_split

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

C++ floating point to integer type conversions

Normal way is to:

float f = 3.4;
int n = static_cast<int>(f);

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

If you have ever used a proxy, VPN, etc(or may not, I am not sure).....Then the solution below may help you...I don't know why (and if anybody can tell me why, I will appreciate that), but it works, pefectly. Have a try when you totally feel desperate about that issue.

Come to your project, and open gradle-wrapper.properties or gradle.properties, comment out these codes about proxy:

#systemProp.http.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.http.proxyHost=127.0.0.1
#systemProp.http.proxyPort=1081
#systemProp.https.nonProxyHosts=118.89.144.241|47.112.105.125
#systemProp.https.proxyHost=127.0.0.1
#systemProp.https.proxyPort=1081

enter image description here

Then, it might work.

PS: I met this problem when I try to use dataBinding library, and when I added the code

buildFeatures {
        dataBinding true
    }

into gradle as the guide told me and Syns the project, I got such an error:"Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve ......". Finally I did what I described above, and I successed. What I experience may give you a hint, so I post the solution here and hope it might help.

Send POST data using XMLHttpRequest

Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:

function post(path, data, callback) {
    "use strict";
    var request = new XMLHttpRequest();

    if (path === "") {
        path = "/";
    }
    request.open('POST', path, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.onload = function (d) {
        callback(d.currentTarget.response);
    };
    request.send(serialize(data));
}

You can you it like so:

post("", {orem: ipsum, name: binny}, function (response) {
    console.log(respone);
})

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

How to get primary key column in Oracle?

Try This Code Here I created a table for get primary key column in oracle which is called test and then query

create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner  ORDER BY cols.table_name, cols.position;

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

When you call loadTeachers() on DOMReady the context of this will not be the #CourseSelect element.

You can fix this by triggering a change() event on the #CourseSelect element on load of the DOM:

$("#CourseSelect").change(loadTeachers).change(); // or .trigger('change');

Alternatively can use $.proxy to change the context the function runs under:

$("#CourseSelect").change(loadTeachers);
$.proxy(loadTeachers, $('#CourseSelect'))();

Or the vanilla JS equivalent of the above, bind():

$("#CourseSelect").change(loadTeachers);
loadTeachers.bind($('#CourseSelect'));

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

It was happening to me in ZF2. I was trying to load the Modal content but I forgot to disable the layout before.

So:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

Node.js global variables

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

Use a JavaScript file and then use module exports.

Example:

File globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

var globals = require('globals'); // << globals.js path
globals.domain // << Domain.

Exiting out of a FOR loop in a batch file?

As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR solution too slow for this purpose. An alternative:

set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart

You might need to use delayed expansion and call subroutines when using this in loops.

What causes a Python segmentation fault?

Google search found me this article, and I did not see the following "personal solution" discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but "re-installing" pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

Throwing exceptions from constructors

It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:

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

A a;     // Implementation defined behaviour if exception is thrown (15.3/13)

int main ()
{
  try
  {
    // Exception for 'a' not caught here.
  }
  catch (int)
  {
  }
}

How can I exclude directories from grep -R?

If you are grepping for code in a git repository and node_modules is in your .gitignore, you can use git grep. git grep searches the tracked files in the working tree, ignoring everything from .gitignore

git grep "STUFF"

JOptionPane Yes or No window

Code for Yes and No Message

      int n = JOptionPane.showConfirmDialog(  
                null,
                "sample question?!" ,
                "",
                JOptionPane.YES_NO_OPTION);

      if(n == JOptionPane.YES_OPTION)
      {
          JOptionPane.showMessageDialog(null, "Opening...");
      }
      else
      {
          JOptionPane.showMessageDialog(null, "Goodbye");
          System.exit(0);