Programs & Examples On #Lossless compression

How can I create directories recursively?

Here is my implementation for your reference:

def _mkdir_recursive(self, path):
    sub_path = os.path.dirname(path)
    if not os.path.exists(sub_path):
        self._mkdir_recursive(sub_path)
    if not os.path.exists(path):
        os.mkdir(path)

Hope this help!

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

it might save some time to somebody.

If you use GuzzleHttp and you face with this error message cURL error 60: SSL: no alternative certificate subject name matches target host name and you are fine with the 'insecure' solution (not recommended on production) then you have to add \GuzzleHttp\RequestOptions::VERIFY => false to the client configuration:

$this->client = new \GuzzleHttp\Client([
    'base_uri'                          => 'someAccessPoint',
    \GuzzleHttp\RequestOptions::HEADERS => [
        'User-Agent' => 'some-special-agent',
    ],
    'defaults'                          => [
        \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
        \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true,
    ],
    \GuzzleHttp\RequestOptions::VERIFY  => false,
]);

which sets CURLOPT_SSL_VERIFYHOST to 0 and CURLOPT_SSL_VERIFYPEER to false in the CurlFactory::applyHandlerOptions() method

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = false;

From the GuzzleHttp documentation

verify

Describes the SSL certificate verification behavior of a request.

  • Set to true to enable SSL certificate verification and use the default CA bundle > provided by operating system.
  • Set to false to disable certificate verification (this is insecure!).
  • Set to a string to provide the path to a CA bundle to enable verification using a custom certificate.

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

How to enable directory listing in apache web server

I solved the problem by enabling the mod_autoindex from Apache. It was disabled by default.

sudo a2enmod autoindex

Fragment transaction animation: slide in and slide out

UPDATE For Android v19+ see this link via @Sandra

You can create your own animations. Place animation XML files in res > anim

enter_from_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate 
      android:fromXDelta="-100%p" android:toXDelta="0%"
      android:fromYDelta="0%" android:toYDelta="0%"
      android:duration="@android:integer/config_mediumAnimTime"/>
</set>

enter_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="100%p" android:toXDelta="0%"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="@android:integer/config_mediumAnimTime" />
</set>

exit_to_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate 
      android:fromXDelta="0%" android:toXDelta="-100%p"
      android:fromYDelta="0%" android:toYDelta="0%"
      android:duration="@android:integer/config_mediumAnimTime"/>
</set>

exit_to_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="0%" android:toXDelta="100%p"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="@android:integer/config_mediumAnimTime" />
</set>

you can change the duration to short animation time

android:duration="@android:integer/config_shortAnimTime"

or long animation time

android:duration="@android:integer/config_longAnimTime" 

USAGE (note that the order in which you call methods on the transaction matters. Add the animation before you call .replace, .commit):

FragmentTransaction transaction = supportFragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();

Get protocol, domain, and port from URL

Here is the solution I'm using:

const result = `${ window.location.protocol }//${ window.location.host }`;

EDIT:

To add cross-browser compatibility, use the following:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

How to call jQuery function onclick?

Try this:

HTML:

<input type="submit" value="submit" name="submit" onclick="myfunction()">

jQuery:

<script type="text/javascript">
 function myfunction() 
 {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
 }
</script>

Converting integer to binary in python

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

Android Studio error: "Environment variable does not point to a valid JVM installation"

In response to:

Ok, Same error (The Environment variable JAVA_HOME (with a value of C:\Program Files(x86)\Java\jdk1.7.0_51\bin)) does not point to a

valid JVM instalation). What should I do? – IPconfigrammer Apr 20 '14 at 18:41

      I can give you a last advice of checking your JDK by opening the jvisualvm.exe or installing a program like BlueJ to check whether

your JDK is corrupt or not. – prakhar19 Apr 20 '14 at 18:45

      jvisualvm.exe works otherwise, I'm not sure. Problem Still unsolved –  IPconfigrammer

IPconfigrammer --I've been having the same problems. After trying just about everything on this page, I noticed when Android Studio was telling me it wasn't valid it asked me to install a 64-bit JDK. So, even though my windows is 86-bit, I downloaded the 64-bit JDK and, without changing any environment variables or anything, I've just opened Android Studio for the first time. No more errors. :)

So try the 64-bit instead of the 86-bit.

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

Vue.js - How to properly watch for nested data

Another way to add that I used to 'hack' this solution was to do this: I set up a seperate computed value that would simply return the nested object value.

data : function(){
    return {
        my_object : {
            my_deep_object : {
                my_value : "hello world";
            }.
        },
    };
},
computed : {
    helper_name : function(){
        return this.my_object.my_deep_object.my_value;
    },
},
watch : {
    helper_name : function(newVal, oldVal){
        // do this...
    }
}

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

Bulk Insertion in Laravel using eloquent ORM

For category relations insertion I came across the same problem and had no idea, except that in my eloquent model I used Self() to have an instance of the same class in foreach to record multiple saves and grabing ids.

foreach($arCategories as $v)
{                
    if($v>0){
        $obj = new Self(); // this is to have new instance of own
        $obj->page_id = $page_id;
        $obj->category_id = $v;
        $obj->save();
    }
}

without "$obj = new Self()" it only saves single record (when $obj was $this)

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this issue; I fixed it by going to

Computer-->Properties-->Advanced Settings-->Environmental Variables

In the System Variables find the variable named PATH.
-->Select Edit -->At the very end of the Path Variable, put a ";" then add your path of your JDK and put \bin\ at the end

Should be fixed.

Example:

System Variable-

C:\Program Files (x86)\Common Files.......HP\LeanFT\bin

JDK path-

C:\Programs Files\Java\jre1.8.0_121

Final Path -

C:\Program Files (x86)\Common Files.......HP\LeanFT\bin;C:\Programs Files\Java\jre1.8.0_121\bin\

Sources: https://www.java.com/en/download/help/path.xml

SVN upgrade working copy

If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.

If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane), set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin.

More can be found on the Netbeans Subversion Clients FAQ.

Why does git status show branch is up-to-date when changes exist upstream?

