Programs & Examples On #Dispose

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources

How to check if object has been disposed in C#

A good way is to derive from TcpClient and override the Disposing(bool) method:

class MyClient : TcpClient {
    public bool IsDead { get; set; }
    protected override void Dispose(bool disposing) {
        IsDead = true;
        base.Dispose(disposing);
    }
}

Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.

Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.

EDIT: A reflection example:

using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
   BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
   // Retrieve a FieldInfo instance corresponding to the field
   PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
   // Retrieve the value of the field, and cast as necessary
   return (bool)field.GetValue(s, null);
}

Finalize vs Dispose

The best example which i know.

 public abstract class DisposableType: IDisposable
  {
    bool disposed = false;

    ~DisposableType()
    {
      if (!disposed) 
      {
        disposed = true;
        Dispose(false);
      }
    }

    public void Dispose()
    {
      if (!disposed) 
      {
        disposed = true;
        Dispose(true);
        GC.SuppressFinalize(this);
      }
    }

    public void Close()
    {
      Dispose();
    }

    protected virtual void Dispose(bool disposing)
    {
      if (disposing) 
      {
        // managed objects
      }
      // unmanaged objects and resources
    }
  }

Should I Dispose() DataSet and DataTable?

If your intention or the context of this question is really garbage collection, then you can set the datasets and datatables to null explicitly or use the keyword using and let them go out of scope. Dispose does not do much as Tetraneutron said it earlier. GC will collect dataset objects that are no longer referenced and also those that are out of scope.

I really wish SO forced people down voting to actually write a comment before downvoting the answer.

Do you need to dispose of objects and set them to null?

I have to answer, too. The JIT generates tables together with the code from it's static analysis of variable usage. Those table entries are the "GC-Roots" in the current stack frame. As the instruction pointer advances, those table entries become invalid and so ready for garbage collection. Therefore: If it is a scoped variable, you don't need to set it to null - the GC will collect the object. If it is a member or a static variable, you have to set it to null

Refresh image with a new one at the same url

Place a second copy of the image in the same spot, then remove the original image.

ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
ele.parentNode.removeChild(ele);

This will effectively refresh the image.

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

C++ Singleton design pattern

I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:

#include<iostream>
#include<string>

class DoNotCopy
{
protected:
    DoNotCopy(void) = default;
    DoNotCopy(const DoNotCopy&) = delete;
    DoNotCopy& operator=(const DoNotCopy&) = delete;
};

class DoNotMove
{
protected:
    DoNotMove(void) = default;
    DoNotMove(DoNotMove&&) = delete;
    DoNotMove& operator=(DoNotMove&&) = delete;
};

class DoNotCopyMove : public DoNotCopy,
    public DoNotMove
{
protected:
    DoNotCopyMove(void) = default;
};

template<class T>
class Singleton : public DoNotCopyMove
{
public:
    static T& Instance(void)
    {
        static T instance;
        return instance;
    }

protected:
    Singleton(void) = default;
};

class Logger final: public Singleton<Logger>
{
public:
    void log(const std::string& str) { std::cout << str << std::endl; }
};



int main()
{
    Logger::Instance().log("xx");
}

The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).

How do I set a program to launch at startup

    /// <summary>
    /// Add application to Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    /// <param name="path"></param>
    public static void AddStartup(string appName, string path)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue(appName, "\"" + path + "\"");
        }
    }

    /// <summary>
    /// Remove application from Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    public static void RemoveStartup(string appName)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue(appName, false);
        }
    }

Convert array of integers to comma-separated string

You can have a pair of extension methods to make this task easier:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();

C dynamically growing array

As with everything that seems scarier at first than it was later, the best way to get over the initial fear is to immerse yourself into the discomfort of the unknown! It is at times like that which we learn the most, after all.

Unfortunately, there are limitations. While you're still learning to use a function, you shouldn't assume the role of a teacher, for example. I often read answers from those who seemingly don't know how to use realloc (i.e. the currently accepted answer!) telling others how to use it incorrectly, occasionally under the guise that they've omitted error handling, even though this is a common pitfall which needs mention. Here's an answer explaining how to use realloc correctly. Take note that the answer is storing the return value into a different variable in order to perform error checking.

Every time you call a function, and every time you use an array, you are using a pointer. The conversions are occurring implicitly, which if anything should be even scarier, as it's the things we don't see which often cause the most problems. For example, memory leaks...

Array operators are pointer operators. array[x] is really a shortcut for *(array + x), which can be broken down into: * and (array + x). It's most likely that the * is what confuses you. We can further eliminate the addition from the problem by assuming x to be 0, thus, array[0] becomes *array because adding 0 won't change the value...

... and thus we can see that *array is equivalent to array[0]. You can use one where you want to use the other, and vice versa. Array operators are pointer operators.

malloc, realloc and friends don't invent the concept of a pointer which you've been using all along; they merely use this to implement some other feature, which is a different form of storage duration, most suitable when you desire drastic, dynamic changes in size.

It is a shame that the currently accepted answer also goes against the grain of some other very well-founded advice on StackOverflow, and at the same time, misses an opportunity to introduce a little-known feature which shines for exactly this usecase: flexible array members! That's actually a pretty broken answer... :(

When you define your struct, declare your array at the end of the structure, without any upper bound. For example:

struct int_list {
    size_t size;
    int value[];
};

This will allow you to unite your array of int into the same allocation as your count, and having them bound like this can be very handy!

sizeof (struct int_list) will act as though value has a size of 0, so it'll tell you the size of the structure with an empty list. You still need to add to the size passed to realloc to specify the size of your list.

Another handy tip is to remember that realloc(NULL, x) is equivalent to malloc(x), and we can use this to simplify our code. For example:

int push_back(struct int_list **fubar, int value) {
    size_t x = *fubar ? fubar[0]->size : 0
         , y = x + 1;

    if ((x & y) == 0) {
        void *temp = realloc(*fubar, sizeof **fubar
                                   + (x + y) * sizeof fubar[0]->value[0]);
        if (!temp) { return 1; }
        *fubar = temp; // or, if you like, `fubar[0] = temp;`
    }

    fubar[0]->value[x] = value;
    fubar[0]->size = y;
    return 0;
}

struct int_list *array = NULL;

The reason I chose to use struct int_list ** as the first argument may not seem immediately obvious, but if you think about the second argument, any changes made to value from within push_back would not be visible to the function we're calling from, right? The same goes for the first argument, and we need to be able to modify our array, not just here but possibly also in any other function/s we pass it to...

array starts off pointing at nothing; it is an empty list. Initialising it is the same as adding to it. For example:

struct int_list *array = NULL;
if (!push_back(&array, 42)) {
    // success!
}

P.S. Remember to free(array); when you're done with it!

How to find Control in TemplateField of GridView?

string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

condition: =K21+$F22

That is not a CONDITION. That is a VALUE. A CONDITION, evaluates as a BOOLEAN value (True/False) If True, then the format is applied.

This would be a CONDITION, for instance

condition: =K21+$F22>0

In general, when applying a CF to a range,

1) select the entire range that you want the Conditional FORMAT to be applied to.

2) enter the CONDITION, as it relates to the FIRST ROW of your selection.

The CF accordingly will be applied thru the range.

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

How to join multiple collections with $lookup in mongodb

According to the documentation, $lookup can join only one external collection.

What you could do is to combine userInfo and userRole in one collection, as provided example is based on relational DB schema. Mongo is noSQL database - and this require different approach for document management.

Please find below 2-step query, which combines userInfo with userRole - creating new temporary collection used in last query to display combined data. In last query there is an option to use $out and create new collection with merged data for later use.

create collections

db.sivaUser.insert(
{    
    "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
        "email" : "[email protected]",
        "userId" : "AD",
        "userName" : "admin"
})

//"userinfo"
db.sivaUserInfo.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "phone" : "0000000000"
})

//"userrole"
db.sivaUserRole.insert(
{
    "_id" : ObjectId("56d82612b63f1c31cf906003"),
    "userId" : "AD",
    "role" : "admin"
})

"join" them all :-)

db.sivaUserInfo.aggregate([
    {$lookup:
        {
           from: "sivaUserRole",
           localField: "userId",
           foreignField: "userId",
           as: "userRole"
        }
    },
    {
        $unwind:"$userRole"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :"$userRole.role"
        }
    },
    {
        $out:"sivaUserTmp"
    }
])


db.sivaUserTmp.aggregate([
    {$lookup:
        {
           from: "sivaUser",
           localField: "userId",
           foreignField: "userId",
           as: "user"
        }
    },
    {
        $unwind:"$user"
    },
    {
        $project:{
            "_id":1,
            "userId" : 1,
            "phone" : 1,
            "role" :1,
            "email" : "$user.email",
            "userName" : "$user.userName"
        }
    }
])