What the status is telling you is that you're behind the ref called origin/master which is a local ref in your local repo. In this case that ref happens to track a branch in some remote, called origin, but the status is not telling you anything about the branch on the remote. It's telling you about the ref, which is just a commit ID stored on your local filesystem (in this case, it's typically in a file called .git/refs/remotes/origin/master in your local repo).

git pull does two operations; first it does a git fetch to get up to date with the commits in the remote repo (which updates the origin/master ref in your local repo), then it does a git merge to merge those commits into the current branch.

Until you do the fetch step (either on its own or via git pull) your local repo has no way to know that there are additional commits upstream, and git status only looks at your local origin/master ref.

When git status says up-to-date, it means "up-to-date with the branch that the current branch tracks", which in this case means "up-to-date with the local ref called origin/master". That only equates to "up-to-date with the upstream status that was retrieved last time we did a fetch" which is not the same as "up-to-date with the latest live status of the upstream".

Why does it work this way? Well the fetch step is a potentially slow and expensive network operation. The design of Git (and other distributed version control systems) is to avoid network operations when unnecessary, and is a completely different model to the typical client-server system many people are used to (although as pointed out in the comments below, Git's concept of a "remote tracking branch" that causes confusion here is not shared by all DVCSs). It's entirely possible to use Git offline, with no connection to a centralized server, and the output of git status reflects this.

Creating and switching branches (and checking their status) in Git is supposed to be lightweight, not something that performs a slow network operation to a centralized system. The assumption when designing Git, and the git status output, was that users understand this (too many Git features only make sense if you already know how Git works). With the adoption of Git by lots and lots of users who are not familiar with DVCS this assumption is not always valid.

Eloquent ORM laravel 5 Get Array of ids

You may also use all() method to get array of selected attributes.

$test=test::select('id')->where('id' ,'>' ,0)->all();

Regards

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

In Flask, What is request.args and how is it used?

@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.

Reference member variables as class members

It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

There's an interesting introduction on wikipedia.

For const-correctness I'd write:

using T = int;

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  // ...

private:
   const T &m_thing;
};

but a problem with this class is that it accepts references to temporary objects:

T t;
A a1{t};    // this is ok, but...

A a2{T()};  // ... this is BAD.

It's better to add (requires C++11 at least):

class A
{
public:
  A(const T &thing) : m_thing(thing) {}
  A(const T &&) = delete;  // prevents rvalue binding
  // ...

private:
  const T &m_thing;
};

Anyway if you change the constructor:

class A
{
public:
  A(const T *thing) : m_thing(*thing) { assert(thing); }
  // ...

private:
   const T &m_thing;
};

it's pretty much guaranteed that you won't have a pointer to a temporary.

Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


Somewhat related topics are:

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

How can I echo the whole content of a .html file in PHP?

You should use readfile():

readfile("/path/to/file");

This will read the file and send it to the browser in one command. This is essentially the same as:

echo file_get_contents("/path/to/file");

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

Wavy shape with css

I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.

css wavy divider in CSS

Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:

Two simple <div>:

_x000D_
_x000D_
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
  background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
  background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
  content: "";_x000D_
  position: relative;_x000D_
  left: -3rem;_x000D_
  /* padding * -1 */_x000D_
  top: calc( 3rem - 4rem / 2);_x000D_
  /* padding - height/2 */_x000D_
  float: left;_x000D_
  display: block;_x000D_
  height: 4rem;_x000D_
  width: 100vw;_x000D_
  background: hsla(0, 0%, 100%, 0.5);_x000D_
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
  padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.2rem;_x000D_
  line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
  color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
_x000D_
_x000D_

Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)

It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)

To edit the colors, you need to edit the URL-encoded SVG itself.

Pay attention (like in the first demo) to a change in the viewBox to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)

Another thing to pay attention to here is the background-size set to 100% 100% to get it to stretch in both directions.

Programmatically get own phone number in iOS

No, there's no legal and reliable way to do this.

If you find a way, it will be disabled in the future, as it has happened with every method before.

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

How to have a transparent ImageButton: Android

DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button (or the generic view) will no more highlight at click!!!

I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view.

Use this in the button specifications:

android:background="?android:selectableItemBackground"

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

How to recover a dropped stash in Git?

git fsck --unreachable | grep commit should show the sha1, although the list it returns might be quite large. git show <sha1> will show if it is the commit you want.

git cherry-pick -m 1 <sha1> will merge the commit onto the current branch.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

FYI this turned out to be an issue for me where I had two tables in a statement like the following:

SELECT * FROM table1
UNION ALL
SELECT * FROM table2

It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the * to SELECT column1, column2 fixed the issue. No idea how that happened, but lesson learned!

List of remotes for a Git repository?

None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:

$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.

The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.

As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.

GIT: Checkout to a specific folder

Another solution which is a bit cleaner - just specify a different work tree.

To checkout everything from your HEAD (not index) to a specific out directory:

git --work-tree=/path/to/outputdir checkout HEAD -- .

To checkout a subdirectory or file from your HEAD to a specific directory:

git --work-tree=/path/to/outputdir checkout HEAD -- subdirname

Cmake doesn't find Boost

If you are building your own boost do not forget to use the --layout=versioned otherwise the search for a particular version of library will fail

Alter table add multiple columns ms sql

ALTER TABLE Regions
ADD ( HasPhotoInReadyStorage  bit,
     HasPhotoInWorkStorage  bit,
     HasPhotoInMaterialStorage bit *(Missing ,)*
     HasText  bit);

How to return dictionary keys as a list in Python?

Converting to a list without using the keys method makes it more readable:

list(newdict)

and, when looping through dictionaries, there's no need for keys():

for key in newdict:
    print key

unless you are modifying it within the loop which would require a list of keys created beforehand:

for key in list(newdict):
    del newdict[key]

On Python 2 there is a marginal performance gain using keys().

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore 

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

Split function in oracle to comma separated values with automatic sequence

If you need a function try this.
First we'll create a type:

CREATE OR REPLACE TYPE T_TABLE IS OBJECT
(
    Field1 int
    , Field2 VARCHAR(25)
);
CREATE TYPE T_TABLE_COLL IS TABLE OF T_TABLE;
/

Then we'll create the function:

CREATE OR REPLACE FUNCTION TEST_RETURN_TABLE
RETURN T_TABLE_COLL
    IS
      l_res_coll T_TABLE_COLL;
      l_index number;
    BEGIN
      l_res_coll := T_TABLE_COLL();
      FOR i IN (
        WITH TAB AS
          (SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
          UNION
          SELECT '1002' ID, 'D,E,F' STR FROM DUAL
          UNION
          SELECT '1003' ID, 'C,E,G' STR FROM DUAL
          )
        SELECT id,
          SUBSTR(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
        FROM
          ( SELECT ',' || STR || ',' AS STR, id FROM TAB
          ),
          ( SELECT level AS lvl FROM dual CONNECT BY level <= 100
          )
        WHERE lvl <= LENGTH(STR) - LENGTH(REPLACE(STR, ',')) - 1
        ORDER BY ID, NAME)
      LOOP
        IF i.ID = 1001 THEN
          l_res_coll.extend;
          l_index := l_res_coll.count;
          l_res_coll(l_index):= T_TABLE(i.ID, i.name);
        END IF;
      END LOOP;
      RETURN l_res_coll;
    END;
    /

Now we can select from it:

select * from table(TEST_RETURN_TABLE()); 

Output:

SQL> select * from table(TEST_RETURN_TABLE());

    FIELD1 FIELD2
---------- -------------------------
      1001 A
      1001 B
      1001 C
      1001 D
      1001 E
      1001 F

6 rows selected.

Obviously you'd need to replace the WITH TAB AS... bit with where you would be getting your actual data from. Credit Credit

How to load up CSS files using Javascript?

Here's a way with jQuery's element creation method (my preference) and with callback onLoad:

var css = $("<link>", {
  "rel" : "stylesheet",
  "type" :  "text/css",
  "href" : "style.css"
})[0];

css.onload = function(){
  console.log("CSS IN IFRAME LOADED");
};

document
  .getElementsByTagName("head")[0]
  .appendChild(css);

Convert file path to a file URI?

The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.

string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");

properly returns file:///C:/my%20example?.txt

if statements matching multiple values

Easier is subjective, but maybe the switch statement would be easier? You don't have to repeat the variable, so more values can fit on the line, and a line with many comparisons is more legible than the counterpart using the if statement.

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Difference between InvariantCulture and Ordinal string comparison

InvariantCulture

Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).

Ordinal

On the other hand, looks purely at the values of the raw byte(s) that represent the character.


There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).

How to save a figure in MATLAB from the command line?

When using the saveas function the resolution isn't as good as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.

source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

How to check if an array element exists?

You want to use the array_key_exists function.

Node.js: Python not found exception due to node-sass and node-gyp

Hey I got this error resolved by following the steps

  • first I uninstalled python 3.8.6 (latest version)
  • then I installed python 2.7.1 (any Python 2 version will work, but not much older and this is recommended)
  • then I added c:\python27 to environment variables
  • my OS is windows, so I followed this link
  • It worked

Specify multiple attribute selectors in CSS

Concatenate the attribute selectors:

input[name="Sex"][value="M"]

Is recursion ever faster than looping?

According to theory its the same things. Recursion and loop with the same O() complexity will work with the same theoretical speed, but of course real speed depends on language, compiler and processor. Example with power of number can be coded in iteration way with O(ln(n)):

  int power(int t, int k) {
  int res = 1;
  while (k) {
    if (k & 1) res *= t;
    t *= t;
    k >>= 1;
  }
  return res;
  }

Dynamically Add Variable Name Value Pairs to JSON Object

in Javascript.

    var myObject = { "name" : "john" };
    // { "name" : "john" };
    myObject.gender = "male";
    // { "name" : "john", "gender":"male"};

How do I 'git diff' on a certain directory?

If you want to exclude the sub-directories, you can use

git diff <ref1>..<ref2> -- $(git diff <ref1>..<ref2> --name-only | grep -v /)

How can I detect browser type using jQuery?

My solution for ie detection:

if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i) ){
    $("html").addClass("ie");
}

Jquery needed.

How do I give ASP.NET permission to write to a folder in Windows 7?

Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.

If you are using II7 (and I guess you do) do the following.

  1. Open IIS7
  2. Select Website for which you need to modify permissions
  3. Go to Basic Settings and see which application pool you're using.
  4. Go to Application pools and find application pool from #3
  5. Find system account used for running this application pool (Identity column)
  6. Navigate to your storage folder in IIS, select it and click on Edit Permissions (under Actions sub menu on the right)
  7. Open security tab and add needed permissions only for user you identified in #3

Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool

Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.

How can I convert a PFX certificate file for use with Apache on a linux server?

Additionally to

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key

I also generated Certificate Authority (CA) certificate:

openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts

And included it in Apache config file:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 SSLCACertificateFile /path/to/domain-ca.crt
 ...
</VirtualHost>

C - freeing structs

Mallocs and frees need to be paired up.

malloc grabbed a chunk of memory big enough for Person.

When you free you tell malloc the piece of memory starting "here" is no longer needed, it knows how much it allocated and frees it.

Whether you call

 free(testPerson) 

or

 free(testPerson->firstName)

all that free() actually receives is an address, the same address, it can't tell which you called. Your code is much clearer if you use free(testPerson) though - it clearly matches up the with malloc.

How to generate java classes from WSDL file

You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.

It creates the complete source files that you would need.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

Is there a way to have printf() properly print out an array (of floats, say)?

You have to loop through the array and printf() each element:

for(int i=0;i<10;++i) {
  printf("%.2f ", foo[i]);
}

printf("\n");

Converting HTML to XML

I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.

  function tryToXml($dom,$content) {
    if(!$content) return false;

    // xml well formed content can be loaded as xml node tree
    $fragment = $dom->createDocumentFragment();
    // wonderfull appendXML to add an XML string directly into the node tree!

    // aappendxml will fail on a xml declaration so manually skip this when occurred
    if( substr( $content,0, 5) == '<?xml' ) {
      $content = substr($content,strpos($content,'>')+1);
      if( strpos($content,'<') ) {
        $content = substr($content,strpos($content,'<'));
      }
    }

    // if appendXML is not working then use below htmlToXml() for nasty html correction
    if(!@$fragment->appendXML( $content )) {
      return $this->htmlToXml($dom,$content);
    }

    return $fragment;
  }



  // convert content into xml
  // dom is only needed to prepare the xml which will be returned
  function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {

    // no xml when html is empty
    if(!$content) return false;

    // real content and possibly it needs encoding
    if( $needEncoding ) {
      // no need to convert character encoding as loadHTML will respect the content-type (only)
      $content =  '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
    }

    // return a dom from the content
    $domInject = new DOMDocument("1.0", "UTF-8");
    $domInject->preserveWhiteSpace = false;
    $domInject->formatOutput = true;

    // html type
    try {
      @$domInject->loadHTML( $content );
    } catch(Exception $e){
      // do nothing and continue as it's normal that warnings will occur on nasty HTML content
    }
        // to check encoding: echo $dom->encoding
        $this->reworkDom( $domInject );

    if( $bodyOnly ) {
      $fragment = $dom->createDocumentFragment();

      // retrieve nodes within /html/body
      foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
       if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
         foreach( $elementLevel1->childNodes as $elementInject ) {
           $fragment->insertBefore( $dom->importNode($elementInject, true) );
         }
        }
      }
    } else {
      $fragment = $dom->importNode($domInject->documentElement, true);
    }

    return $fragment;
  }



    protected function reworkDom( $node, $level = 0 ) {

        // start with the first child node to iterate
        $nodeChild = $node->firstChild;

        while ( $nodeChild )  {
            $nodeNextChild = $nodeChild->nextSibling;

            switch ( $nodeChild->nodeType ) {
                case XML_ELEMENT_NODE:
                    // iterate through children element nodes
                    $this->reworkDom( $nodeChild, $level + 1);
                    break;
                case XML_TEXT_NODE:
                case XML_CDATA_SECTION_NODE:
                    // do nothing with text, cdata
                    break;
                case XML_COMMENT_NODE:
                    // ensure comments to remove - sign also follows the w3c guideline
                    $nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
                    break;
                case XML_DOCUMENT_TYPE_NODE:  // 10: needs to be removed
                case XML_PI_NODE: // 7: remove PI
                    $node->removeChild( $nodeChild );
                    $nodeChild = null; // make null to test later
                    break;
                case XML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                case XML_HTML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                default:
                    throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
            }
            $nodeChild = $nodeNextChild;
        } ;
    }

Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:

        $c='<p>test<font>two</p>';
    $dom=new DOMDocument('1.0', 'UTF-8');

$n=$dom->appendChild($dom->createElement('info')); // make a root element

if( $valueXml=tryToXml($dom,$c) ) {
  $n->appendChild($valueXml);
}
    echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';

In this example '<p>test<font>two</p>' will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info> tag can be skipped.

With this I'm getting real nice XML out of unstructured and even corrupted HTML!

I hope it's a bit clear and might contribute to other people to use it.

How to start IIS Express Manually

There is not a program but you can make a batch file and run a command like that :

powershell "start-process 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -workingdirectory 'C:\Program Files (x86)\IIS Express\' -windowstyle Hidden"

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Code offset dynamic for dynamic page

var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});

Regular Expression to get a string between parentheses in Javascript

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));

Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
    alert(matches[i]);
}

This code alerts with all the matches.

References:

search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp

search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

ps command doesn't work in docker container

use docker top

docker top <container ID>

How to get the selected radio button’s value?

Try this

function findSelection(field) {
    var test = document.getElementsByName(field);
    var sizes = test.length;
    alert(sizes);
    for (i=0; i < sizes; i++) {
            if (test[i].checked==true) {
            alert(test[i].value + ' you got a value');     
            return test[i].value;
        }
    }
}


function submitForm() {

    var genderS =  findSelection("genderS");
    alert(genderS);
    return false;
}

A fiddle here.

How to get the number of days of difference between two dates on mysql?

Use the DATEDIFF() function.

Example from documentation:

SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
    -> 1

How do you test running time of VBA code?

The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.

Dim t as single
t = Timer
'code
MsgBox Timer - t

How to add display:inline-block in a jQuery show() function?