Pycharm does not show plot

I had the same problem. Check wether plt.isinteractive() is True. Setting it to 'False' helped for me.

plt.interactive(False)

What is the difference between C and embedded C?

C is a only programming language its used in system programming. but embedded C is used to implement the projects like real time applications

How to check for palindrome using Python logic

Here is an example that takes a user's input and checks if the input is a palindrome:

name = input("Write your word here:  ")
input("Press <enter> to check if the word is a palindrome.")
if str(name) == str(name)[::-1]:
    print("True")
else:
    print("False")

However, there is no need to even set up the if/else statement. You can directly print the result of the logical comparison, as shown here:

name = input("Write your word here:  ")
input("Press <enter> to check if the word is a palindrome.")
print(str(name) == str(name)[::-1])

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

Open source PDF library for C/C++ application?

If you're brave and willing to roll your own, you could start with a PostScript library and augment it to deal with PDF, taking advantage of Adobe's free online PDF reference.

Why does javascript map function return undefined?

You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.

What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

var arr = ['a','b',1];
var results = arr.filter(function(item){
    return typeof item ==='string';  
});

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How to export iTerm2 Profiles

Caveats: this answer only allows exports color settings.

iTerm => Preferences => Profiles => Colors => Load Presets => Export

Import shall be similar.

invalid byte sequence for encoding "UTF8"

This error means that records encoding in the file is different with respect to the connection. In this case iconv may return the error, sometimes even despite //IGNORE flag:

iconv -f ASCII -t utf-8//IGNORE < b.txt > /a.txt

iconv: illegal input sequence at position (some number)

The trick is to find incorrect characters and replace it. To do it on Linux use "vim" editor:

vim (your text file), press "ESC": button and type ":goto (number returned by iconv)"

To find non ASCII characters you may use the following command:

grep --color='auto' -P "[\x80-\xFF]"

If you remove incorrect characters please check if you really need to convert your file: probably the problem is already solved.

Center form submit buttons HTML / CSS

<style>
form div {
    width: 400px;   
    border: 1px solid black;
} 

form input[type='submit']  {
    display: inline-block;
    width: 70px;
}

div.submitWrapper  {
   text-align: center;    
}    
</style>
<form>

<div class='submitWrapper'>    
<input type='submit' name='submit' value='Submit'> 
 </div>

Also Check this jsfiddle

CardView not showing Shadow in Android L

I think if you check your manifest first if you wrote android:hardwareAccelerated="false" you should make it true to having shadow for the card Like this answer here

How can I add raw data body to an axios request?

How about using direct axios API?

axios({
  method: 'post',
  url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
  headers: {}, 
  data: {
    foo: 'bar', // This is the body part
  }
});

Source: axios api

How to find indices of all occurrences of one string in another in JavaScript?

the below code will do the job for you :

function indexes(source, find) {
  var result = [];
  for(i=0;i<str.length; ++i) {
    // If you want to search case insensitive use 
    // if (source.substring(i, i + find.length).toLowerCase() == find) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
    }
  }
  return result;
}

indexes("hello, how are you", "ar")

How do I create a simple 'Hello World' module in Magento?

First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.

Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.

Create a module

All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>
<config>
     <modules>
        <MyCompanyName_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </MyCompanyName_HelloWorld>
     </modules>
</config>

MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module.

Clear the application cache

Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application

  1. Go to System->Cache Management
  2. Select Refresh from the All Cache menu
  3. Click Save Cache settings

Now, we make sure that Magento knows about the module

  1. Go to System->Configuration
  2. Click Advanced
  3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"

If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

Setup the directory structure

Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql

And add a configuration file

touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml

and inside the configuration file, add the following, which is essentially a "blank" configuration.

<?xml version="1.0"?>
<config>
    <modules>
        <MyCompanyName_HelloWorld>
            <version>0.1.0</version>
        </MyCompanyName_HelloWorld>
    </modules>
</config>

Oversimplifying things, this configuration file will let you tell Magento what code you want to run.

Setting up the router

Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of

http://example.com/magento/index.php/helloworld

So, in your configuration file, add the following section.

<config>
<!-- ... -->
    <frontend>
        <routers>
            <!-- the <helloworld> tagname appears to be arbitrary, but by
            convention is should match the frontName tag below-->
            <helloworld>
                <use>standard</use>
                <args>
                    <module>MyCompanyName_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
    </frontend>
<!-- ... -->
</config>

What you're saying here is "any URL with the frontName of helloworld ...

http://example.com/magento/index.php/helloworld

should use the frontName controller MyCompanyName_HelloWorld".

So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php

Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception

Controller file was loaded but class does not exist

So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

<?php
class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
    }
}

What we've just setup is the module/frontName controller. This is the default controller and the default action of the module. If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName

So if you want to match this url

http://example.com/magento/index.php/helloworld/foo

You will have to have a FooController, which you can do this way :

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
<?php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo 'Foo Index Action';
    }

    public function addAction(){
        echo 'Foo add Action';
    }

    public function deleteAction(){
        echo 'Foo delete Action';
    }
}

Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it. So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foo because the second part of the url is and will always be the controllerName. This behaviour is an inheritance of the Zend Framework bundled in Magento.

You should now be able to hit the following URLs and see the results of your echo statements

http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete

So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

Python: most idiomatic way to convert None to empty string?

Use F string if you are using python v3.7

xstr = F"{s}"

Add a scrollbar to a <textarea>

What you need is overflow-y: scroll;

Demo

_x000D_
_x000D_
    textarea {_x000D_
        overflow-y: scroll;_x000D_
        height: 100px;_x000D_
        resize: none; /* Remove this if you want the user to resize the textarea */_x000D_
    }
_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_

Execute jar file with multiple classpath libraries from command prompt

You cannot use both -jar and -cp on the command line - see the java documentation that says that if you use -jar:

the JAR file is the source of all user classes, and other user class path settings are ignored.

You could do something like this:

java -cp lib\*.jar;. myproject.MainClass

Notice the ;. in the -cp argument, to work around a Java command-line bug. Also, please note that this is the Windows version of the command. The path separator on Unix is :.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

Difference between acceptance test and functional test?

They are the same thing.

Acceptance testing is performed on the completed system in as identical as possible to the real production/deployement environment before the system is deployed or delivered.

You can do acceptance testing in an automated manner, or manually.

Downloading a picture via urllib and python

For Python 3 you will need to import import urllib.request:

import urllib.request 

urllib.request.urlretrieve(url, filename)

for more info check out the link

How to merge every two lines into one from the command line?

There are more ways to kill a dog than hanging. [1]

awk '{key=$0; getline; print key ", " $0;}'

Put whatever delimiter you like inside the quotes.


References:

  1. Originally "Plenty of ways to skin the cat", reverted to an older, potentially originating expression that also has nothing to do with pets.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):

error_reporting(E_ALL);
ini_set('display_errors', 'On');

After that, restart server.

Why can't I declare static methods in an interface?

Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Just reset your simulator by clicking Simulator-> Reset Contents and Settings..

How to handle a lost KeyStore password in Android?

Brute is your best bet!

Here is a script that helped me out:

https://code.google.com/p/android-keystore-password-recover/wiki/HowTo

You can optionally give it a list of words the password might include for a very fast recover (for me it worked in <1 sec)

Right way to write JSON deserializer in Spring or extend it

With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.

Dont use this

<dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.12</version>  
        </dependency>  

Use this instead.

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

Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

FYI - none of the above worked for me in 2012 SP1...simple solution was to embed credentials in the shared data source and then tell Safari to trust the SSRS server site. Then it worked great! Took days chasing down supposed solutions like above only to find out integrated security won't work reliably on Safari - you have to mess with the keychain on the mac and then still wouldn't work reliably.

How do I get the web page contents from a WebView?

This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.

browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");

Finding the index of elements based on a condition using python list comprehension

Even if it's a late answer: I think this is still a very good question and IMHO Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access the indices of list elements according to a manually defined filter.

You could manually define a function, which provides that functionality:

def indices(list, filtr=lambda x: bool(x)):
    return [i for i,x in enumerate(list) if filtr(x)]

print(indices([1,0,3,5,1], lambda x: x==1))

Yields: [0, 4]

In my imagination the perfect way would be making a child class of list and adding the indices function as class method. In this way only the filter method would be needed:

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, *args)
    def indices(self, filtr=lambda x: bool(x)):
        return [i for i,x in enumerate(self) if filtr(x)]

my_list = MyList([1,0,3,5,1])
my_list.indices(lambda x: x==1)

I elaborated a bit more on that topic here: http://tinyurl.com/jajrr87

Returning anonymous type in C#

In C# 7 we can use tuples to accomplish this:

public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                       select new { SomeVariable = ....,
                                    AnotherVariable = ....}
                       ).ToList();

      return TheQueryFromDB
                .Select(s => (
                     SomeVariable = s.SomeVariable, 
                     AnotherVariable = s.AnotherVariable))
                 .ToList();
  }
}

You might need to install System.ValueTuple nuget package though.

Regular expression to match a line that doesn't contain a word

If you're just using it for grep, you can use grep -v hede to get all lines which do not contain hede.

ETA Oh, rereading the question, grep -v is probably what you meant by "tools options".

How to add hours to current date in SQL Server?

declare @hours int = 5;

select dateadd(hour,@hours,getdate())

How do I drop a foreign key in SQL Server?

I don't know MSSQL but would it not be:

alter table company drop **constraint** Company_CountryID_FK;

Copy file from source directory to binary directory using CMake

This is what I used to copy some resource files: the copy-files is an empty target to ignore errors

 add_custom_target(copy-files ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
    ${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
    )

Bootstrap 4 responsive tables won't take up 100% width

It's caused by the table-responsive class giving the table a property of display:block, which is strange because this overwrites the table classes original display:table and is why the table shrinks when you add table-responsive.

Most likely its down to bootstrap 4 still being in dev. You are safe to overwrite this property with your own class that sets display:table and it won't effect the responsiveness of the table.

e.g.

.table-responsive-fix{
   display:table;
}

Bootstrap Carousel Full Screen

I found an answer on the startbootstrap.com. Try this code:

CSS

html,
body {
    height: 100%;
}

.carousel,
.item,
.active {
    height: 100%;
}


.carousel-inner {
    height: 100%;
}

/* Background images are set within the HTML using inline CSS, not here */

.fill {
    width: 100%;
    height: 100%;
    background-position: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

footer {
    margin: 50px 0;
}

HTML

   <div class="carousel-inner">
        <div class="item active">
            <!-- Set the first background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide One');"></div>
            <div class="carousel-caption">
                <h2>Caption 1</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the second background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Two');"></div>
            <div class="carousel-caption">
                <h2>Caption 2</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the third background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Three');"></div>
            <div class="carousel-caption">
                <h2>Caption 3</h2>
            </div>
        </div>
    </div>

Source

What do parentheses surrounding an object/function/class declaration mean?

Andy Hume pretty much gave the answer, I just want to add a few more details.

With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.

The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.

I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:

var add_gen = function(n) {
  return function(x) {
    return n + x;
  };
};
var add2 = add_gen(2);
add2(3); // result is 5

What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.

The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.

With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:

for(var i=0; i<5; i++) {
  setTimeout(function(){alert(i)}, 10);
}

The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.

You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)

for(var i=0; i<5; i++) {
  setTimeout(
     (function(j) {
       return function(){alert(j)};
     })(i), 10);
}

With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.

I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.

Trigger a button click with JavaScript on the Enter key in a text box

Nobody noticed the html attibute "accesskey" which is available since a while.

This is a no javascript way to keyboard shortcuts stuffs.

accesskey_browsers

The accesskey attributes shortcuts on MDN

Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

_x000D_
_x000D_
let client = navigator.userAgent.toLowerCase(),_x000D_
    isLinux = client.indexOf("linux") > -1,_x000D_
    isWin = client.indexOf("windows") > -1,_x000D_
    isMac = client.indexOf("apple") > -1,_x000D_
    isFirefox = client.indexOf("firefox") > -1,_x000D_
    isWebkit = client.indexOf("webkit") > -1,_x000D_
    isOpera = client.indexOf("opera") > -1,_x000D_
    input = document.getElementById('guestInput');_x000D_
_x000D_
if(isFirefox) {_x000D_
   input.setAttribute("placeholder", "ALT+SHIFT+Z");_x000D_
} else if (isWin) {_x000D_
   input.setAttribute("placeholder", "ALT+Z");_x000D_
} else if (isMac) {_x000D_
  input.setAttribute("placeholder", "CTRL+ALT+Z");_x000D_
} else if (isOpera) {_x000D_
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");_x000D_
} else {'Point me to operate...'}
_x000D_
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
_x000D_
_x000D_
_x000D_

How to call an element in a numpy array?

Use numpy. array. flatten() to convert a 2D NumPy array into a 1D array print(array_2d) array_1d = array_2d. flatten() flatten array_2d print(array_1d)

How to watch and reload ts-node when TypeScript files change

Another way could be to compile the code first in watch mode with tsc -w and then use nodemon over javascript. This method is similar in speed to ts-node-dev and has the advantage of being more production-like.

 "scripts": {
    "watch": "tsc -w",
    "dev": "nodemon dist/index.js"
  },

Finding current executable's path without /proc/self/exe

Depending on the version of QNX Neutrino, there are different ways to find the full path and name of the executable file that was used to start the running process. I denote the process identifier as <PID>. Try the following:

  1. If the file /proc/self/exefile exists, then its contents are the requested information.
  2. If the file /proc/<PID>/exefile exists, then its contents are the requested information.
  3. If the file /proc/self/as exists, then:
    1. open() the file.
    2. Allocate a buffer of, at least, sizeof(procfs_debuginfo) + _POSIX_PATH_MAX.
    3. Give that buffer as input to devctl(fd, DCMD_PROC_MAPDEBUG_BASE,....
    4. Cast the buffer to a procfs_debuginfo*.
    5. The requested information is at the path field of the procfs_debuginfo structure. Warning: For some reason, sometimes, QNX omits the first slash / of the file path. Prepend that / when needed.
    6. Clean up (close the file, free the buffer, etc.).
  4. Try the procedure in 3. with the file /proc/<PID>/as.
  5. Try dladdr(dlsym(RTLD_DEFAULT, "main"), &dlinfo) where dlinfo is a Dl_info structure whose dli_fname might contain the requested information.

I hope this helps.

How to import Google Web Font in CSS file?

Jus go through the link

https://developers.google.com/fonts/docs/getting_started

To import it to stylesheet use

@import url('https://fonts.googleapis.com/css?family=Open+Sans');

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

SQL: IF clause within WHERE clause

    WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE  '%' + @OrderNumber END

In line case Condition will work properly.

How to redirect cin and cout to files?

Try this to redirect cout to file.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

How do I conditionally add attributes to React components?

juandemarco's answer is usually correct, but here is another option.

Build an object how you like:

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition)
  inputProps.disabled = true;

Render with spread, optionally passing other props also.

<input
    value="this is overridden by inputProps"
    {...inputProps}
    onChange={overridesInputProps}
 />

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

How do you Change a Package's Log Level using Log4j?

set the system property log4j.debug=true. Then you can determine where your configuration is running amuck.

Combine two data frames by rows (rbind) when they have different sets of columns

Most of the base R answers address the situation where only one data.frame has additional columns or that the resulting data.frame would have the intersection of the columns. Since the OP writes I am hoping to retain the columns that do not match after the bind, an answer using base R methods to address this issue is probably worth posting.

Below, I present two base R methods: One that alters the original data.frames, and one that doesn't. Additionally, I offer a method that generalizes the non-destructive method to more than two data.frames.

First, let's get some sample data.

# sample data, variable c is in df1, variable d is in df2
df1 = data.frame(a=1:5, b=6:10, d=month.name[1:5])
df2 = data.frame(a=6:10, b=16:20, c = letters[8:12])

Two data.frames, alter originals
In order to retain all columns from both data.frames in an rbind (and allow the function to work without resulting in an error), you add NA columns to each data.frame with the appropriate missing names filled in using setdiff.

# fill in non-overlapping columns with NAs
df1[setdiff(names(df2), names(df1))] <- NA
df2[setdiff(names(df1), names(df2))] <- NA

Now, rbind-em

rbind(df1, df2)
    a  b        d    c
1   1  6  January <NA>
2   2  7 February <NA>
3   3  8    March <NA>
4   4  9    April <NA>
5   5 10      May <NA>
6   6 16     <NA>    h
7   7 17     <NA>    i
8   8 18     <NA>    j
9   9 19     <NA>    k
10 10 20     <NA>    l

Note that the first two lines alter the original data.frames, df1 and df2, adding the full set of columns to both.


Two data.frames, do not alter originals
To leave the original data.frames intact, first loop through the names that differ, return a named vector of NAs that are concatenated into a list with the data.frame using c. Then, data.frame converts the result into an appropriate data.frame for the rbind.

rbind(
  data.frame(c(df1, sapply(setdiff(names(df2), names(df1)), function(x) NA))),
  data.frame(c(df2, sapply(setdiff(names(df1), names(df2)), function(x) NA)))
)

Many data.frames, do not alter originals
In the instance that you have more than two data.frames, you could do the following.

# put data.frames into list (dfs named df1, df2, df3, etc)
mydflist <- mget(ls(pattern="df\\d+"))
# get all variable names
allNms <- unique(unlist(lapply(mydflist, names)))

# put em all together
do.call(rbind,
        lapply(mydflist,
               function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                  function(y) NA)))))