actually jQuery simply clears the value of the 'display' property, and doesn't set it to 'block' (see internal implementation of jQuery.showHide()) -

   function showHide(elements, show) {
    var display, elem, hidden,

...

         if (show) {
            // Reset the inline display of this element to learn if it is
            // being hidden by cascaded rules or not
            if (!values[index] && display === "none") {
                elem.style.display = "";
            }

...

        if (!show || elem.style.display === "none" || elem.style.display === "") {
            elem.style.display = show ? values[index] || "" : "none";
        }
    }

Please note that you can override $.fn.show()/$.fn.hide(); storing original display in element itself when hiding (e.g. as an attribute or in the $.data()); and then applying it back again when showing.

Also, using css important! will probably not work here - since setting a style inline is usually stronger than any other rule

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

Determine if an element has a CSS class with jQuery

As for the negation, if you want to know if an element hasn't a class you can simply do as Mark said.

if (!currentPage.parent().hasClass('home')) { do what you want }

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

How can I refresh or reload the JFrame?

Try

SwingUtilities.updateComponentTreeUI(frame);

If it still doesn't work then after completing the above step try

frame.invalidate();
frame.validate();
frame.repaint();

jquery get all form elements: input, textarea & select

all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

What's the best way to store Phone number in Django models

Use CharField for phone field in the model and the localflavor app for form validation:

https://docs.djangoproject.com/en/1.7/topics/localflavor/

What is the exact location of MySQL database tables in XAMPP folder?

In Ubuntu the file path is ./opt/lampp/var/mysql

How can I run another application within a panel of my C# program?

I know this is possible if the other application can attach itself to a win32 window handle. For example, we have a separate C# application that hosts a DirectX application inside one of its windows. I'm not familiar with the exact details of how this is implemented, but I think just passing the win32 Handle of your panel to the other application is enough for that application to attach its DirectX surface.

How to make an element width: 100% minus padding?

You can do this:

width: auto;
padding: 20px;

How can I replace every occurrence of a String in a file with PowerShell?

I prefer using the File-class of .NET and its static methods as seen in the following example.

$content = [System.IO.File]::ReadAllText("c:\bla.txt").Replace("[MYID]","MyValue")
[System.IO.File]::WriteAllText("c:\bla.txt", $content)

This has the advantage of working with a single String instead of a String-array as with Get-Content. The methods also take care of the encoding of the file (UTF-8 BOM, etc.) without you having to take care most of the time.

Also the methods don't mess up the line endings (Unix line endings that might be used) in contrast to an algorithm using Get-Content and piping through to Set-Content.

So for me: Fewer things that could break over the years.

A little-known thing when using .NET classes is that when you have typed in "[System.IO.File]::" in the PowerShell window you can press the Tab key to step through the methods there.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

If you're looking for a minimal solution that invalidates the cache, this edited version of Dr Manhattan's solution should be sufficient. Note that I'm specifying the root / directory to indicate I want the whole site refreshed.

export AWS_ACCESS_KEY_ID=<Key>
export AWS_SECRET_ACCESS_KEY=<Secret>
export AWS_DEFAULT_REGION=eu-west-1

echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=<distributionId> --paths / --profile=<awsprofile>

Region Codes can be found here

You'll also need to create a profile using the aws cli. Use the aws configure --profile option. Below is an example snippet from Amazon.

$ aws configure --profile user2
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE
AWS Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: text

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

How do I execute a program from Python? os.system fails due to spaces in path

The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. Python will convert forward-slashed to backslashes on Windows, so you can use

os.system('"C://Temp/a b c/Notepad.exe"')

The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE

How to check if input date is equal to today's date?

for completeness, taken from this solution:

You could use toDateString:

var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());

no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho

AngularJS How to dynamically add HTML and bind to controller

See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.

The config portion looks like this:

  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/', {controller:'ListCtrl', templateUrl:'list.html'})
      .otherwise({redirectTo:'/'});
  }])

The point of entry for injecting the partial view into your main template is:

<div class="container" ng-view=""></div>

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN
IF THEN ELSE
IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

So your code should appear like this.

    declare
        var_number number;
    begin
        var_number := 10;
        if var_number > 100 then
           dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
        elsif var_number < 100 then
           dbms_output.put_line(var_number ||' is less than 100');
        else
           dbms_output.put_line(var_number ||' is equal to 100');
        end if;
    end; 

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.

Cannot authenticate into mongo, "auth fails"

This fixed my issue:

Go to terminal shell and type mongo.

Then type use db_name.

Then type:

 db.createUser(
   {
     user: "mongodb",
     pwd: "dogmeatsubparflavour1337",
     roles: [ { role: "dbOwner", db: "db_name" } ]
   }
 )

Also try: db.getUsers()

Quick sample:

const MongoClient = require('mongodb').MongoClient;

// MongoDB Connection Info
const url = 'mongodb://mongodb:[email protected]:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options

// Use Connect Method to connect to the Server
MongoClient.connect(url)
  .then((db) => {
    console.log(db);
    console.log('Casually connected correctly to server.');
    // Be careful with db.close() when working asynchronously
    db.close();
  })
  .catch((error) => {
    console.log(error);
  });

Overriding interface property type defined in Typescript d.ts file

NOTE: Not sure if the syntax I'm using in this answer was available when the older answers were written, but I think that this is a better approach on how to solve the example mentioned in this question.


I've had some issues related to this topic (overwriting interface properties), and this is how I'm handling it:

  1. First create a generic interface, with the possible types you'd like to use.

You can even use choose a default value for the generic parameter as you can see in <T extends number | SOME_OBJECT = number>

type SOME_OBJECT = { foo: "bar" }

interface INTERFACE_A <T extends number | SOME_OBJECT = number> {
  property: T;
}
  1. Then you can create new types based on that contract, by passing a value to the generic parameter (or omit it and use the default):
type A_NUMBER = INTERFACE_A;                   // USES THE default = number TYPE. SAME AS INTERFACE_A<number>
type A_SOME_OBJECT = INTERFACE_A<SOME_OBJECT>  // MAKES { property: SOME_OBJECT }

And this is the result:

const aNumber: A_NUMBER = {
    property: 111  // THIS EXPECTS A NUMBER
}

const anObject: A_SOME_OBJECT = {
    property: {   // THIS EXPECTS SOME_OBJECT
        foo: "bar"
    }
}

Typescript playground

How do format a phone number as a String in Java?

This is how I ended up doing it:

private String printPhone(Long phoneNum) {
    StringBuilder sb = new StringBuilder(15);
    StringBuilder temp = new StringBuilder(phoneNum.toString());

    while (temp.length() < 10)
        temp.insert(0, "0");

    char[] chars = temp.toString().toCharArray();

    sb.append("(");
    for (int i = 0; i < chars.length; i++) {
        if (i == 3)
            sb.append(") ");
        else if (i == 6)
            sb.append("-");
        sb.append(chars[i]);
    }

    return sb.toString();
}

I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that. I only accept a 10 character long as a phone number. I just wanted to print it with some formatting.

Thanks for the responses.

How to format a java.sql Timestamp for displaying?

String timeFrSSHStr = timeFrSSH.toString();

Maven: Non-resolvable parent POM

I had the issue that two reactor build pom.xml files had the same artefactId.

How to rename a table in SQL Server?

When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too

I took a code example for table dependencies at Pinal Dave's blog here

USE AdventureWorks
GO
SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'Customer'

So, all these dependent objects needs to be updated also

Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too

How to set margin of ImageView using code, not xml

sample code is here ,its very easy

LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                params1.height = 70;
                params1.setMargins(0, 210, 0, 0);//top margin -210 here
                twoLetter.setLayoutParams(params1);//setting layout params
                twoLetter.setImageResource(R.drawable.oo);

Can we instantiate an abstract class?

Technical Answer

Abstract classes cannot be instantiated - this is by definition and design.

From the JLS, Chapter 8. Classes:

A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses.

From JSE 6 java doc for Classes.newInstance():

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.

A Different Angle On This - Teamplay & Social Intelligence:

This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.

"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??

Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.

How can you undo the last git add?

At date git prompts:

  1. use "git rm --cached <file>..." to unstage if files were not in the repo. It unstages the files keeping them there.
  2. use "git reset HEAD <file>..." to unstage if the files were in the repo, and you are adding them as modified. It keeps the files as they are, and unstages them.

At my knowledge you cannot undo the git add -- but you can unstage a list of files as mentioned above.

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

Create an empty data.frame

Say your column names are dynamic, you can create an empty row-named matrix and transform it to a data frame.

nms <- sample(LETTERS,sample(1:10))
as.data.frame(t(matrix(nrow=length(nms),ncol=0,dimnames=list(nms))))

Increase max execution time for php

Well, since your on a shared server, you can't do anything about it. They usually set the max execution time so that you can't override it. I suggest you contact them.

How to fix Warning Illegal string offset in PHP

Magic word is: isset

Validate the entry:

if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

PHP Curl And Cookies

You can specify the cookie file with a curl opt. You could use a unique file for each user.

curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );

The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.

    function fetch( $url, $z=null ) {
            $ch =  curl_init();

            $useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';

            curl_setopt( $ch, CURLOPT_URL, $url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
            curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );

            if( isset($z['post']) )         curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
            if( isset($z['refer']) )        curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );

            curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
            curl_setopt( $ch, CURLOPT_COOKIEJAR,  $z['cookiefile'] );
            curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );

            $result = curl_exec( $ch );
            curl_close( $ch );
            return $result;
    }

I use this for quick grabs. It takes the url and an array of options.

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Call a Vue.js component method from outside the component

I have used a very simple solution. I have included a HTML element, that calls the method, in my Vue Component that I select, using Vanilla JS, and I trigger click!

In the Vue Component, I have included something like the following:

<span data-id="btnReload" @click="fetchTaskList()"><i class="fa fa-refresh"></i></span>

That I use using Vanilla JS:

const btnReload = document.querySelector('[data-id="btnReload"]');
btnReload.click();                

JavaScript naming conventions

One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:

define(['Lightbox'],function(Lightbox) {
  var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
  myLightbox.show('hello')
})

I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:

define(['theLightbox'],function(theLightbox) {
  theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})

Find current directory and file's directory

To get the full path to the directory a Python file is contained in, write this in that file:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)


To get the current working directory use

import os
cwd = os.getcwd()

Documentation references for the modules, constants and functions used above:

CSS3 selector :first-of-type with class name?

The draft CSS Selectors Level 4 proposes to add an of <other-selector> grammar within the :nth-child selector. This would allow you to pick out the nth child matching a given other selector:

:nth-child(1 of p.myclass) 

Previous drafts used a new pseudo-class, :nth-match(), so you may see that syntax in some discussions of the feature:

:nth-match(1 of p.myclass)

This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.

How to change the color of an svg element?

Simply add fill:"desiredColor" in the svg tag of the image: example:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#bbb9c6">
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>

Difference between /res and /assets directories

Both are pretty similar. The real main difference between the two is that in the res directory each file is given a pre-compiled ID which can be accessed easily through R.id.[res id]. This is useful to quickly and easily access images, sounds, icons...

The assets directory is more like a filesystem and provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java. This directory is good for things such as game details, dictionaries,...etc. Hope that helps.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

What do the icons in Eclipse mean?

I can't find a way to create a table with icons in SO, so I am uploading 2 images. Objects Icons

Decorator icons

connect to host localhost port 22: Connection refused

  1. Before installing/reinstalling anything check the status of sshd . . .
sudo systemctl status sshd
  1. You should see something like . . .
? sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; disabled; vendor prese>
   Active: inactive (dead)
     Docs: man:sshd(8)
           man:sshd_config(5)
  1. Just enable and start sshd
sudo systemctl enable sshd
sudo systemctl start sshd

How to check for an empty struct?

As an alternative to the other answers, it's possible to do this with a syntax similar to the way you originally intended if you do it via a case statement rather than an if:

session := Session{}
switch {
case Session{} == session:
    fmt.Println("zero")
default:
    fmt.Println("not zero")
}

playground example

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

Understanding the set() function

As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

LINQ with groupby and count

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.Key, group.Count()));

C++ Convert string (or char*) to wstring (or wchar_t*)

Here's a way to combining string, wstring and mixed string constants to wstring. Use the wstringstream class.

This does NOT work for multi-byte character encodings. This is just a dumb way of throwing away type safety and expanding 7 bit characters from std::string into the lower 7 bits of each character of std:wstring. This is only useful if you have a 7-bit ASCII strings and you need to call an API that requires wide strings.

#include <sstream>

std::string narrow = "narrow";
std::wstring wide = L"wide";

std::wstringstream cls;
cls << " abc " << narrow.c_str() << L" def " << wide.c_str();
std::wstring total= cls.str();

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

jQuery get value of selected radio button

<input type="radio" class="radioBtnClass" name="numbers" value="1" />1<br/>
<input type="radio" class="radioBtnClass" name="numbers" value="2" />2<br/>
<input type="radio" class="radioBtnClass" name="numbers" value="3" />3<br/>

This will return, checked radio button value.

if($("input[type='radio'].radioBtnClass").is(':checked')) {
    var card_type = $("input[type='radio'].radioBtnClass:checked").val();
    alert(card_type);
}

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}

Write HTML file using Java

If you want to do that yourself, without using any external library, a clean way would be to create a template.html file with all the static content, like for example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$title</title>
</head>
<body>$body
</body>
</html>

Put a tag like $tag for any dynamic content and then do something like this:

File htmlTemplateFile = new File("path/template.html");
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title = "New Page";
String body = "This is Body";
htmlString = htmlString.replace("$title", title);
htmlString = htmlString.replace("$body", body);
File newHtmlFile = new File("path/new.html");
FileUtils.writeStringToFile(newHtmlFile, htmlString);

Note: I used org.apache.commons.io.FileUtils for simplicity.

Installing R with Homebrew

If you run

xcode-select --install

you do you not need to install gcc through brew, and you will not have to waste time compiling gcc. See https://stackoverflow.com/a/24967219/2668545 for more details.

After that, you can simply do

brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r

Make Bootstrap's Carousel both center AND responsive?

By using this on bootstrap 3:

#carousel-example-generic{
    margin:auto;
}

How to rename a component in Angular CLI?

Currently Angular CLI doesn't support the feature of renaming or refactoring code.

You can achieve such functionality with the help of some IDE.

Intellij, Eclipse, VSCode etc.. has default support the refactoring.

Nowadays VSCode is showing some uptrend,personally I'm a fan of this

Refactoring with VSCode

Determinig reference : - VS Code help you find all references of a variable by selecting variable and pressing shortcut SHIFT + F12. This works incredibly well with Type Script.

Renaming all instances of reference :- After finding all the references you can press F2 will open a popup and you can change the value and click enter this will update all the instances of reference.

Renaming files and imports You can rename a file and its import references with a plugin. More details can be found here

enter image description here

With above steps after renaming the variables and files you can achieve the angular component renaming.

Eclipse error: R cannot be resolved to a variable

I'm not posting this as an answer but a confirmation to Paresh's accepted answer. I recently updated SDK tools to Revision 22 and I noticed my code changes was not being affective on the device i'm testing at all. Such as the url I was using, I was getting errors for connection time out regarding the url I was "previously" using. Therefore I cleaned the project and built again only to find out that autogenerated R.java file is missing.

After reading Paresh's answer and checking what's going on with my sdk manager this is what I saw: enter image description here

SDK Build-tools 17 was not installed and there was already a new update to SDK tools even though it does not mention any change related to this problem in the changelog, this update brought back my R.java file and the related problems were gone after an eclipse restart and final clean/rebuild on the project.

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

How to call a method defined in an AngularJS directive?

TESTED Hope this helps someone.

My simple approach (Think tags as your original code)

<html>
<div ng-click="myfuncion"> 
<my-dir callfunction="myfunction">
</html>

<directive "my-dir">
callfunction:"=callfunction"
link : function(scope,element,attr) {
scope.callfunction = function() {
 /// your code
}
}
</directive>

CSS: borders between table columns only