Maybe a bit nicer to not see the row names of original data.frames? Then do this.

do.call(rbind,
        c(lapply(mydflist,
                 function(x) data.frame(c(x, sapply(setdiff(allNms, names(x)),
                                                    function(y) NA)))),
          make.row.names=FALSE))

Difference between Method and Function?

There is no functions in c#. There is methods (typical method:public void UpdateLeaveStatus(EmployeeLeave objUpdateLeaveStatus)) link to msdn and functors - variable of type Func<>

Insert entire DataTable into database at once instead of row by row?

Consider this approach, you don't need a for loop:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    bulkCopy.DestinationTableName = 
        "dbo.BulkCopyDemoMatchingColumns";

    try
    {
        // Write from the source to the destination.
        bulkCopy.WriteToServer(ExitingSqlTableName);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Adding attributes to an XML node

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string userName { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string passWord { get; set; }

    public int Age { get; set; }
    public string Name { get; set; }         
 }

 public class LoginNode 
 {
    public UserNode id { get; set; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

Symfony - generate url with parameter in controller

If you want absolute urls, you have the third parameter.

$product_url = $this->generateUrl('product_detail', 
    array(
        'slug' => 'slug'
    ),
    UrlGeneratorInterface::ABSOLUTE_URL
);

Remember to include UrlGeneratorInterface.

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

How to Change Margin of TextView

        TextView tv = (TextView)findViewById(R.id.item_title));
        RelativeLayout.LayoutParams mRelativelp = (RelativeLayout.LayoutParams) tv
                    .getLayoutParams();
        mRelativelp.setMargins(DptoPxConvertion(15), 0, DptoPxConvertion (15), 0);
        tv.setLayoutParams(mRelativelp);

    private int DptoPxConvertion(int dpValue)
    {
       return (int)((dpValue * mContext.getResources().getDisplayMetrics().density) + 0.5);
    }

getLayoutParams() of textview should be casted to the corresponding Params based on the Parent of the textview in xml.

<RelativeLayout>
   <TextView
    android:id="@+id/item_title">
</RelativeLayout>

To render the same real size on different devices use DptoPxConvertion() method which I have used above. setMargin(left,top,right,bottom) params will take values in pixel not in dp. For further reference see this Link Answer

Oracle client ORA-12541: TNS:no listener

You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)

Step 1 - Edit listener.ora

This file is located in:

  • Windows: %ORACLE_HOME%\network\admin\listener.ora.
  • Linux: $ORACLE_HOME/network/admin/listener.ora

Replace localhost with 0.0.0.0

# ...

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    )
  )

# ...

Step 2 - Restart Oracle services

  • Windows: WinKey + r

    services.msc
    
  • Linux (CentOs):

    sudo systemctl restart oracle-xe
    

enter image description here

Text size and different android screen sizes

Do not hardcode the sizes.

For flexibility ad new screen resolutions - the best practice is to place dummy TextView into layout to obtain the textSize:

<TextView
        android:id="@+id/dummyTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:text="TextView" />

And in your code for example:

TextView testTextView = (TextView) rootView.findViewById(R.id.dummyTextView);
float textSize = testTextView.getTextSize();

Keep textSize as a reference to which you can add constant or percetage size (by calculating).

Convert string with commas to array

use the built-in map function with an anonymous function, like so:

string.split(',').map(function(n) {return Number(n);});

[edit] here's how you would use it

var string = "0,1";
var array = string.split(',').map(function(n) {
    return Number(n);
});
alert( array[0] );

How is returning the output of a function different from printing it?

def add(x, y):
    return x+y

That way it can then become a variable.

sum = add(3, 5)

print(sum)

But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.

Choosing the default value of an Enum type without having to change values

One more way that might be helpful - to use some kind of "alias". For example:

public enum Status
{
    New = 10,
    Old = 20,
    Actual = 30,

    // Use Status.Default to specify default status in your code. 
    Default = New 
}

Best way to specify whitespace in a String.Split operation

You can just do:

string myStr = "The quick brown fox jumps over the lazy dog";
string[] ssizes = myStr.Split(' ');

MSDN has more examples and references:

http://msdn.microsoft.com/en-us/library/b873y76a.aspx

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

AJAX reload page with POST

If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page

Javascript to be used (always in myForm.php):

function submitform()
{
  document.getElementById('myForm').submit();
}

Suppose your form is on myForm.php: Method 1:

<form action="./myForm.php" method="post" id="myForm">
    ...
</form>

Method 2:

myForm.php:

<form action="./myFormActor.php" method="post" id="myForm">
    ...
</form>

myFormActor.php:

<?php
    //all code here, no output
    header("Location: ./myForm.php");
?>

What does <![CDATA[]]> in XML mean?

The Cdata is a data which you may want to pass to an xml parser and still not interpreted as an xml.

Say for eg :- You have an xml which has encapsulates question/answer object . Such open fields can have any data which does not strictly fall under basic data type or xml defined custom data types. Like --Is this a correct tag for xml comment ? .-- You may have a requirement to pass it as it is without being interpreted by the xml parser as another child element. Here Cdata comes to your rescue . By declaring as Cdata you are telling the parser don't treat the data wrapped as an xml (though it may look like one )

Date Format in Swift

swift 3

func dataFormat(dataJ: Double) -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .none
        let date = Date(timeIntervalSince1970: dataJ)
        return (dataJ != nil) ? "Today, \(dateFormatter.string(from: date))" : "Date Invalid"

    }

AngularJS view not updating on model change

As Ajay beniwal mentioned above you need to use Apply to start digestion.

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

Show how many characters remaining in a HTML text box using JavaScript

HTML:

 <form>
  <textarea id='text' maxlength='10'></textarea>
  <div id='msg'>10 characters left</div>
  <div id='lastChar'></div>
</form>

JS:

function charCount() {
  var textEntered = document.getElementById('text').value;
  var msg = document.getElementById('msg');
  var counter = (10-(textEntered.length));
  msg.textContent = counter+' characters left';
}

var el = document.getElementById('text');
el.addEventListener('keyup',charCount,false);

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:

  • success() returns the original promise
  • then() returns a new promise

The difference is then() drives sequential operations, since each call returns a new promise.

$http.get(/*...*/).
  then(function seqFunc1(response){/*...*/}).
  then(function seqFunc2(response){/*...*/})
  1. $http.get()
  2. seqFunc1()
  3. seqFunc2()

success() drives parallel operations, since handlers are chained on the same promise.

$http(/*...*/).
  success(function parFunc1(data){/*...*/}).
  success(function parFunc2(data){/*...*/})
  1. $http.get()
  2. parFunc1(), parFunc2() in parallel

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

How do I check that a Java String is not all whitespaces?

This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is null.

We want false if (1) s is null or (2) s is empty or (3) s only contains whitechars.

public static boolean containsNonWhitespaceChar(String s) {
  return !((s == null) || "".equals(s.trim()));
}

Delete a dictionary item if the key exists

There is also:

try:
    del mydict[key]
except KeyError:
    pass

This only does 1 lookup instead of 2. However, except clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.

PreparedStatement with list of parameters in a IN clause

What you can do is dynamically build the select string (the 'IN (?)' part) by a simple for loop as soon as you know how many values you need to put inside the IN clause. You can then instantiate the PreparedStatement.

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

Notepad++ Multi editing

Notepad++ only has column editing. This is not completely the same as multiple cursors.

Sublime Text has a marvelous implementation of this, might be worth checking out...
It's a relatively new editor (2011) that is gaining popularity quite fast: http://www.google.com/trends/explore#q=Notepad%2B%2B%2C%20Sublime%20Text&cmpt=q

Edit: Apparently somewhere around Notepad++ version 6.x multi-cursor editing got added, but there are still a few more advanced features for it in Sublime, like "select next occurrence".

How to position text over an image in css

How about something like this: http://jsfiddle.net/EgLKV/3/

Its done by using position:absolute and z-index to place the text over the image.

_x000D_
_x000D_
#container {_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  position: relative;_x000D_
}_x000D_
#image {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
}_x000D_
#text {_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  color: white;_x000D_
  font-size: 24px;_x000D_
  font-weight: bold;_x000D_
  left: 150px;_x000D_
  top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
  <p id="text">_x000D_
    Hello World!_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to link home brew python version and set it as default

If you used

brew install python

before 'unlink' you got

brew info python
/usr/local/Cellar/python/2.7.11

python -V
Python 2.7.10

so do

brew unlink python && brew link python

and open a new terminal shell

python -V
Python 2.7.11

How to make an alert dialog fill 90% of screen size?

According to Android platform developer Dianne Hackborn in this discussion group post, Dialogs set their Window's top level layout width and height to WRAP_CONTENT. To make the Dialog bigger, you can set those parameters to MATCH_PARENT.

Demo code:

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    Dialog d = adb.setView(new View(this)).create();
    // (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(d.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    d.show();
    d.getWindow().setAttributes(lp);

Note that the attributes are set after the Dialog is shown. The system is finicky about when they are set. (I guess that the layout engine must set them the first time the dialog is shown, or something.)

It would be better to do this by extending Theme.Dialog, then you wouldn't have to play a guessing game about when to call setAttributes. (Although it's a bit more work to have the dialog automatically adopt an appropriate light or dark theme, or the Honeycomb Holo theme. That can be done according to http://developer.android.com/guide/topics/ui/themes.html#SelectATheme )

WebAPI to Return XML

Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage( so that I get a return compatible with IHttpActionResult:

return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
       {
           Content = new ObjectContent<SomeType>(objectToSerialize, 
              new System.Net.Http.Formatting.XmlMediaTypeFormatter { 
                  UseXmlSerializer = true 
              })
       });

How can I create a self-signed cert for localhost?

you could try mkcert.

macos: brew install mkcert

PHP Get all subdirectories of a given directory

you can use glob() with GLOB_ONLYDIR option

or

$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);

How can I convert string to datetime with format specification in JavaScript?

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

How to find all combinations of coins when given some dollar value

Let C(i,J) the set of combinations of making i cents using the values in the set J.

You can define C as that:

enter image description here

(first(J) takes in a deterministic way an element of a set)

It turns out a pretty recursive function... and reasonably efficient if you use memoization ;)

How to pass all arguments passed to my bash script to a function of mine?

Use the $@ variable, which expands to all command-line parameters separated by spaces.

abc "$@"

How do I call an Angular 2 pipe with multiple arguments?

In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I'm aware to the fact that in the original question Jenkins pipeline was not mentioned, but if it is still applicable (using it), I find this solution easy to maintain and convenient.

This approach describe the settings required to compose a Jenkins pipeline that "polls" (list) dynamically all branches of a particular repository, which then lets the user run the pipeline with some specific branch when running a build of this job.

The assumptions here are:

  • The Jenkins server is 2.204.2 (hosted on Ubuntu 18.04)
  • The repository is hosted in a BitBucket.

First thing to do is to provide Jenkins credentials to connect (and "fetch") to the private repository in BitBucket. This can be done by creating an SSH key pair to "link" between the Jenkins (!!) user on the machine that hosts the Jenkins server and the (private) BitBucket repository.

  1. First thing is to create an SSH key to the Jenkins user (which is the user that runs the Jenkins server - it is most likely created by default upon the installation):

    guya@ubuntu_jenkins:~$ sudo su jenkins 
    [sudo] password for guya:
    jenkins@ubuntu_jenkins:/home/guya$ ssh-keygen
    

    The output should look similar to the following:

Generating public/private rsa key pair. Enter file in which to save the key
(/var/lib/jenkins/.ssh/id_rsa): Created directory '/var/lib/jenkins/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa. Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub. The key fingerprint is: SHA256:q6PfEthg+74QFwO+esLbOtKbwLG1dhtMLfxIVSN8fQY jenkins@ubuntu_jenkins The key's randomart image is: +---[RSA 2048]----+ | . .. o.E. | | . . .o... o | | . o.. o | | +.oo | | . ooX..S | |..+.Bo* . | |.++oo* o. | |..+*..*o | | .=+o==+. | +----[SHA256]-----+ jenkins@ubuntu_jenkins:/home/guya$

  1. Now the content of this SSH key needs to be set in the BitBucket repository as follows:
  • Create (add) an SSH key in the BitBucket repository by going to: Settings --> Access keys --> Add key.
  • Give the key Read permissions and copy the content of the PUBLIC key to the "body" of the key. The content of the key can be displayed by running: cat /var/lib/jenkins/.ssh/id_rsa.pub
  1. After that the SSH key was set in the BitBucket repository, we need to "tell" Jenkins to actually USE it when it tries to fetch (read in this case) the content of the repository. NOTE that by letting Jenkins know, actually means let user jenkins this "privilege".

This can be done by adding a new  SSH User name with private key to the Jenkins --> Credentials --> System --> Global Credentials --> Add credentials.

  • In the ID section put any descriptive name to the key.
  • In the Username section put the user name of the Jenkins server which is jenkins.
  • Tick the Private key section and paste the content of the PRIVATE key that was generated earlier by copy-paste the content of: ~/.ssh/id_rsa. This is the private key which start with the string:-----BEGIN RSA PRIVATE KEY----- and ends with the string: -----END RSA PRIVATE KEY-----. Note that this entire "block" should be copied-paste into the above section.
  1. Install the Git Parameter plugin that can be found in its official page here

  2. The very minimum pipeline that is required to list (dynamically) all the branches of a given repository is as follows:

    pipeline 
    { 
        agent any parameters
        { 
            gitParameter branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH' 
        }
        stages 
        { 
           stage("list all branches") 
           { 
               steps 
               { 
                    git branch: "${params.BRANCH}", credentialsId: "SSH_user_name_with_private_key", url: "ssh://[email protected]:port/myRepository.git" 
               } 
          } 
       } 
    }
    

NOTES:

  • The defaultValue is set to master so that if no branches exist - it will be displayed in the "drop list" of the pipeline.
  • The credentialsId has the name of the credentials configured earlier.
  • In this case I used the SSH URL of the repository in the url parameter.
  • This answer assumes (and configured) that the git server is BitBucket. I assume that all the "administrative" settings done in the initial steps, have their equivalent settings in GitHub.

NVIDIA NVML Driver/library version mismatch

Surprise surprise, rebooting solved the issue (I thought I had already tried that).

The solution Robert Crovella mentioned in the comments may also be useful to someone else, since it's pretty similar to what I did to solve the issue the first time I had it.

How to embed a video into GitHub README.md?

Update Feb. 2021, as noted by Abhishek Singh in the comments, and Nat Friedman on Twitter:

You can now – finally! – drop images and videos (mp4, gif) onto the Markdown file editor on GitHub.

image and video

Paste works too, if you're into that kind of thing.
It's worked in issues and PRs for a while; what's new here is support in markdown files.

GitHub Enterprise Server tends to lag http://github.com by a couple of months, but it will get there in a future release.

Kyle Daigle (Senior Director of Special Projects at GitHub) adds:

Currently, the file is stored as an asset outside the repository (sort of like an image uploaded to an image).
(Uploads to githubusercontent and stores it there. Then makes a link in the markdown to that uploaded image.)

The team is interested in exploring adding the image to the repo too... would you want something like that?

Sven-Michael Stübe comments:

I usually add the images to my repo. Especially if you host your blog as github page w/ a custom domain.

But I think this feature would also add a lot of complexity. It's not a big pain to add the image manually. For PRs+Comments the drag&drop is more essential

Kyle answers:

For the blog case (which is what made us think about image upload to the repo) you're totally right.
This type of drag and drop is helpful when adding an image to a README or other in-repo documentation though (when you don't want to upload to the repo).

That feature has come a long way since its initial proposal... back in 2012(!)


Update Dec. 2020: see "Video upload public beta ", which embeds video (embedding only, not link/reference)

https://i0.wp.com/user-images.githubusercontent.com/22751162/101841526-ebf6ff00-3afa-11eb-965d-5ce11efdb9f8.png?ssl=1


2010: The "Github Flavored Markdown" doesn't support this kind of feature for any page:

An old support thread "Embed YouTube videos in markdown files" stated:

With pages.github.io, yes, everywhere else, no.

(Note: as detailed in "Github Top-Level Project Page", github.io is the new domain for user and organization pages since April 2013.
The page GitHub publication is presented here)

This could be a feature request like the syntax highlighting was.

For instance: "HTML5 video in markdown" (August 2010):

Is there any way to implement a HTML5 video into the README.markdown file?

Not currently but we might be expanding what you can do with the READMEs in the future.

In the meantime, you can do this with GitHub Pages and our Wikis.


Benjamin Oakes confirms in the comments (May 2012):

I sent in a support request. The response was that embedding videos is not supported.

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

Can't load AMD 64-bit .dll on a IA 32-bit platform

Try this:

  1. Download and install a 32-bit JDK.
  2. Go to eclipse click on your project (Run As ? Run Configurations...) under Java Application branch.
  3. Go to the JRE tab and select Alternate JRE. Click on Installed JRE button, add your 32-bit JRE and select.

"fatal: Not a git repository (or any of the parent directories)" from git status

in my case, i had the same problem while i try any git -- commands (eg git status) using windows cmd. so what i do is after installing git for window https://windows.github.com/ in the environmental variables, add the class path of the git on the "PATH" varaiable. usually the git will installed on C:/user/"username"/appdata/local/git/bin add this on the PATH in the environmental variable

and one more thing on the cmd go to your git repository or cd to where your clone are on your window usually they will be stored on the documents under github

cd Document/Github/yourproject

after that you can have any git commands

Removing input background colour for Chrome autocomplete?

i use this. work for me. remove yellow background of field.

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active,
input:-webkit-autofill:valid,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus
{
    -webkit-transition-delay: 99999s;
    -webkit-text-fill-color:#D7D8CE;
}

Possible to change where Android Virtual Devices are saved?

Add a new user environment variable (Windows 7):

  1. Start Menu > Control Panel > System > Advanced System Settings (on the left) > Environment Variables

  2. Add a new user variable (at the top) that points your home user directory:

    Variable name: ANDROID_SDK_HOME
    Variable value: a path to a directory of your choice

AVD Manager will use this directory to save its .android directory into it.

For those who may be interested, I blogged about my first foray into Android development...
Android "Hello World": a Tale of Woe

Alternatively, you can use the Rapid Environment Editor to set the environment variables.

How to set a timer in android

Probably Timerconcept

new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

 public void onTick(long millisUntilFinished) {
  }
  public void onFinish() {
 }
}.start();