Inside <td>, use style="border-left:1px solid #colour;"

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

If you are using Sentry check the logged in user with Sentry::getUser()->id. The error you get is that the Auth::user() returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object.

Kafka consumer list

you can use this for 0.9.0.0. version kafka

./kafka-consumer-groups.sh --list --zookeeper hostname:potnumber

to view the groups you have created. This will display all the consumer group names.

 ./kafka-consumer-groups.sh --describe --zookeeper hostname:potnumber  --describe  --group consumer_group_name

To view the details

GROUP, TOPIC, PARTITION, CURRENT OFFSET, LOG END OFFSET, LAG, OWNER

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

adding to scotty's answer:

Option 1: Either include this in your JS file:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

Option 2: or just use the URL to download 'angular-route.min.js' to your local.

and then (whatever option you choose) add this 'ngRoute' as dependency.

explained: var app = angular.module('myapp', ['ngRoute']);

Cheers!!!

How to get margin value of a div in plain JavaScript?

I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:

_x000D_
_x000D_
/***
 * get live runtime value of an element's css style
 *   http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
 *     note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
 ***/
var getStyle = function(e, styleName) {
  var styleValue = "";
  if (document.defaultView && document.defaultView.getComputedStyle) {
    styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
  } else if (e.currentStyle) {
    styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
      return p1.toUpperCase();
    });
    styleValue = e.currentStyle[styleName];
  }
  return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft);    // 10px
_x000D_
#yourElement {
  margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
_x000D_
_x000D_

Git error when trying to push -- pre-receive hook declined

For me Authorization on remote git server solve the problem. enter image description here

How to examine processes in OS X's Terminal?

Try ps -ef. man ps will give you all the options.

 -A      Display information about other users' processes, including those without controlling terminals.

 -e      Identical to -A.

 -f      Display the uid, pid, parent pid, recent CPU usage, process start time, controlling tty, elapsed CPU usage, and the associated command.  If the -u option is also used, display
         the user name rather then the numeric uid.  When -o or -O is used to add to the display following -f, the command field is not truncated as severely as it is in other formats.

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

How do I print my Java object without getting "SomeType@2f92e0f4"?

In Eclipse, Go to your class, Right click->source->Generate toString();

It will override the toString() method and will print the object of that class.

MS SQL 2008 - get all table names and their row counts in a DB

Try this it's simple and fast

SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
   INNER JOIN sys.sysindexes AS I ON T.object_id = I.id 
   AND I.indid < 2 ORDER  BY I.rows DESC

Get Environment Variable from Docker Container

@aisbaa's answer works if you don't care when the environment variable was declared. If you want the environment variable, even if it has been declared inside of an exec /bin/bash session, use something like:

IFS="=" read -a out <<< $(docker exec container /bin/bash -c "env | grep ENV_VAR" 2>&1)

It's not very pretty, but it gets the job done.

To then get the value, use:

echo ${out[1]}

How to write a Unit Test?

Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x

Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.

How to create a responsive image that also scales up in Bootstrap 3

Not sure if it helps you still... but I had to do a small trick to make the image bigger but keeping it responsive

@media screen and (max-width: 368px) {
    img.smallResolution{
        min-height: 150px;
    }

}

Hope it helps P.S. The max width can be anything you like

Access Form - Syntax error (missing operator) in query expression

I did quickly fix it by going into "Design View" of the main Table of same Form and putting underline (_) between any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

How much memory can a 32 bit process access on a 64 bit operating system?

You've got the same basic restriction when running a 32bit process under Win64. Your app runs in a 32 but subsystem which does its best to look like Win32, and this will include the memory restrictions for your process (lower 2GB for you, upper 2GB for the OS)

How to redirect verbose garbage collection output to a file?

From the output of java -X:

    -Xloggc:<file>    log GC status to a file with time stamps

Documented here:

-Xloggc:filename

Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of -verbose:gc with the time elapsed since the first GC event preceding each logged event. The -Xloggc option overrides -verbose:gc if both are given with the same java command.

Example:

    -Xloggc:garbage-collection.log

So the output looks something like this:

0.590: [GC 896K->278K(5056K), 0.0096650 secs]
0.906: [GC 1174K->774K(5056K), 0.0106856 secs]
1.320: [GC 1670K->1009K(5056K), 0.0101132 secs]
1.459: [GC 1902K->1055K(5056K), 0.0030196 secs]
1.600: [GC 1951K->1161K(5056K), 0.0032375 secs]
1.686: [GC 1805K->1238K(5056K), 0.0034732 secs]
1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs]
1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]

Indexes of all occurrences of character in a string

int index = -1;
while((index = text.indexOf("on", index + 1)) >= 0) {
   LOG.d("index=" + index);
}

Is < faster than <=?

This would be highly dependent on the underlying architecture that the C is compiled to. Some processors and architectures might have explicit instructions for equal to, or less than and equal to, which execute in different numbers of cycles.

That would be pretty unusual though, as the compiler could work around it, making it irrelevant.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Perform debounce in React.js

Hook:

import {useState} from "react";

const useDebounce = ({defaultTimeout = 250, defaultIdentifier = 'default'} = {}) => {

    const [identifiers, setIdentifiers] = useState({[defaultIdentifier]: null});

    return ({fn = null, identifier = defaultIdentifier, timeout = defaultTimeout} = {}) => {
        if (identifiers.hasOwnProperty(identifier)) clearTimeout(identifiers[identifier]);
        setIdentifiers({...identifiers, [identifier]: setTimeout(fn, timeout)});
    };
};

export default useDebounce;

And use it anywhere (in same file use identifier to prevent concurrence) like:

const debounce = useDebounce();

const handlerA = () => {
    debounce({fn: () => console.log('after 2000ms of last call with identifier A'), identifier: 'A', timeout: 2000});
};

const handlerB = () => {
    debounce({fn: () => console.log('after 1500ms of last call with identifier B'), identifier: 'B', timeout: 1500});
};

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

How to get a URL parameter in Express?

You can do something like req.param('tagId')

How to get year/month/day from a date object?

var date = new Date().toLocaleDateString()
"12/30/2009"

How do I enable EF migrations for multiple contexts to separate databases?

If more databases exist use following codes in PowerShell

Add-Migration Starter -context EnrollmentAppContext 
  • 'Starter' is Migration Name

  • 'EnrollmentAppContext' is name of my app Context

You can open PowerShell in VS by doing: Tools->NuGet Package Manager->Package Manager Console

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

<select name="country" formControlName="country" id="country" 
       class="formcontrol form-control-element" [(ngModel)]="country">
   <option value="90">Turkey</option>
   <option value="1">USA</option>
   <option value="30">Greece</option>
</select>
name="country"
formControlName="country" 
[(ngModel)]="country" 

Those are the three things need to use ngModel inside a formGroup directive.

Note that same name should be used.

How to know that a string starts/ends with a specific string in jQuery?

You can always extend String prototype like this:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

And use it like this:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

How do you post data with a link

We should make everything easier for everyone because you can simply combine JS to PHP Combining PHP and JS is pretty easy.

$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = $house_number; document.forms[0].submit();</script>";

Or a somewhat safer way

$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = " . $house_number . "; document.forms[0].submit();</script>";

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

How can I check if my python object is a number?

Test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).

However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.

This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

Select last N rows from MySQL

select * from Table ORDER BY id LIMIT 30

Notes: * id should be unique. * You can control the numbers of rows returned by replacing the 30 in the query

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Do the following.

  1. Close the sdk manager and eclipse.

  2. Go to the folder where you have stored your adt.

  3. In that adt folder you'll find a folder known as tools.

  4. Make a copy of the contents of that folder and paste it in a folder called copytools.

  5. Now go to the command prompt and go to the location of the copytools.

  6. Then execute the command android.bat the sdk manager will start.

  7. Now update all the plugins you want. It'll update your original folder.

  8. After the update delete the copy.