or

Method 2 ::

Program the timer

Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

Go into the run method and add the following code.

//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {

    @Override
    public void run() {
        TextView tv = (TextView) findViewById(R.id.main_timer_text);
        tv.setText(String.valueOf(time));
        time += 1;
    }

});

HashSet vs LinkedHashSet

The answer lies in which constructors the LinkedHashSet uses to construct the base class:

public LinkedHashSet(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor, true);      // <-- boolean dummy argument
}

...

public LinkedHashSet(int initialCapacity) {
    super(initialCapacity, .75f, true);            // <-- boolean dummy argument
}

...

public LinkedHashSet() {
    super(16, .75f, true);                         // <-- boolean dummy argument
}

...

public LinkedHashSet(Collection<? extends E> c) {
    super(Math.max(2*c.size(), 11), .75f, true);   // <-- boolean dummy argument
    addAll(c);
}

And (one example of) a HashSet constructor that takes a boolean argument is described, and looks like this:

/**
 * Constructs a new, empty linked hash set.  (This package private
 * constructor is only used by LinkedHashSet.) The backing
 * HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this
 *             constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}

Checking if an Android application is running in the background

Since it isn't already mentioned, I will suggest the readers to explore ProcessLifecycleOwner available through Android Architecture components

ImportError: No module named psycopg2

i have the same problem, but this piece of snippet alone solved my problem.

pip install psycopg2

Push to GitHub without a password using ssh-key

Additionally for gists, it seems you must leave out the username

git remote set-url origin [email protected]:<Project code>

C# Enum - How to Compare Value

You can use extension methods to do the same thing with less code.

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}

static class AccountTypeMethods
{
    public static bool IsRetailer(this AccountType ac)
    {
        return ac == AccountType.Retailer;
    }
}

And to use:

if (userProfile.AccountType.isRetailer())
{
    //your code
}

I would recommend to rename the AccountType to Account. It's not a name convention.

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

ImportError: No module named sklearn.cross_validation

Make sure you have Anaconda installed and then create a virtualenv using conda. This will ensure all the imports work

Python 2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Mar  9 2015, 16:20:48) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> from sklearn.cross_validation import train_test_split

Recursive search and replace in text files on Mac and Linux

https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

Usage looks like:

$ ls test
a  d  d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"                         
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye

Checking if date is weekend PHP

For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".

Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.

EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).

With block equivalent in C#?

You could use the argument accumulator pattern.

Big discussion about this here:

http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx

a page can have only one server-side form tag

Does your page contain these

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
</asp:content>

tags, and are all your controls inside these? You should only have the Form tags in the MasterPage.


Here are some of my understanding and suggestion:

Html element can be put in the body of html pages and html page does support multiple elements, however they can not be nested each other, you can find the detailed description from the W3C html specification:

The FORM element

http://www.w3.org/MarkUp/html3/forms.html

And as for ASP.NET web form page, it is based on a single server-side form element which contains all the controls inside it, so generally we do not recommend that we put multiple elements. However, this is still supported in ASP.NET page(master page) and I think the problem in your master page should be caused by the unsupported nested element, and multiple in the same level should be ok. e.g:

In addition, if what you want to do through multiple forms is just make our page posting to multiple pages, I think you can consider using the new feature for cross-page posting in ASP.NET 2.0. This can help us use button controls to postback to different pages without having multpile forms on the page:

Cross-Page Posting in ASP.NET Web Pages

http://msdn2.microsoft.com/en-us/lib...39(VS.80).aspx

http://msdn2.microsoft.com/en-us/lib...40(VS.80).aspx

Is it possible to specify a different ssh port when using rsync?

I found this solution on Mike Hike Hostetler's site that worked perfectly for me.

# rsync -avz -e "ssh -p $portNumber" user@remoteip:/path/to/files/ /local/path/

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

Entity Framework code first unique column

From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:

this.Property(p => p.UserName)
    .HasColumnAnnotation("Index", new IndexAnnotation(new[] { 
        new IndexAttribute("Index") { IsUnique = true } 
    }
));

This will create the following SQL script:

CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
    [UserName] ASC
)
WITH (
    PAD_INDEX = OFF, 
    STATISTICS_NORECOMPUTE = OFF, 
    SORT_IN_TEMPDB = OFF, 
    IGNORE_DUP_KEY = OFF, 
    DROP_EXISTING = OFF, 
    ONLINE = OFF, 
    ALLOW_ROW_LOCKS = ON, 
    ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]

If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:

Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'. 
The duplicate key value is (...).
The statement has been terminated.

Again, column annotations are not available in Entity Framework prior to version 6.1.

Modify SVG fill color when being served as Background-Image

 .icon { 
  width: 48px;
  height: 48px;
  display: inline-block;
  background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%; 
  background-size: cover;
}

.icon-orange { 
  -webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4); 
  filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4); 
}

.icon-yellow {
  -webkit-filter: hue-rotate(70deg) saturate(100);
  filter: hue-rotate(70deg) saturate(100);
}

codeben article and demo

What are the options for (keyup) in Angular2?

Have hit the same problem today.

These are poorly documented, an open issue exist.

Some for keyup, like space:

<input (keyup.space)="doSomething()">
<input (keyup.spacebar)="doSomething()">  

Some for keydown
(may work for keyup too):

<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.alt)="...">
<input (keydown.shift.esc)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.f4)="...">

All above are from below links:

https://github.com/angular/angular/issues/18870
https://github.com/angular/angular/issues/8273
https://github.com/angular/angular/blob/master/packages/platform-browser/src/dom/events/key_events.ts
https://alligator.io/angular/binding-keyup-keydown-events/

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

You could try jQuery UI's .position method.

$("#mydiv").position({
  of: $('#mydiv').parent(),
  my: 'left+200 top+200',
  at: 'left top'
});

Check the working demo.

Visual Studio Code Automatic Imports

I used Auto Import plugin by steoates which is quite easy.

Automatically finds, parses and provides code actions and code completion for all available imports. Works with Typescript and TSX.

How to make correct date format when writing data to Excel

This is an old thread. By this time, people either use OpenXML. OpenXML is much better. Well, many people like me are stuck because the initial developers use the interops.

I had same struggle for couple hours. I have tried everything here and other usage. It still gave me numerical representation.

Then I found out that I set the style. The style property ruined everything. I just added the NumberFormatproperty

Here is what I did. It works

                //set the font style and size
                Excel.Style styleDate = MyBook.Styles.Add("StyleDate");
                styleDate.NumberFormat = "mm/dd/yyyy";//remember to include this when setting style property
                styleDate.Font.Size = 10;
                styleDate.Font.Name = "Arial"

                //the function will return datetime value from database or whatever
                DateTime DtVal= GetdatetimeVal(); 

                xlWorkSheet.Cells[Row, Col].Style = styleDate
                xlWorkSheet.Cells[Row, Col] = DtVal;

How to run batch file from network share without "UNC path are not supported" message?

My env windows10 2019 lts version and I add this two binray data ,fix this error

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor DisableUNCCheck value 1 Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Command Processor DisableUNCCheck value 1

How to get $HOME directory of different user in bash script?

Quick and dirty, and store it in a variable:

USER=somebody
USER_HOME="$(echo -n $(bash -c "cd ~${USER} && pwd"))"

Label on the left side instead above an input field

<div class="control-group">
   <label class="control-label" for="firstname">First Name</label>
   <div class="controls">
    <input type="text" id="firstname" name="firstname"/>
   </div>
</div>

Also we can use it Simply as

<label>First name:
    <input type="text" id="firstname" name="firstname"/>
</label>

How to get the query string by javascript?

I have use this method

function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case I forgot to add providers: [INPUT_VALUE_ACCESSOR] to my custom component

I had INPUT_VALUE_ACCESSOR created as:

export const INPUT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TextEditorComponent),
  multi: true,
};

Change arrow colors in Bootstraps carousel

a little example that works for me

    .carousel-control-prev,
    .carousel-control-next{
        height: 50px;
        width: 50px;
        outline: $color-white;
        background-size: 100%, 100%;
        border-radius: 50%;
        border: 1px solid $color-white;
        background-color: $color-white;
    }

    .carousel-control-prev-icon { 
        background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); 
        width: 30px;
        height: 48px;
    }
    .carousel-control-next-icon { 
        background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E");
        width: 30px;
        height: 48px;
    }

Passing capturing lambda as function pointer

A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):

#include <iostream>


template<typename Function>
struct function_traits;

template <typename Ret, typename... Args>
struct function_traits<Ret(Args...)> {
    typedef Ret(*ptr)(Args...);
};

template <typename Ret, typename... Args>
struct function_traits<Ret(*const)(Args...)> : function_traits<Ret(Args...)> {};

template <typename Cls, typename Ret, typename... Args>
struct function_traits<Ret(Cls::*)(Args...) const> : function_traits<Ret(Args...)> {};

using voidfun = void(*)();

template <typename F>
voidfun lambda_to_void_function(F lambda) {
    static auto lambda_copy = lambda;

    return []() {
        lambda_copy();
    };
}

// requires C++20
template <typename F>
auto lambda_to_pointer(F lambda) -> typename function_traits<decltype(&F::operator())>::ptr {
    static auto lambda_copy = lambda;
    
    return []<typename... Args>(Args... args) {
        return lambda_copy(args...);
    };
}



int main() {
    int num;

    void(*foo)() = lambda_to_void_function([&num]() {
        num = 1234;
    });
    foo();
    std::cout << num << std::endl; // 1234

    int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
        num = a;
        return a;
    });
    std::cout << bar(4321) << std::endl; // 4321
    std::cout << num << std::endl; // 4321
}

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

What does "exited with code 9009" mean during this build?

I have had the error 9009 when my post build event script was trying to run a batch file that did not exist in the path specified.

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Hey Please use / in your web.xml (instead of /*)

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

Change Row background color based on cell value DataTable

I Used rowCallBack datatable property it is working fine. PFB :-

"rowCallback": function (row, data, index) {

                        if ((data[colmindx] == 'colm_value')) { 
                            $(row).addClass('OwnClassName');
                        }
                        else if ((data[colmindx] == 'colm_value')) {
                                $(row).addClass('OwnClassStyle');
                            }
                    }

Is it possible to remove inline styles with jQuery?

$('div[style*=block]').removeAttr('style');

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

In the %run magic documentation you can find:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

Therefore, supplying -i does the trick:

%run -i 'script.py'

The "correct" way to do it

Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

I'd like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you're constantly editing the other file, then autoreload comes to your help.

Your example would look like this:
script.py

import matplotlib.pyplot as plt

def myplot(f, x):
    """
    :param f: function to plot
    :type f: callable
    :param x: values for x
    :type x: list or ndarray

    Plots the function f(x).
    """
    # yes, you can pass functions around as if
    # they were ordinary variables (they are)
    plt.plot(x, f(x))
    plt.xlabel("Eje $x$",fontsize=16)
    plt.ylabel("$f(x)$",fontsize=16)
    plt.title("Funcion $f(x)$")

Jupyter console

In [1]: import numpy as np

In [2]: %load_ext autoreload

In [3]: %autoreload 1

In [4]: %aimport script

In [5]: def f(x):
      :     return np.exp(-x ** 2)
      :
      :

In [6]: x = np.linspace(-1, 3, 100)

In [7]: script.myplot(f, x)

In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File:      [...]\script.py
Type:      function

How to find and replace string?

Not exactly that, but std::string has many replace overloaded functions.

Go through this link to see explanation of each, with examples as to how they're used.

Also, there are several versions of string::find functions (listed below) which you can use in conjunction with string::replace.

  • find
  • rfind
  • find_first_of
  • find_last_of
  • find_first_not_of
  • find_last_not_of

Also, note that there are several versions of replace functions available from <algorithm> which you can also use (instead of string::replace):

  • replace
  • replace_if
  • replace_copy
  • replace_copy_if

How to set a ripple effect on textview or imageview on Android?

Add android:clickable="true" android:focusable="true"

For Ripple Effect

android:background="?attr/selectableItemBackgroundBorderless"

For Selectable Effect

android:background="?android:attr/selectableItemBackground"

For Button effect

android:adjustViewBounds="true" style="?android:attr/borderlessButtonStyle"

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Change Toolbar color in Appcompat 21

You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    } 

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    }



    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);
        }

      //Step 3: Changing the color of title and subtitle.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
            }
        }

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                              innerView.post(new Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });
                        }
                    }
                }
            }
        }
    }



}

then refer to it in your layout file. Now you can set a custom color using

toolbar.setItemColor(Color.Red);

Sources:

I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

Multiple modals overlay

No script solutions , using only css given you have two layers of modals, set the 2nd modal to a higher z index

.second-modal { z-index: 1070 }

div.modal-backdrop + div.modal-backdrop {
   z-index: 1060; 
}

Converting BitmapImage to Bitmap and vice versa

If you just need to go from BitmapImage to Bitmap it's quite easy,

private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
    {
        return new Bitmap(bitmapImage.StreamSource);
    }

Django: OperationalError No Such Table

I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate. Now it works just fine. Remember, by running python manage.py makemigrations first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.

Binding a WPF ComboBox to a custom list

To bind the data to ComboBox

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

ComboData looks like:

public class ComboData
{ 
  public int Id { get; set; } 
  public string Value { get; set; } 
}

(note that Id and Value have to be properties, not class fields)

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

jQuery - setting the selected value of a select control via its text description

If you are trying to bind select with ID then the following code worked for me.

<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
    <option value="0" class="notag" id="id0_0">--Select--</option>
    <option class="notag" value="338" id="id0_338"  >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro  > £114.00</option>
    <option class="notag" value="282" id="id0_282"  >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00</option>
    <option class="notag" value="265" id="id0_265"  >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro  > £114.00</option>
    <option class="notag" value="101" id="id0_101"  >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI  > £114.00</option>
    <option class="notag" value="105" id="id0_105"  >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI  > £114.00</option></select>

AND THIS IS TEH JS CODE

$( document ).ready(function() {
      var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00";
      alert(text);
$("#groupsel_0 option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text;
}).prop('selected', true);
});

How to use Apple's new San Francisco font on a webpage

If the user is running El Capitan or higher, it will work in Chrome with

font-family: 'BlinkMacSystemFont';

Maximum and minimum values in a textbox

Set Attributes in CodeBehind

textWeight.Attributes.Add("minimum", minValue.ToString());
textWeight.Attributes.Add("maximum", maxValue.ToString());

Result:

<input type="text" minimum="0" maximum="100" id="textWeight" value="2" name="textWeight">

By jQuery

    jQuery(document).ready(function () {

        var textWeight = $("input[type='text']#textWeight");

        textWeight.change(function () {

              var min = textWeight.attr("minimum");

              var max= textWeight.attr("maximum");

              var value = textWeight.val();

              if(val < min || val > max)
              {
                    alert("Your Message");

                    textWeight.val(min);
              }

        });
    });

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

What is the best JavaScript code to create an img element

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

React Native fixed footer

The way I did this was to have a view (lets call it P) with flex 1, then inside that view have 2 more views (C1 and C2) with flex 0.9 and 0.1 respectively (you can change the flex heights to required values). Then, inside the C1 have a scrollview. This worked perfectly for me. Example below.

<View style={{flex: 1}}>
    <View style={{flex: 0.9}}>
        <ScrollView>
            <Text style={{marginBottom: 500}}>scrollable section</Text>
        </ScrollView>
    </View>
    <View style={{flex: 0.1}}>
        <Text>fixed footer</Text>
    </View>
</View>

How to run an .ipynb Jupyter Notebook from terminal?

In your Terminal run ipython:

ipython

then locate your script and put there:

%run your_script.ipynb

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

Change bootstrap navbar background color and font color

No need for the specificity .navbar-default in your CSS. Background color requires background-color:#cc333333 (or just background:#cc3333). Finally, probably best to consolidate all your customizations into a single class, as below:

.navbar-custom {
    color: #FFFFFF;
    background-color: #CC3333;
}

..

<div id="menu" class="navbar navbar-default navbar-custom">

Example: http://www.bootply.com/OusJAAvFqR#

What is a mutex?

Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).

In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.

pthread library provides support for Mutex.

typedef union
{
  struct __pthread_mutex_s
  {
    ***int __lock;***
    unsigned int __count;
    int __owner;
#ifdef __x86_64__
    unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
    short __spins;
    short __elision;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
# define __PTHREAD_SPINS             0, 0
#else
    unsigned int __nusers;
    __extension__ union
    {
      struct
      {
        short __espins;
        short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS         { 0, 0 }
      } __elision_data;
      __pthread_slist_t __list;
    };
#endif

This is the structure for mutex data type i.e pthread_mutex_t. When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.

This ensure that no two processes/threads can access the critical section at same time.

Best JavaScript compressor

YUI Compressor is the way to go. It has a great compression rate, is well tested and is in use among many top sites, and, well, personally recommended by me.

I've used it for my projects without a single JavaScript error or hiccup. And it has nice documentation.

I've never used its CSS compression capabilities, but they exist as well. CSS compression works just as well.

Note: Although Dean Edwards's /packer/ achieves a better compression rate than YUI Compressor, I ran into a few JavaScript errors when using it.

How to "properly" print a list?

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".

I don't understand -Wl,-rpath -Wl,

One other thing. You may need to specify the -L option as well - eg

-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz

or you may end up with an error like

ld: cannot find -lbaz

ios app maximum memory budget

Working with the many answers above, I have implemented Apples new method os_proc_available_memory() for iOS 13+ coupled with NSByteCountFormatter which offers a number of useful formatting options for nicer output of the memory:

#include <os/proc.h>

....

- (NSString *)memoryStringForBytes:(unsigned long long)memoryBytes {
    NSByteCountFormatter *byteFormatter = [[NSByteCountFormatter alloc] init];
    byteFormatter.allowedUnits = NSByteCountFormatterUseGB;
    byteFormatter.countStyle = NSByteCountFormatterCountStyleMemory;
    NSString *memoryString = [byteFormatter stringFromByteCount:memoryBytes];
    return memoryString;
}

- (void)memoryLoggingOutput {
    if (@available(iOS 13.0, *)) {
        NSLog(@"Physical memory available: %@", [self memoryStringForBytes:[NSProcessInfo processInfo].physicalMemory]);
        NSLog(@"Memory A (brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory()]);
        NSLog(@"Memory B (no brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory]);
    }
}

Important note: Do not forget the () at the end. I have included both NSLog options in in the memoryLoggingOutput method because it does not warn you that they are missing and failure to include the brackets returns an unexpected yet constant result.

The string returned from the method memoryStringForBytes outputs values like so:

NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.93 GB
// 2 seconds later
NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.84 GB

What characters do I need to escape in XML documents?

It depends on the context. For the content, it is < and &, and ]]> (though a string of three instead of one character).

For attribute values, it is <, &, ", and '.

For CDATA, it is ]]>.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Since you say that any language is acceptable, the natural choice is PostGIS:

SELECT * FROM places
WHERE ST_DistanceSpheroid(geom, $location, $spheroid) < $max_metres;

If you want to use WGS datum, you should set $spheroid to 'SPHEROID["WGS 84",6378137,298.257223563]'

Assuming that you have indexed places by the geom column, this should be reasonably efficient.

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

If you are using IIS Express and VS 2017:

Go to the Web Application Properties > Web Tab > Servers Section > And change the Bitness to x64.

Windows command to convert Unix line endings?

I cloned my git project using the git bash on windows. All the files then had LF endings. Our repository has CRLF endings as default.

I deleted the project, and then cloned it again using the Windows Command Prompt. The CRLF endings were intact then. In my case, if I had changed the endings for the project, then it would've resulted in a huge commit and would've caused trouble for my teammates. So, did it this way. Hope this helps somebody.

How do I wrap text in a pre tag?

I've found that skipping the pre tag and using white-space: pre-wrap on a div is a better solution.

 <div style="white-space: pre-wrap;">content</div>

PHP Warning: PHP Startup: Unable to load dynamic library

php -r "echo php_ini_loaded_file();"

Will show in CLI current ini loaded file, search there for Your extension, path to it is incorrect.

Eloquent Collection: Counting and Detect Empty

so Laravel actually returns a collection when just using Model::all(); you don't want a collection you want an array so you can type set it. (array)Model::all(); then you can use array_filter to return the results

$models = (array)Model::all()
$models = array_filter($models);
if(empty($models))
{
 do something
}

this will also allow you to do things like count().

How to force DNS refresh for a website?

So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.

Replace spaces with dashes and make all letters lower-case

Above answer can be considered to be confusing a little. String methods are not modifying original object. They return new object. It must be:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

I did make some adjustment to make the image aligned at center horizontal:

// the space between the image and text
        let spacing = CGFloat(36.0);

        // lower the text and push it left so it appears centered
        //  below the image
        let imageSize = tutorialButton.imageView!.frame.size;
        tutorialButton.titleEdgeInsets = UIEdgeInsetsMake(
            0, -CGFloat(imageSize.width), -CGFloat(imageSize.height + spacing), 0.0);

        // raise the image and push it right so it appears centered
        //  above the text
        let titleSize = tutorialButton.titleLabel!.frame.size;
        tutorialButton.imageEdgeInsets = UIEdgeInsetsMake(
            -CGFloat(titleSize.height + spacing), CGFloat((tutorialButton.frame.width - imageSize.width) / 2), 0.0, -CGFloat(titleSize.width));

Adding a column to a data.frame

Data.frame[,'h_new_column'] <- as.integer(Data.frame[,'h_no'], breaks=c(1, 4, 7))

How to get the path of src/test/resources directory in JUnit?

Use the following to inject Hibernate with Spring in your unit tests:

@Bean
public LocalSessionFactoryBean getLocalSessionFactoryBean() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    localSessionFactoryBean.setPackagesToScan("com.example.yourpackage.model");
    return localSessionFactoryBean;
}

If you don't have the hibernate.cfg.xml present in your src/test/resources folder it will automatically fall back to the one in your src/main/resources folder.

How to store token in Local or Session Storage in Angular 2?

var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

Remove quotes from String in Python

if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

how to use python2.7 pip instead of default pip

There should be a binary called "pip2.7" installed at some location included within your $PATH variable.

You can find that out by typing

which pip2.7

This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

Now, you should be all set, and

which pip2.7

should return the correct output.

Update data on a page without refreshing

I think you would like to learn ajax first, try this: Ajax Tutorial

If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:

var xhr = new XMLHttpReuqest();
xhr.open("GET", "http://some.com");

xhr.onreadystatechange = handler; // do something here...
xhr.send();

Java - How to create new Entry (key, value)

Try Maps.immutableEntry from Guava

This has the advantage of being compatible with Java 5 (unlike AbstractMap.SimpleEntry which requires Java 6.)

How to create a bash script to check the SSH connection?

Complementing the response of @Adrià Cidre you can do:

status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

if [[ $status == ok ]] ; then
  echo auth ok, do something
elif [[ $status == "Permission denied"* ]] ; then
  echo no_auth
else
  echo other_error
fi

How to find if element with specific id exists or not

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

Return different type of data from a method in java?

I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.

public  enum  SmartReturn {

    IntegerType, DoubleType;

    @SuppressWarnings("unchecked")
    public <T> T comeback(String value) {
        switch (this) {
            case IntegerType:
                return (T) Integer.valueOf(value);
            case DoubleType:
                return (T) Double.valueOf(value);
            default:
                return null;
        }
    }
}

Unit Test:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}

C# : Out of Memory exception

While the GC compacts the small object heap as part of an optimization strategy to eliminate memory holes, the GC never compacts the large object heap for performance reasons**(the cost of compaction is too high for large objects (greater than 85KB in size))**. Hence if you are running a program that uses many large objects in an x86 system, you might encounter OutOfMemory exceptions. If you are running that program in an x64 system, you might have a fragmented heap.

1052: Column 'id' in field list is ambiguous

What you are probably really wanting to do here is use the union operator like this:

(select ID from Logo where AccountID = 1 and Rendered = 'True')
  union
  (select ID from Design where AccountID = 1 and Rendered = 'True')
  order by ID limit 0, 51

Here's the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

How to install numpy on windows using pip install?

Check installation of python 2.7 than install/reinstall pip which described here than open command line and write

pip install numpy

or

pip install scipy

if already installed try this

pip install -U numpy