Enjoy. Hope this helps.

Only on Firefox "Loading failed for the <script> with source"

I ran in the same situation and the script was correctly loading in safe mode. However, disabling all the Add-ons and other Firefox security features didn't help. One thing I tried, and this was the solution in my case, was to temporary disable the cache from the developer window for this particular request. After I saw this was the cause, I wiped out the cache for that site and everything started word normally.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

If you are using windows, sometimes this may happen because Windows stores credentials for outer repo (in our case github) in its own storage. And credentials that saved there can be different from those you need right now.

enter image description here

So to avoid this problem, just find github in this storage and delete saved credentials. After this, while pushing git will request your credentials and will allow you to push.

Remove x-axis label/text in chart.js

For those whom this did not work, here is how I hid the labels on the X-axis-

options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        left: 1,
        right: 2,
        top: 2,
        bottom: 0,
      },
    },
    scales: {
      xAxes: [
        {
          time: {
            unit: 'Areas',
          },
          gridLines: {
            display: false,
            drawBorder: false,
          },
          ticks: {
            maxTicksLimit: 7,
            display: false, //this removed the labels on the x-axis
          },
          'dataset.maxBarThickness': 5,
        },
      ],

Non greedy (reluctant) regex matching in sed?

Another sed version:

sed 's|/[:alnum:].*||' file.txt

It matches / followed by an alphanumeric character (so not another forward slash) as well as the rest of characters till the end of the line. Afterwards it replaces it with nothing (ie. deletes it.)

TypeScript enum to object array

You can do that in this way:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

export class GoalProgressMeasurement {
    constructor(public goalProgressMeasurement: GoalProgressMeasurements, public name: string) {
    }
}

export var goalProgressMeasurements: { [key: number]: GoalProgressMeasurement } = {
    1: new GoalProgressMeasurement(GoalProgressMeasurements.Percentage, "Percentage"),
    2: new GoalProgressMeasurement(GoalProgressMeasurements.Numeric_Target, "Numeric Target"),
    3: new GoalProgressMeasurement(GoalProgressMeasurements.Completed_Tasks, "Completed Tasks"),
    4: new GoalProgressMeasurement(GoalProgressMeasurements.Average_Milestone_Progress, "Average Milestone Progress"),
    5: new GoalProgressMeasurement(GoalProgressMeasurements.Not_Measured, "Not Measured"),
}

And you can use it like this:

var gpm: GoalProgressMeasurement = goalProgressMeasurements[GoalProgressMeasurements.Percentage];
var gpmName: string = gpm.name;

var myProgressId: number = 1; // the value can come out of drop down selected value or from back-end , so you can imagine the way of using
var gpm2: GoalProgressMeasurement = goalProgressMeasurements[myProgressId];
var gpmName: string = gpm.name;

You can extend the GoalProgressMeasurement with additional properties of the object as you need. I'm using this approach for every enumeration that should be an object containing more then a value.

Split string into strings by length?

# spliting a string by the length of the string

def len_split(string,sub_string):
    n,sub,str1=list(string),len(sub_string),')/^0*/-'
    for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
        n.insert(i,str1)   
    n="".join(n)
    n=n.split(str1)
    return n

x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))

# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']

What does request.getParameter return?

Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

How to parse a JSON Input stream

All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).

With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.

public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);

    private final InputStream inputStream;
    private JsonParser jsonParser;
    private boolean isInitialized;

    private Map<String, Object> nextObject;

    public JsonObjectIterator(final InputStream inputStream) {
        this.inputStream = inputStream;
        this.isInitialized = false;
        this.nextObject = null;
    }

    private void init() {
        this.initJsonParser();
        this.initFirstElement();
        this.isInitialized = true;
    }

    private void initJsonParser() {
        final ObjectMapper objectMapper = new ObjectMapper();
        final JsonFactory jsonFactory = objectMapper.getFactory();

        try {
            this.jsonParser = jsonFactory.createParser(inputStream);
        } catch (final IOException e) {
            LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
        }
    }

    private void initFirstElement() {
        try {
            // Check that the first element is the start of an array
            final JsonToken arrayStartToken = this.jsonParser.nextToken();
            if (arrayStartToken != JsonToken.START_ARRAY) {
                throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
            }

            // Initialize the first object
            this.initNextObject();
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
        }

    }

    private void initNextObject() {
        try {
            final JsonToken nextToken = this.jsonParser.nextToken();

            // Check for the end of the array which will mean we're done
            if (nextToken == JsonToken.END_ARRAY) {
                this.nextObject = null;
                return;
            }

            // Make sure the next token is the start of an object
            if (nextToken != JsonToken.START_OBJECT) {
                throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
            }

            // Get the next product and make sure it's not null
            this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
            if (this.nextObject == null) {
                throw new IllegalStateException("The next parsed object of the Json structure was null");
            }
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean hasNext() {
        if (!this.isInitialized) {
            this.init();
        }

        return this.nextObject != null;
    }

    @Override
    public Map<String, Object> next() {
        // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state

        // Makes sure we're initialized first
        if (!this.isInitialized) {
            this.init();
        }

        // Store the current next object for return
        final Map<String, Object> currentNextObject = this.nextObject;

        // Initialize the next object
        this.initNextObject();

        return currentNextObject;
    }

    @Override
    public void close() throws IOException {
        IOUtils.closeQuietly(this.jsonParser);
        IOUtils.closeQuietly(this.inputStream);
    }

}

If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.

Excel VBA Run-time error '13' Type mismatch

Diogo

Justin has given you some very fine tips :)

You will also get that error if the cell where you are performing the calculation has an error resulting from a formula.

For example if Cell A1 has #DIV/0! error then you will get "Excel VBA Run-time error '13' Type mismatch" when performing this code

Sheets("Sheet1").Range("A1").Value - 1

I have made some slight changes to your code. Could you please test it for me? Copy the code with the line numbers as I have deliberately put them there.

Option Explicit

Sub Sample()
  Dim ws As Worksheet
  Dim x As Integer, i As Integer, a As Integer, y As Integer
  Dim name As String
  Dim lastRow As Long
10        On Error GoTo Whoa

20        Application.ScreenUpdating = False

30        name = InputBox("Please insert the name of the sheet")

40        If Len(Trim(name)) = 0 Then Exit Sub

50        Set ws = Sheets(name)

60        With ws
70            If Not IsError(.Range("BE4").Value) Then
80                x = Val(.Range("BE4").Value)
90            Else
100               MsgBox "Please check the value of cell BE4. It seems to have an error"
110               GoTo LetsContinue
120           End If

130           .Range("BF4").Value = x

140           lastRow = .Range("BE" & Rows.Count).End(xlUp).Row

150           For i = 5 To lastRow
160               If IsError(.Range("BE" & i)) Then
170                   MsgBox "Please check the value of cell BE" & i & ". It seems to have an error"
180                   GoTo LetsContinue
190               End If

200               a = 0: y = Val(.Range("BE" & i))
210               If y <> x Then
220                   If y <> 0 Then
230                       If y = 3 Then
240                           a = x
250                           .Range("BF" & i) = Val(.Range("BE" & i)) - x

260                           x = Val(.Range("BE" & i)) - x
270                       End If
280                       .Range("BF" & i) = Val(.Range("BE" & i)) - a
290                       x = Val(.Range("BE" & i)) - a
300                   Else
310                       .Range("BF" & i).ClearContents
320                   End If
330               Else
340                   .Range("BF" & i).ClearContents
350               End If
360           Next i
370       End With

LetsContinue:
380       Application.ScreenUpdating = True
390       Exit Sub
Whoa:
400       MsgBox "Error Description :" & Err.Description & vbNewLine & _
         "Error at line     : " & Erl
410       Resume LetsContinue
End Sub

How can JavaScript save to a local file?

Based on http://html5-demos.appspot.com/static/a.download.html:

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

Are nested try/except blocks in Python a good programming practice?

A good and simple example for nested try/except could be the following:

import numpy as np

def divide(x, y):
    try:
        out = x/y
    except:
        try:
            out = np.inf * x / abs(x)
        except:
            out = np.nan
    finally:
        return out

Now try various combinations and you will get the correct result:

divide(15, 3)
# 5.0

divide(15, 0)
# inf

divide(-15, 0)
# -inf

divide(0, 0)
# nan

(Of course, we have NumPy, so we don't need to create this function.)

What does += mean in Python?

a += b is essentially the same as a = a + b, except that:

  • + always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).

  • In a = a + b, a is evaluated twice.

  • Python: Simple Statements

    • A simple statement is comprised within a single logical line.

If this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:

# two variables referring to the same list
>>> list1 = []
>>> list2 = list1

# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])

# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])

Remove NA values from a vector

Trying ?max, you'll see that it actually has a na.rm = argument, set by default to FALSE. (That's the common default for many other R functions, including sum(), mean(), etc.)

Setting na.rm=TRUE does just what you're asking for:

d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)

If you do want to remove all of the NAs, use this idiom instead:

d <- d[!is.na(d)]

A final note: Other functions (e.g. table(), lm(), and sort()) have NA-related arguments that use different names (and offer different options). So if NA's cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's usually one already there.

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

How to open a specific port such as 9090 in Google Compute Engine

Here is the command-line approach to answer this question:

gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"

This will open the port 9090 for the instances that you name. Omitting --source-tags and --source-ranges will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create command manual

The previous answers are great, but Google recommends using the newer gcloud commands instead of the gcutil commands.

PS: To get an idea of Google's firewall rules, run gcloud compute firewall-rules list and view all your firewall rules

Initializing multiple variables to the same value in Java

String one, two, three;
one = two = three = "";

This should work with immutable objects. It doesn't make any sense for mutable objects for example:

Person firstPerson, secondPerson, thirdPerson;
firstPerson = secondPerson = thirdPerson = new Person();

All the variables would be pointing to the same instance. Probably what you would need in that case is:

Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();

Or better yet use an array or a Collection.

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


Getting new Twitter API consumer and secret keys

To get Consumer Key & Consumer Secret, you have to create an app in Twitter via

https://developer.twitter.com/en/apps

Then you'll be taken to a page containing Consumer Key & Consumer Secret.

Hopefully this information will clarify OAuth essentials for Twitter:

  1. Create a Twitter account if you don't already have one
  2. Visit 'https://apps.twitter.com' and follow the required prompts to create a developer project (Twitter requires you to answer some questions before they will approve your account. Approval was nearly instant in my case.)
  3. Requesting the API key and secret via the Developer Portal causes Twitter to produce the following three things:
  • API key (this is your 'consumer key')
  • API secret key (this is your 'consumer secret')
  • Bearer token
  1. Next, visit the 'Authentication Tokens' area of the Developer Portal and generate an 'Access token & secret'. This will provide you with the following two items:
  • Access token (this is your 'token key')
  • Access token secret (this is your 'token secret')
  1. The consumer key, consumer secret, token key, and token secret should be sufficient to do Twitter API calls (they were for me). Good luck!

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

How can I send an Ajax Request on button click from a form with 2 buttons?

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});

Simplest/cleanest way to implement a singleton in JavaScript

I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton. However, the module pattern is not a singleton.

Module pattern:

var foo = (function () {
    "use strict";
    function aPrivateFunction() {}
    return { aPublicFunction: function () {...}, ... };
}());

Everything initialized in the module pattern happens when Foo is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.

Singleton pattern:

short form
var Foo = function () {
    "use strict";
    if (Foo._instance) {
        // This allows the constructor to be called multiple times
        // and refer to the same instance. Another option is to
        // throw an error.
        return Foo._instance;
    }
    Foo._instance = this;
    // Foo initialization code
};
Foo.getInstance = function () {
    "use strict";
    return Foo._instance || new Foo();
}
long form, using module pattern
var Foo = (function () {
    "use strict";
    var instance; //prevent modification of "instance" variable
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
        //Singleton initialization code
    }
    // Instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    }
    return Singleton;
}());

In both versions of the singleton pattern that I've provided, the constructor itself can be used as the accessor:

var a,
    b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true

If you don't feel comfortable using the constructor this way, you can throw an error in the if (instance) statement, and stick to using the long form:

var a,
    b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true

I should also mention that the singleton pattern fits well with the implicit constructor function pattern:

function Foo() {
    if (Foo._instance) {
        return Foo._instance;
    }
    // If the function wasn't called as a constructor,
    // call it as a constructor and return the result
    if (!(this instanceof Foo)) {
        return new Foo();
    }
    Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Use ASP.NET MVC validation with jquery ajax?

Here's a rather simple solution:

In the controller we return our errors like this:

if (!ModelState.IsValid)
        {
            return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
        }

Here's some of the client script:

function displayValidationErrors(errors)
{
    var $ul = $('div.validation-summary-valid.text-danger > ul');

    $ul.empty();
    $.each(errors, function (idx, errorMessage) {
        $ul.append('<li>' + errorMessage + '</li>');
    });
}

That's how we handle it via ajax:

$.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
        var isSuccessful = (data['success']);

        if (isSuccessful) {
            $('#partial-container-steps').html(data['view']);
            initializePage();
        }
        else {
            var errors = data['errors'];

            displayValidationErrors(errors);
        }
    }
});

Also, I render partial views via ajax in the following way:

var view = this.RenderRazorViewToString(partialUrl, viewModel);
        return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);

RenderRazorViewToString method:

public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                     viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                         ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

How can I hide/show a div when a button is clicked?

The following solution is:

  • briefest. Somewhat similar to here. It's also minimal: The table in the DIV is orthogonal to your question.
  • fastest: getElementById is called once at the outset. This may or may not suit your purposes.
  • It uses pure JavaScript (i.e. without JQuery).
  • It uses a button. Your taste may vary.
  • extensible: it's ready to add more DIVs, sharing the code.

_x000D_
_x000D_
mydiv = document.getElementById("showmehideme");_x000D_
_x000D_
function showhide(d) {_x000D_
    d.style.display = (d.style.display !== "none") ? "none" : "block";_x000D_
}
_x000D_
#mydiv { background-color: #ddd; }
_x000D_
<button id="button" onclick="showhide(mydiv)">Show/Hide</button>_x000D_
<div id="showmehideme">_x000D_
    This div will show and hide on button click._x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get the old value of a changed cell in Excel VBA?

Using Static will solve your problem (with some other stuff to initialize old_value properly:

Private Sub Worksheet_Change(ByVal Target As Range)
    Static old_value As String
    Dim inited as Boolean 'Used to detect first call and fill old_value
    Dim new_value As String
    If Not Intersect(cell, Range("cell_of_interest")) Is Nothing Then
         new_value = Range("cell_of_interest").Value
         If Not inited Then
             inited = True
         Else
            Call DoFoo (old_value, new_value)
        End If
        old_value = new_value
    Next cell
End Sub

In workbook code, force call of Worksheet_change to fill old_value:

Private Sub Private Sub Workbook_Open()
     SheetX.Worksheet_Change SheetX.Range("cell_of_interest")
End Sub

Note, however, that ANY solution based in VBA variables (including dictionary and another more sophisticate methods) will fail if you stop (Reset) running code (eg. while creating new macros, debugging some code, ...). To avoid such, consider using alternative storage methods (hidden worksheet, for example).