Programs & Examples On #Ieframe.dll

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

In 2 out of 2 occasions of reports IE8 crashing I got it fixed with removing the background-image from the body element in css. Background-colors are no problem and also putting the same background-image on any other element(for example html) is no problem.

The crash only happened in an actual IE8 in IE8 mode. So you can't test this in IE9 compatibility mode and strangely it can indeed be 'fixed' by forcing IE8 to go into IE7 mode.

Abstract Class vs Interface in C++

Pure Virtual Functions are mostly used to define:

a) abstract classes

These are base classes where you have to derive from them and then implement the pure virtual functions.

b) interfaces

These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

Is it bad practice to use break to exit a loop in Java?

If you start to do something like this, then I would say it starts to get a bit strange and you're better off moving it to a seperate method that returns a result upon the matchedCondition.

boolean matched = false;
for(int i = 0; i < 10; i++) {
    for(int j = 0; j < 10; j++) {
        if(matchedCondition) {
            matched = true;
            break;
        }
    }
    if(matched) {
        break;
    }
}

To elaborate on how to clean up the above code, you can refactor, moving the code to a function that returns instead of using breaks. This is in general, better dealing with complex/messy breaks.

public boolean  matches()
    for(int i = 0; i < 10; i++) {
        for(int j = 0; j < 10; j++) {
            if(matchedCondition) {
                return true;
            }
        }
    }
    return false;
}

However for something simple like my below example. By all means use break!

for(int i = 0; i < 10; i++) {
    if(wereDoneHere()) { // we're done, break.
        break;
    }
}

And changing the conditions, in the above case i, and j's value, you would just make the code really hard to read. Also there could be a case where the upper limits (10 in the example) are variables so then it would be even harder to guess what value to set it to in order to exit the loop. You could of course just set i and j to Integer.MAX_VALUE, but I think you can see this starts to get messy very quickly. :)

asp.net validation to make sure textbox has integer values

Visual Studio has got now integrated support for range checking and type checking :-

Try this :- For RANGE CHECKING Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-

View>Toolbox>Validation

Now Drag on RangeValidator to your design page where you want to show the error message(ofcourse if user is inputting out of range value) now click on your RangeValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write :-

Number must be in range.

Now select on Control to validate and select your TextboxID (or write it anyways) from the drop down.Locate Type in the property bar itself and select down Integer.
Just above it you will find maximum and minimum value .Type in your desired number .

For Type checking (without any Range)
Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-

View>Toolbox>Validation

Now Drag on CompareValidator to your design page where you want to show the error message(ofcourse if user is inputting some text in it). now click on your CompareValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write:-

Value must be a number .

Now locate ControltoValidate option and write your controlID name in it(alternatively you can also select from drop down).Locate the Operator option and write DataTypeCheck(alternatively you can also select from drop down)in it .Again locate the Type option and write Integer in it .

That's sit.

Alternatively you can write the following code in your aspx page :- <%--to validate without any range--%>

Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.

Here's what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here's what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there's another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

How can I write to the console in PHP?

For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

Python integer division yields float

According to Python3 documentation,python when divided by integer,will generate float despite expected to be integer.

For exclusively printing integer,use floor division method. Floor division is rounding off zero and removing decimal point. Represented by //

Hence,instead of 2/2 ,use 2//2

You can also import division from __future__ irrespective of using python2 or python3.

Hope it helps!

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

Function pointer to member function

Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.



template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs&&... rargs) = 0;
    //virtual RET call() = 0;
};

template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
    T * owner;
    RET(T::*x)(RArgs...);
    RET call(RArgs&&... rargs) {
        return (*owner.*(x))(std::forward<RArgs>(rargs)...);
    };
    CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};

template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
    T* owner;
    RET(T::*x)(Args...);
    RET call() {
        return (*owner.*(x))(std::get<Args&&>(args)...);
    };
    std::tuple<Args&&...> args;
    CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
        args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};

Test / example:

class container {
public:
    static void printFrom(container* c) { c->print(); };
    container(int data) : data(data) {};
    ~container() {};
    void print() { printf("%d\n", data); };
    void printTo(FILE* f) { fprintf(f, "%d\n", data); };
    void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
    int data;
};

int main() {
    container c1(1), c2(20);
    CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
    Callback_t<void>* fp1 = &f1;
    fp1->call();//1
    CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
    Callback_t<void>* fp2 = &f2;
    fp2->call();//20
    CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
    Callback_t<void, int>* fp3 = &f3;
    fp3->call(15);//20:15
}

Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.

Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....

Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.

#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif

template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs... rargs) = 0;
    virtual ~Callback_t() = default;
};

template<class RET, class... RArgs> class CallbackFactory {
private:
    template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
    private:
        T * owner;
        RET(T::*x)(CArgs..., RArgs...);
        std::tuple<CArgs...> cargs;
        RET call(RArgs... rargs) {
            return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
        };
    public:
        Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
        ~Callback() {};
    };
public:
    template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
    return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}

in angularjs how to access the element that triggered the event?

 updateTypeahead(this)

will not pass DOM element to the function updateTypeahead(this). Here this will refer to the scope. If you want to access the DOM element use updateTypeahead($event). In the callback function you can get the DOM element by event.target.

Please Note : ng-change function doesn't allow to pass $event as variable.

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

http://play.golang.org/p/CPdfsYGNy_

m1 := map[string]int{   
    "a":1,
    "b":2,
}
m2 := map[string]int{   
    "a":1,
    "b":2,
}
fmt.Println(reflect.DeepEqual(m1, m2))

Use dynamic variable names in `dplyr`

With rlang 0.4.0 we have curly-curly operators ({{}}) which makes this very easy.

library(dplyr)
library(rlang)

iris1 <- tbl_df(iris)

multipetal <- function(df, n) {
   varname <- paste("petal", n , sep=".")
   mutate(df, {{varname}} := Petal.Width * n)
}

multipetal(iris1, 4)

# A tibble: 150 x 6
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.4
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>     <dbl>
# 1          5.1         3.5          1.4         0.2 setosa      0.8
# 2          4.9         3            1.4         0.2 setosa      0.8
# 3          4.7         3.2          1.3         0.2 setosa      0.8
# 4          4.6         3.1          1.5         0.2 setosa      0.8
# 5          5           3.6          1.4         0.2 setosa      0.8
# 6          5.4         3.9          1.7         0.4 setosa      1.6
# 7          4.6         3.4          1.4         0.3 setosa      1.2
# 8          5           3.4          1.5         0.2 setosa      0.8
# 9          4.4         2.9          1.4         0.2 setosa      0.8
#10          4.9         3.1          1.5         0.1 setosa      0.4
# … with 140 more rows

We can also pass quoted/unquoted variable names to be assigned as column names.

multipetal <- function(df, name, n) {
   mutate(df, {{name}} := Petal.Width * n)
}

multipetal(iris1, temp, 3)

# A tibble: 150 x 6
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species  temp
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl>
# 1          5.1         3.5          1.4         0.2 setosa  0.6  
# 2          4.9         3            1.4         0.2 setosa  0.6  
# 3          4.7         3.2          1.3         0.2 setosa  0.6  
# 4          4.6         3.1          1.5         0.2 setosa  0.6  
# 5          5           3.6          1.4         0.2 setosa  0.6  
# 6          5.4         3.9          1.7         0.4 setosa  1.2  
# 7          4.6         3.4          1.4         0.3 setosa  0.900
# 8          5           3.4          1.5         0.2 setosa  0.6  
# 9          4.4         2.9          1.4         0.2 setosa  0.6  
#10          4.9         3.1          1.5         0.1 setosa  0.3  
# … with 140 more rows

It works the same with

multipetal(iris1, "temp", 3)

CSS to make table 100% of max-width

I have a very well working solution for tables of max-width: 100%. Just use word-break: break-all; for the table cells (except heading cells) to break all long text into several lines:

<!DOCTYPE html>
<html>
<head>
<style>

table {
  max-width: 100%; 
}
table td {
  word-break: break-all;
}

</style>
</head>
<body>

<table border="1">
  <tr>
    <th><strong>Input</strong></th>
    <th><strong>Output</strong></th>
  </tr>
  <tr>
    <td>some text</td>
    <td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
  </tr>
</table>

</body>
</html>

This will render like this (when the screen width is limited):

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

Update Git branches from master

to update your branch from the master:

  git checkout master
  git pull
  git checkout your_branch
  git merge master

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Oracle - What TNS Names file am I using?

The easiest way is probably to check the PATH environment variable of the process that is connecting to the database. Most likely the tnsnames.ora file is in first Oracle bin directory in path..\network\admin. TNS_ADMIN environment variable or value in registry (for the current Oracle home) may override this.

Using filemon like suggested by others will also do the trick.

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Return Result from Select Query in stored procedure to a List

SqlConnection con = new SqlConnection("Data Source=DShp;Initial Catalog=abc;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("data", con);

da.SelectCommand.CommandType= CommandType.StoredProcedure;

DataSet ds=new DataSet();

da.Fill(ds, "data");
GridView1.DataSource = ds.Tables["data"];
GridView1.DataBind();

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

How to SHA1 hash a string in Android?

If you can get away with using Guava it is by far the simplest way to do it, and you don't have to reinvent the wheel:

final HashCode hashCode = Hashing.sha1().hashString(yourValue, Charset.defaultCharset());

You can then take the hashed value and get it as a byte[], as an int, or as a long.

No wrapping in a try catch, no shenanigans. And if you decide you want to use something other than SHA-1, Guava also supports sha256, sha 512, and a few I had never even heard about like adler32 and murmur3.

Inline for loop

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

How to get and set the current web page scroll position?

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

C# Equivalent of SQL Server DataTypes

SQL Server and .Net Data Type mapping

SQL Server and .Net Data Type mapping

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

Will #if RELEASE work like #if DEBUG does in C#?

Nope.

While in debug configuration there is a DEBUG defined constant (automatically defined by Visual Studio) while there is no such constant defined for release mode. Check your project settings under build.

Selecting [Define DEBUG constant] under Project -> Build is like including #define DEBUG at the beginning of every file.

If you want to define a RELEASE constant for the release configuration go to:

  • Project Properties -> Build
  • Select Release Mode
  • in the Conditional compilation symbols textbox enter: RELEASE

How can I get the selected VALUE out of a QCombobox?

The question is old, but maybe, somebody need an actual answer.

In the QGIS 3.4 you can get the value from the QComboBox with the method currentData().

Example: comboBox.currentData()

Link: https://doc.qt.io/qt-5/qcombobox.html#currentData-prop

How do I serialize a Python dictionary into a string, and then back to a dictionary?

It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle (or, if you’re using CPython 2.x, cPickle, which is faster).

>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
>>> pickle.loads(_)
{'foo': 'bar'}

If you want it to be readable, you could use json:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}

json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

>>> pickle.dumps(object())
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
>>> json.dumps(object())
Traceback (most recent call last):
  ...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

How to compare LocalDate instances Java 8

LocalDate ld ....;
LocalDateTime ldtime ...;

ld.isEqual(LocalDate.from(ldtime));

Android Studio - Failed to notify project evaluation listener error

In my case, I had to do -

File -> Sync Project with Gradle Files

Sync Project with Gradle Files

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

You need to put SongsTableSeeder into file SongsTableSeeder.php in the same directory where you have your DatabaseSeeder.php file.

And you need to run in your console:

composer dump-autoload

to generate new class map and then run:

php artisan db:seed

I've just tested it. It is working without a problem in Laravel 5

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How do I use method overloading in Python?

Python does not support method overloading like Java or C++. We may overload the methods, but we can only use the latest defined method.

# First sum method.
# Takes two argument and print their sum
def sum(a, b):
    s = a + b
    print(s)

# Second sum method
# Takes three argument and print their sum
def sum(a, b, c):
    s = a + b + c
    print(s)

# Uncommenting the below line shows an error
# sum(4, 5)

# This line will call the second sum method
sum(4, 5, 5)

We need to provide optional arguments or *args in order to provide a different number of arguments on calling.

Courtesy Python | Method Overloading

Iterate over model instance field names and values in template

I'm using this, https://github.com/miracle2k/django-tables.

<table>
<tr>
    {% for column in table.columns %}
    <th><a href="?sort={{ column.name_toggled }}">{{ column }}</a></th>
    {% endfor %}
</tr>
{% for row in table.rows %}
    <tr>
    {% for value in row %}
        <td>{{ value }}</td>
    {% endfor %}
    </tr>
{% endfor %}
</table>

Context.startForegroundService() did not then call Service.startForeground()

I just sharing my review about this. I am not surely(100% telling) that above code is not working for me and other guys also but some times I got this issue. Suppose I run the app 10 time then might be got this issue 2 to 3 three time.

I have tried above all the answers but still not solve the issue. I have implemented above all the codes and tested in different api levels (API level 26, 28, 29) and difference mobile (Samsung, Xiaomi, MIUI, Vivo, Moto, One Plus, Huawei, etc ) and getting same below issue.

Context.startForegroundService() did not then call Service.startForeground();

I have read service on google developer web site, some other blog and some stack overflow question and got the idea that this issue will happen when we call startForgroundSerivce() method but at that time service was not started.

In my case I have stop the service and after immediately start service. Below is the hint.

....//some other code
...// API level and other device auto star service condition is already set
stopService();
startService();
.....//some other code

In this case service is not started due to processing speed and low memory in RAM but startForegroundService() method is called and fire the exception.

Work for me:

new Handler().postDelayed(()->ContextCompat.startForegroundService(activity, new Intent(activity, ChatService.class)), 500);

I have change code and set 500 milliseconds delay to call startService() method and issue is solved. This is not perfect solution because this way app's performance goes downgrade.

Note: This is only for Foreground and Background service only. Don't tested when using Bind service. I am sharing this because only this is the way I have solved this issue.

Given a DateTime object, how do I get an ISO 8601 date in string format?

The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".

When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

– from MSDN

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I know this is a somewhat old thread, but I had this problem too with a c#/WPF app I was creating. The app worked fine on the development machine, but would not start on the test machine. The Application Log in the Event Viewer gave a somewhat nebulous .NET Runtime error of System.IO.DirectoryNotFoundException.

I tried using some debugging software but the app would not stay running long enough to attach the debugger to the process. After banging my head against my desk for a day and looking at many web pages like this one, what I wound up doing to troubleshoot this was to install VS2019 on my test machine. I then dragged the .exe file from its folder (it was deep in the Users[user]\AppData\Apps\2.0... folder) to the open VS2019 instance and went to start it from there. Immediately, it came up with a dialog box giving the exception and the cause.

In my case, when I added an icon to one of the forms, the complete path to the icon was placed into the XAML instead of just the icon name. I had copied the icon file into the project folder, but since the project folder does not exist on the test machine, this was the root cause of the error. I then removed the path from the XAML, leaving just the icon name one, rebuilt the solution and re-published it, and it ran just fine on the test machine now. Of course there are many causes besides what gave me the error, but this method of troubleshooting should hopefully identify the root cause of the error, since the Windows Event Viewer gives a somewhat vague answer.

To summarize, use Visual Studio on the test machine as a debugger of sorts. But, to get it to work right, I had to drag the .exe file into the IDE and Start (run) it from there. I believe this will also work with VS2017 as well as VS2019. Hopefully this helps someone who is still having this issue.

NULL value for int in Update statement

By using NULL without any quotes.

UPDATE `tablename` SET `fieldName` = NULL;

SQL to Query text in access with an apostrophe in it

How about more simply: Select * from tblStudents where [name] = replace(YourName,"'","''")

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.

Maximum length for MD5 input/output

You can have any length, but of course, there can be a memory issue on the computer if the String input is too long. The output is always 32 characters.

Spring Boot access static resources missing scr/main/resources

To get the files in the classpath :

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();

To read the file onStartup use @PostConstruct:

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}

Here is a Small example for reading an XML File on Spring Boot App startup.

What are the differences between Abstract Factory and Factory design patterns?

Consider this example for easy understanding.

What does telecommunication companies provide? Broadband, phone line and mobile for instance and you're asked to create an application to offer their products to their customers.

Generally what you'd do here is, creating the products i.e broadband, phone line and mobile are through your Factory Method where you know what properties you have for those products and it's pretty straightforward.

Now, the company wants to offer their customer a bundle of their products i.e broadband, phone line, and mobile altogether, and here comes the Abstract Factory to play.

Abstract Factory is, in other words, are the composition of other factories who are responsible for creating their own products and Abstract Factory knows how to place these products in more meaningful in respect of its own responsibilities.

In this case, the BundleFactory is the Abstract Factory, BroadbandFactory, PhonelineFactory and MobileFactory are the Factory. To simplify more, these Factories will have Factory Method to initialise the individual products.

Se the code sample below:

public class BroadbandFactory : IFactory {
    public static Broadband CreateStandardInstance() {
        // broadband product creation logic goes here
    }
}

public class PhonelineFactory : IFactory {
    public static Phoneline CreateStandardInstance() {
        // phoneline product creation logic goes here
    }
}

public class MobileFactory : IFactory {
    public static Mobile CreateStandardInstance() {
        // mobile product creation logic goes here
    }
}

public class BundleFactory : IAbstractFactory {

    public static Bundle CreateBundle() {
        broadband = BroadbandFactory.CreateStandardInstance();
        phoneline = PhonelineFactory.CreateStandardInstance();
        mobile = MobileFactory.CreateStandardInstance();

        applySomeDiscountOrWhatever(broadband, phoneline, mobile);
    }

    private static void applySomeDiscountOrWhatever(Broadband bb, Phoneline pl, Mobile m) {
        // some logic here
        // maybe manange some variables and invoke some other methods/services/etc.
    }
}

Hope this helps.

How to get first 5 characters from string

An alternative way to get only one character.

$str = 'abcdefghij';
echo $str{5};

I would particularly not use this, but for the purpose of education. We can use that to answer the question:

$newString = '';
for ($i = 0; $i < 5; $i++) {
    $newString .= $str{$i};
}
echo $newString;

For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4

More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access

Flutter Countdown Timer

You can use this plugin timer_builder

timer_builder widget that rebuilds itself on scheduled, periodic, or dynamically generated time events.

Examples

Periodic rebuild

import 'package:timer_builder/timer_builder.dart';

class ClockWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return TimerBuilder.periodic(Duration(seconds: 1),
      builder: (context) {
        return Text("${DateTime.now()}");
      }
    );
  }
  
}

Rebuild on a schedule

import 'package:timer_builder/timer_builder.dart';

class StatusIndicator extends StatelessWidget {

  final DateTime startTime;
  final DateTime endTime;
  
  StatusIndicator(this.startTime, this.endTime);
  
  @override
  Widget build(BuildContext context) {
    return TimerBuilder.scheduled([startTime, endTime],
      builder: (context) {
        final now = DateTime.now();
        final started = now.compareTo(startTime) >= 0;
        final ended = now.compareTo(endTime) >= 0;
        return Text(started ? ended ? "Ended": "Started": "Not Started");
      }
    );
  }
  
}

enter image description here

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

jQuery .ready in a dynamically inserted iframe

Try this,

<iframe id="testframe" src="about:blank" onload="if (testframe.location.href != 'about:blank') testframe_loaded()"></iframe>

All you need to do then is create the JavaScript function testframe_loaded().

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Many browsers have changed their security policies to no longer allow reading data directly from file shares or even local resources. You need to either place the files somewhere that your tomcat instance can serve them up and put a "regular" http url in the html you generate. This can be accomplished by either providing a servlet which reads and provides the file putting the file into a directory where tomcat will serve it up as "static" content.

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

CSS: Creating textured backgrounds

Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.

In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.

How can I extract all values from a dictionary in Python?

If you want all of the values, use this:

dict_name_goes_here.values()

reading external sql script in python

A very simple way to read an external script into an sqlite database in python is using executescript():

import sqlite3

conn = sqlite3.connect('csc455_HW3.db')

with open('ZooDatabase.sql', 'r') as sql_file:
    conn.executescript(sql_file.read())

conn.close()

How to pass object with NSNotificationCenter

Swift 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

Bonus (that you should definitely do!) :

Replace Notification.Name("SomeNotificationName") with .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

Replace "key0" and "key1" with Notification.Key.key0 and Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...

How can I fill a column with random numbers in SQL? I get the same value in every row

If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  

Force “landscape” orientation mode

I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.

I fixed just calling the manifest.json correctly on html headers.

My html headers:

<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">

And the manifest.json file content:

{
  "display": "standalone",
  "orientation": "portrait",
  "start_url": "/",
  "theme_color": "#000000",
  "background_color": "#ffffff",
  "icons": [
  {
    "src": "android-chrome-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }
}

To generate your favicons and icons use this webtool: https://realfavicongenerator.net/

To generate your manifest file use: https://tomitm.github.io/appmanifest/

My PWA Works great, hope it helps!

How can I export Excel files using JavaScript?

I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info

Search for value in DataGridView in a column

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

Getting an element from a Set

Quick helper method that might address this situation:

<T> T onlyItem(Collection<T> items) {
    if (items.size() != 1)
        throw new IllegalArgumentException("Collection must have single item; instead it has " + items.size());

    return items.iterator().next();
}

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

Checking if an object is a number in C#

There are some great answers above. Here is an all-in-one solution. Three overloads for different circumstances.

// Extension method, call for any object, eg "if (x.IsNumeric())..."
public static bool IsNumeric(this object x) { return (x==null ? false : IsNumeric(x.GetType())); }

// Method where you know the type of the object
public static bool IsNumeric(Type type) { return IsNumeric(type, Type.GetTypeCode(type)); }

// Method where you know the type and the type code of the object
public static bool IsNumeric(Type type, TypeCode typeCode) { return (typeCode == TypeCode.Decimal || (type.IsPrimitive && typeCode != TypeCode.Object && typeCode != TypeCode.Boolean && typeCode != TypeCode.Char)); }

Base64 encoding and decoding in client-side Javascript

Modern browsers have built-in javascript functions for Base64 encoding btoa() and decoding atob(). More info about support in older browser versions: https://caniuse.com/?search=atob

However, be aware that atob and btoa functions work only for ASCII charset. If you need Base64 functions for UTF-8 charset, you can do it with:

function base64_encode(s) {      
    return btoa(unescape(encodeURIComponent(s)));
}
function base64_decode(s) {      
    return decodeURIComponent(escape(atob(s)));
}

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

Comparing HTTP and FTP for transferring files

One consideration is that FTP can use non-standard ports, which can make getting though firewalls difficult (especially if you're using SSL). HTTP is typically on a known port, so this is rarely a problem.

If you do decide to use FTP, make sure you read about Active and Passive FTP.

In terms of performance, at the end of the day they're both spewing files directly down TCP connections so should be about the same.

dpi value of default "large", "medium" and "small" text views android

Programmatically, you could use:

textView.setTextAppearance(android.R.style.TextAppearance_Large);

How to configure port for a Spring Boot application

There are two main ways to change the port in the Embedded Tomcat in a Spring Boot Application.

Modify application.properties

First you can try the application.properties file in the /resources folder:

server.port = 8090

application.properties file

Modify a VM option

The second way, if you want to avoid modifying any files and checking in something that you only need on your local, you can use a vm arg:

Go to Run -> Edit Configurations -> VM options

-Dserver.port=8090

Change port with a vm arg

Additionally, if you need more information you can view the following blog post here: Changing the port on a Spring Boot Application

How to create a new figure in MATLAB?

figure;
plot(something);

or

figure(2);
plot(something);
...
figure(3);
plot(something else);
...

etc.

Stop embedded youtube iframe?

Talvi's answer may still work, but that Youtube Javascript API has been marked as deprecated. You should now be using the newer Youtube IFrame API.

The documentation provides a few ways to accomplish video embedding, but for your goal, you'd include the following:

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

This should be very simple if Google Calendar does not require the *.ics-extension (which will require some URL rewriting in the server).

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";

//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;

That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You bind in onResume but unbind in onDestroy. You should do the unbinding in onPause instead, so that there are always matching pairs of bind/unbind calls. Your intermittent errors will be where your activity is paused but not destroyed, and then resumed again.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Setting the filter to an OpenFileDialog to allow the typical image formats?

This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:

---------------------------------
| EXTENSION  |  DOCTYPE         |
---------------------------------
|   .doc     |  Document        |
|   .docx    |  Document        |
|   .pdf     |  Document        |
|   ...      |  ...             |
|   .bmp     |  Image           |
|   .jpg     |  Image           |
|   ...      |  ...             |
---------------------------------

Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:

    private static string GetUploadFilter()
    {
        // Desired format:
        // "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
        // "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"

        string filter = String.Empty;
        string nameFilter = String.Empty;
        string extFilter = String.Empty;

        // Used to get extensions
        DataTable dt = new DataTable();
        dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");

        // Used to cycle through doctype groupings ("Images", "Documents", etc.)
        DataTable dtDocTypes = new DataTable();
        dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");

        // For each doctype grouping...
        foreach (DataRow drDocType in dtDocTypes.Rows)
        {
            nameFilter = drDocType["DOCTYPE"].ToString() + " files (";

            // ... add its associated extensions
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
                {
                    nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
                    extFilter += "*" + dr["EXTENSION"].ToString() + ";";
                }                    
            }

            // Remove endings put in place in case there was another to add, and end them with pipe characters:
            nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
            nameFilter += ")|";
            extFilter = extFilter.TrimEnd(';');
            extFilter += "|";

            // Add the name and its extensions to our main filter
            filter += nameFilter + extFilter;

            extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
        }

        filter = filter.TrimEnd('|');
        return filter;
    }

    private void UploadFile(string fileType, object sender)
    {            
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        string filter = GetUploadFilter();
        dlg.Filter = filter;

        if (dlg.ShowDialog().Value == true)
        {
            string fileName = dlg.FileName;

            System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
            byte[] array = new byte[fs.Length];

            // This will give you just the filename
            fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
            ...

Should yield a filter that looks like this:

enter image description here

How to deselect a selected UITableView cell?

NSIndexPath * index = [self.menuTableView indexPathForSelectedRow];
[self.menuTableView deselectRowAtIndexPath:index animated:NO];

place this code according to your code and you will get your cell deselected.

How to rename a file using svn?

This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case). In which case you need to rename to a third, dummy, name:

svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit

Handling click events on a drawable within an EditText

Simply copy paste the following code and it does the trick.

editMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() >= (editMsg.getRight() - editMsg.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here

                    Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        }
    });

JavaScript unit test tools for TDD

We added JUnit integration to our Java to Javascript code generator ST-JS (http://st-js.org). The framework generates to corresponding Javascript for both the tested code and the unit tests and sends the code to different browsers.

There is no need for a separate server as the unit test runner opens the needed http port (and closes it once the tests finished). The framework manipulates the Java stacktrace so that the failed asserts are correctly displayed by the JUnit Eclipse plugin. Here is a simple example with jQuery and Mockjax:

@RunWith(STJSTestDriverRunner.class)
@HTMLFixture("<div id='fortune'></div>")

@Scripts({ "classpath://jquery.js",
       "classpath://jquery.mockjax.js", "classpath://json2.js" })
public class MockjaxExampleTest {
  @Test
  public void myTest() {
    $.ajaxSetup($map("async", false));
    $.mockjax(new MockjaxOptions() {
      {
        url = "/restful/fortune";
        responseText = new Fortune() {
          {
            status = "success";
            fortune = "Are you a turtle?";
          }
        };
      }
    });

    $.getJSON("/restful/fortune", null, new Callback3<Fortune, String, JQueryXHR>() {
      @Override
      public void $invoke(Fortune response, String p2, JQueryXHR p3) {
        if (response.status.equals("success")) {
          $("#fortune").html("Your fortune is: " + response.fortune);
        } else {
          $("#fortune").html("Things do not look good, no fortune was told");
        }

      }
    });
    assertEquals("Your fortune is: Are you a turtle?", $("#fortune").html());
  }

  private static class Fortune {
    public String status;
    public String fortune;
  }
}

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

What is the difference between an expression and a statement in Python?

Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:

# all the above expressions
print 42
if x: do_y()
return
a = 7

How do I automatically set the $DISPLAY variable for my current session?

do you use Bash? Go to the file .bashrc in your home directory and set the variable, then export it.

DISPLAY=localhost:0.0 ; export DISPLAY

you can use /etc/bashrc if you want to do it for all the users.

You may also want to look in ~/.bash_profile and /etc/profile

EDIT:

function get_xserver ()
{
    case $TERM in
       xterm )
            XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )    
            XSERVER=${XSERVER%%:*}
            ;;
        aterm | rxvt)           
            ;;
    esac  
}

if [ -z ${DISPLAY:=""} ]; then
    get_xserver
    if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || \
      ${XSERVER} == "unix" ]]; then 
        DISPLAY=":0.0"          # Display on local host.
    else
        DISPLAY=${XSERVER}:0.0  # Display on remote host.
    fi
fi

export DISPLAY

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

iPhone/iOS JSON parsing tutorial

try out with this fastest JSON framework JSONKit. it's faster than normal JSON framework.

Save Javascript objects in sessionStorage

Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.

How to create a zip archive with PowerShell?

Here is a slightly improved version of sonjz's answer,it adds an overwrite option.

function Zip-Files(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$false)]
        [string] $zipfilename,
        [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false)]
        [string] $sourcedir,
        [Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)]
        [bool] $overwrite)

{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal

    if ($overwrite -eq $true )
    {
        if (Test-Path $zipfilename)
        {
            Remove-Item $zipfilename
        }
    }

    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}

Clicking the back button twice to exit an activity

@Override public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_MAIN);
   intent.addCategory(Intent.CATEGORY_HOME);

   startActivity(intent);
}

Print the contents of a DIV

I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.

https://github.com/jasonday/printThis

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

Editing specific line in text file in Python

you can use fileinput to do in place editing

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line

What is the difference between call and apply?

A well explained by flatline. I just want to add a simple example. which makes it easy to understand for beginners.

func.call(context, args1 , args2 ); // pass arguments as "," saprated value

func.apply(context, [args1 , args2 ]);   //  pass arguments as "Array"

we also use "Call" and "Apply" method for changing reference as defined in code below

_x000D_
_x000D_
    let Emp1 = {_x000D_
        name: 'X',_x000D_
        getEmpDetail: function (age, department) {_x000D_
            console.log('Name :', this.name, '  Age :', age, '  Department :', department)_x000D_
        }_x000D_
    }_x000D_
    Emp1.getEmpDetail(23, 'Delivery')_x000D_
_x000D_
    // 1st approch of chenging "this"_x000D_
    let Emp2 = {_x000D_
        name: 'Y',_x000D_
        getEmpDetail: Emp1.getEmpDetail_x000D_
    }_x000D_
    Emp2.getEmpDetail(55, 'Finance')_x000D_
_x000D_
    // 2nd approch of changing "this" using "Call" and "Apply"_x000D_
    let Emp3 = {_x000D_
        name: 'Z',_x000D_
    }_x000D_
_x000D_
    Emp1.getEmpDetail.call(Emp3, 30, 'Admin')        _x000D_
// here we have change the ref from **Emp1 to Emp3**  object_x000D_
// now this will print "Name =  X" because it is pointing to Emp3 object_x000D_
    Emp1.getEmpDetail.apply(Emp3, [30, 'Admin']) //
_x000D_
_x000D_
_x000D_

How to copy files between two nodes using ansible

You can use deletgate with scp too:

- name: Copy file to another server
  become: true
  shell: "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null admin@{{ inventory_hostname }}:/tmp/file.yml /tmp/file.yml"
  delegate_to: other.example.com

Because of delegate the command is run on the other server and it scp's the file to itself.

Difference between links and depends_on in docker_compose.yml

This answer is for docker-compose version 2 and it also works on version 3

You can still access the data when you use depends_on.

If you look at docker docs Docker Compose and Django, you still can access the database like this:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

What is the difference between links and depends_on?

links:

When you create a container for a database, for example:

docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql

docker inspect d54cf8a0fb98 |grep HostPort

And you may find

"HostPort": "32777"

This means you can connect the database from your localhost port 32777 (3306 in container) but this port will change every time you restart or remove the container. So you can use links to make sure you will always connect to the database and don't have to know which port it is.

web:
  links:
   - db

depends_on:

I found a nice blog from Giorgio Ferraris Docker-compose.yml: from V1 to V2

When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.

And

So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose

Update

depends_on

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Simple example:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

The selected answer posted here solved one problem, but another is that you'll have to change the app pool to use .Net 2.0.

"SharePoint 2010 uses .NET Framework 3.5, not 4.0. The SharePoint 2010 app pools should be configured as .NET Framework 2.0 using the Integrated Pipeline Mode."

source: http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/4727f9b4-cc58-4d86-903b-fabed13da0ff

What’s the best way to load a JSONObject from a json text file?

On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );

This is not demanding a given Object structure for receiving/reading the json string.

How to make a vertical line in HTML

You can use hr (horizontal line) tag and than rotate it 90 degree with css below

hr {   
    transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -webkit-transform:rotate(90deg);
}

http://jsfiddle.net/haykaghabekyan/0c969bm6/1/

day of the week to day number (Monday = 1, Tuesday = 2)

What about using idate()? idate()

$integer = idate('w', $timestamp);

Xcode doesn't see my iOS device but iTunes does

Had same problem with some non-licensed cables. Works fine with Apple's & Belkin's USB cables.

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

How to check if the key pressed was an arrow key in Java KeyListener?

Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }

How to convert an int to a hex string?

Let me add this one, because sometimes you just want the single digit representation

( x can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):

'{:x}'.format(15)
> f

And now with the new f'' format strings you can do:

f'{15:x}'
> f

To add 0 padding you can use 0>n:

f'{2034:0>4X}'
> 07F2

NOTE: the initial 'f' in f'{15:x}' is to signify a format string

How to trigger an event after using event.preventDefault()

Nope. Once the event has been canceled, it is canceled.

You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):

var lots_of_stuff_already_done = false;

$('.button').on('click', function(e) {
    if (lots_of_stuff_already_done) {
        lots_of_stuff_already_done = false; // reset flag
        return; // let the event bubble away
    }

    e.preventDefault();

    // do lots of stuff

    lots_of_stuff_already_done = true; // set flag
    $(this).trigger('click');
});

A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:

function onWithPrecondition(callback) {
    var isDone = false;

    return function(e) {
        if (isDone === true)
        {
            isDone = false;
            return;
        }

        e.preventDefault();

        callback.apply(this, arguments);

        isDone = true;
        $(this).trigger(e.type);
    }
}

Usage:

var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));

Bonus super-minimalistic jQuery plugin with Promise support:

(function( $ ) {
    $.fn.onButFirst = function(eventName,         /* the name of the event to bind to, e.g. 'click' */
                               workToBeDoneFirst, /* callback that must complete before the event is re-fired */
                               workDoneCallback   /* optional callback to execute before the event is left to bubble away */) {
        var isDone = false;

        this.on(eventName, function(e) {
            if (isDone === true) {
                isDone = false;
                workDoneCallback && workDoneCallback.apply(this, arguments);
                return;
            }

            e.preventDefault();

            // capture target to re-fire event at
            var $target = $(this);

            // set up callback for when workToBeDoneFirst has completed
            var successfullyCompleted = function() {
                isDone = true;
                $target.trigger(e.type);
            };

            // execute workToBeDoneFirst callback
            var workResult = workToBeDoneFirst.apply(this, arguments);

            // check if workToBeDoneFirst returned a promise
            if (workResult && $.isFunction(workResult.then))
            {
                workResult.then(successfullyCompleted);
            }
            else
            {
                successfullyCompleted();
            }
        });

        return this;
    };
}(jQuery));

Usage:

$('.button').onButFirst('click',
    function(){
        console.log('doing lots of work!');
    },
    function(){
        console.log('done lots of work!');
    });

How do I disable directory browsing?

Add this in your .htaccess file:

Options -Indexes

If it is not work for any reason, try this within your .htaccess file:

IndexIgnore *

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

How to send an email from JavaScript

It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.

Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.

Makefile to compile multiple C programs?

Pattern rules let you compile multiple c files which require the same compilation commands using make as follows:

objects = program1 program2
all: $(objects)

$(objects): %: %.c
        $(CC) $(CFLAGS) -o $@ $<

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

How to retrieve field names from temporary table (SQL Server 2008)

Anthony

try the below one. it will give ur expected output

select c.name as Fields from 
tempdb.sys.columns c
    inner join tempdb.sys.tables t
 ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

Fastest way to Remove Duplicate Value from a list<> by lambda

The easiest way to get a new list would be:

List<long> unique = longs.Distinct().ToList();

Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.

Note that Distinct() isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct() for more information.

If you don't need it to be a List<long>, you could just keep it as:

IEnumerable<long> unique = longs.Distinct();

At this point it will go through the de-duping each time you iterate over unique though. Whether that's good or not will depend on your requirements.

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

Encode String to UTF-8

A Java String is internally always encoded in UTF-16 - but you really should think about it like this: an encoding is a way to translate between Strings and bytes.

So if you have an encoding problem, by the time you have String, it's too late to fix. You need to fix the place where you create that String from a file, DB or network connection.

CSS table-cell equal width

HTML

<div class="table">
    <div class="table_cell">Cell-1</div>
    <div class="table_cell">Cell-2 Cell-2 Cell-2 Cell-2Cell-2 Cell-2</div>
    <div class="table_cell">Cell-3Cell-3 Cell-3Cell-3 Cell-3Cell-3</div>
    <div class="table_cell">Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4Cell-4</div>
</div>?

CSS

.table{
    display:table;
    width:100%;
    table-layout:fixed;
}
.table_cell{
    display:table-cell;
    width:100px;
    border:solid black 1px;
}

DEMO.

One line if in VB .NET

if Condition then command1 : else command2...

Image inside div has extra space below the image

All you have to do is assign this property:

img {
    display: block;
}

The images by default have this property:

img {
    display: inline;
}

How to set column header text for specific column in Datagridview C#

there is HeaderText property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

    public Form1()
    {
        InitializeComponent();

        grid.Columns[0].HeaderText = "First Column"; 
        //..............
    }

More details are here at MSDN. More details about DataGrid are here.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

git: patch does not apply

WARNING: This command can remove old lost commits PERMANENTLY. Make a copy of your entire repository before attempting this.

I have found this link

I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:

git fsck --full
git reflog expire --expire=now --all
git gc --prune=now

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

Disabling radio buttons with jQuery

Remove your "each" and just use:

$('input[name=ticketID]').attr("disabled",true);

That simple. It works

Get the device width in javascript

You should use

document.documentElement.clientWidth

It is regarded as cross-browser compability, and is the same method that jQuery(window).width(); uses.

For detailed information have a look at: https://ryanve.com/lab/dimensions/

identifier "string" undefined?

Because string is defined in the namespace std. Replace string with std::string, or add

using std::string;

below your include lines.

It probably works in main.cpp because some other header has this using line in it (or something similar).

How to convert an array into an object using stdClass()

If you want to recursively convert the entire array into an Object type (stdClass) then , below is the best method and it's not time-consuming or memory deficient especially when you want to do a recursive (multi-level) conversion compared to writing your own function.

$array_object = json_decode(json_encode($array));

rejected master -> master (non-fast-forward)

NOTICE: This is never a recommended use of git. This will overwrite changes on the remote. Only do this if you know 100% that your local changes should be pushed to the remote master.

Try this: git push -f origin master

Can I prevent text in a div block from overflowing?

.NonOverflow {
    width: 200px; /* Need the width for this to work */
    overflow: hidden;
}
<div class="NonOverflow">
    Long Text
</div>

C++ where to initialize static const

Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:

#include <string>

class foo {
public:
   foo();
   foo( int );
private:
   inline static const std::string s { "foo" };
};

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

How do I run a terminal inside of Vim?

Eventually a native :terminal command was added to vim in 2017.

Here is an excerpt from the :terminal readme:

This feature is for running a terminal emulator in a Vim window. A job can be started connected to the terminal emulator. For example, to run a shell:

 :term bash

Or to run build command:

 :term make myprogram

The job runs asynchronously from Vim, the window will be updated to show output from the job, also while editing in another window.

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

Eclipse cannot load SWT libraries

In my case, I was missing the /usr/lib/jni directory entirely. Fixed by

sudo apt-get install libswt-gtk-3-jni libswt-gtk-3-java

No need to symlink afterwards. Eclipse started normally.

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

  • Most probably this happen because of some silly mistake in layout file
  • in my case case I have copied a textview from another project but the backgroundColor resource was not available in my current project
  • The thing that it was not showing the error at run time but gives above error while compile time.
  • You can find out where the exact error in your xml by following the process:

Click on the Gradle tab in right side of Android Studio -> Open the projects build directory as shown in below image -> Run the assembleDebug

-- The error will be shown like in below image

enter image description here

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

How to find a hash key containing a matching value

You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.

"The system cannot find the file specified"

I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.

Convert JSON format to CSV format for MS Excel

You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361

The import com.google.android.gms cannot be resolved

I had the same problem so that the dumb API I decided as follows changing the import line

import com.google.android.gms.maps.model.LatLng;

Python Binomial Coefficient

Note that starting Python 3.8, the standard library provides the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

import math
math.comb(10, 5)  # 252
math.comb(10, 10) # 1

How to choose multiple files using File Upload Control?

        aspx code

            <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
            <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
            <hr />
            <asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />


    Code Behind:

protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.

OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by @gnovice.

EDIT

One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.

Find all packages installed with easy_install/pip?

Start with:

$ pip list

To list all packages. Once you found the package you want, use:

$ pip show <package-name>

This will show you details about this package, including its folder. You can skip the first part if you already know the package name

Click here for more information on pip show and here for more information on pip list.

Example:

$ pip show jupyter
Name: jupyter
Version: 1.0.0
Summary: Jupyter metapackage. Install all the Jupyter components in one go.
Home-page: http://jupyter.org
Author: Jupyter Development Team
Author-email: [email protected]
License: BSD
Location: /usr/local/lib/python2.7/site-packages
Requires: ipywidgets, nbconvert, notebook, jupyter-console, qtconsole, ipykernel    

How to restart a node.js server

To say "nodemon" would answer the question.

But on how only to kill (all) node demon(s), the following works for me:

pkill -HUP node

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

After countless hours of frustration I managed to get all working:

odbcinst.ini:

[FreeTDS]
Description = FreeTDS Driver v0.91
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1

odbc.ini:

[test]
Driver = FreeTDS
Description = My Test Server
Trace = No
#TraceFile = /tmp/sql.log
ServerName = mssql
#Port = 1433
instance = SQLEXPRESS
Database = usedbname
TDS_Version = 4.2

FreeTDS.conf:

[mssql]
host = hostnameOrIP
instance = SQLEXPRESS
#Port = 1433
tds version = 4.2

First test connection (mssql is a section name from freetds.conf):

tsql -S mssql -U username -P password

You must see some settings but no errors and only a 1> prompt. Use quit to exit.

Then let's test DSN/FreeTDS (test is a section name from odbc.ini; -v means verbose):

isql -v test username password -v

You must see message Connected!

What is the difference between a token and a lexeme?

a) Tokens are symbolic names for the entities that make up the text of the program; e.g. if for the keyword if, and id for any identifier. These make up the output of the lexical analyser. 5

(b) A pattern is a rule that specifies when a sequence of characters from the input constitutes a token; e.g the sequence i, f for the token if , and any sequence of alphanumerics starting with a letter for the token id.

(c) A lexeme is a sequence of characters from the input that match a pattern (and hence constitute an instance of a token); for example if matches the pattern for if , and foo123bar matches the pattern for id.

Should I use Vagrant or Docker for creating an isolated environment?

If your purpose is the isolation, I think Docker is what you want.

Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.

Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system. You can use Dockerfile with the docker build command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.

The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.

Represent space and tab in XML tag

For me, to make it work I need to encode hex value of space within CDATA xml element, so that post parsing it adds up just as in the htm webgae & when viewed in browser just displays a space!. ( all above ideas & answers are useful )

<my-xml-element><![CDATA[&#x20;]]></my-xml-element>

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

SQL Server - In clause with a declared variable

Try this:

CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
  SELECT * FROM A WHERE ID NOT IN (@excludedlist)

And then call it like this:

DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

Is Python strongly typed?

Python is strongly, dynamically typed.

  • Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
  • Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.

As for your example

bob = 1
bob = "bob"

This works because the variable does not have a type; it can name any object. After bob=1, you'll find that type(bob) returns int, but after bob="bob", it returns str. (Note that type is a regular function, so it evaluates its argument, then returns the type of the value.)

Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)

I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.

The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., + is overloaded so that it works on two numbers or two strings, but not a string and an number. This is a design choice made when + was implemented, but not really a necessity following from the language's semantics. In fact, when you overload + on a custom type, you can make it implicitly convert anything to a number:

def to_number(x):
    """Try to convert function argument to float-type object."""
    try: 
        return float(x) 
    except (TypeError, ValueError): 
        return 0 

class Foo:
    def __init__(self, number): 
        self.number = number

    def __add__(self, other):
        return self.number + to_number(other)

Instance of class Foo can be added to other objects:

>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42

Observe that even though strongly typed Python is completely fine with adding objects of type int and float and returns an object of type float (e.g., int(42) + float(1) returns 43.0). On the other hand, due to the mismatch between types Haskell would complain if one tries the following (42 :: Integer) + (1 :: Float). This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to redirect both stdout and stderr to a file

Use:

command >>log_file 2>>log_file

http://localhost:50070 does not work HADOOP

First all need to do is start hadoop nodes and Trackers, simply by typing start-all.sh on ur terminal. To check all the trackers and nodes are started write 'jps' command. if everything is fine and working, go to your browser type the following url http://localhost:50070

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

Create PDF from a list of images

I know this is an old question. In my case I use Reportlab.

Sheet dimensions are expressed in points, not pixels, with a point equal to 1/72 inch. An A4 sheet is made up of 595.2 points width and 841.8 points height. The origin of the position coordinates (0, 0) is in the lower left corner. When creating an instance of canvas.Canvas, you can specify the size of the sheets using the pagesize parameter, passing a tuple whose first element represents the width in points and the second, the height. The c.showPage () method tells ReportLab that it has already finished working on the current sheet and moves on to the next one. Although a second sheet has not yet been worked on (and will not appear in the document as long as nothing has been drawn) it is good practice to remember to do so before invoking c.save (). To insert images into a PDF document, ReportLab uses the Pillow library. The drawImage () method takes as its argument the path of an image (supports multiple formats such as PNG, JPEG and GIF) and the position (x, y) in the that you want to insert. The image can be reduced or enlarged indicating its dimensions via the width and height arguments.

The following code provides pdf file name, list with png files, coordinates to insert images as well as size to fit in portrait letter pages.

def pntopd(file, figs, x, y, wi, he):
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4, letter, landscape, portrait
    w, h = letter
    c = canvas.Canvas(str(file), pagesize=portrait(letter))
    for png in figs:
        c.drawImage(png, x, h - y, width=wi, height=he)
        c.showPage()
    c.save()
    
    
    
from datetime import date
from pathlib import Path
ruta = "C:/SQLite"
today = date.today()
dat_dir = Path(ruta)
tit = today.strftime("%y%m%d") + '_ParameterAudit'
pdf_file = tit + ".pdf"
pdf_path = dat_dir / pdf_file
pnglist = ['C0.png', 'C4387.png', 'C9712.png', 'C9685.png', 'C4364.png']
pntopd(pdf_path, pnglist, 50, 550, 500, 500)

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

Get and Set Screen Resolution

In C# this is how to get the resolution Screen:

button click or form load:

string screenWidth = Screen.PrimaryScreen.Bounds.Width.ToString();
string screenHeight = Screen.PrimaryScreen.Bounds.Height.ToString();
Label1.Text = ("Resolution: " + screenWidth + "x" + screenHeight);

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

Using %f with strftime() in Python to get microseconds

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

libaio.so.1: cannot open shared object file

I had the same problem, and it turned out I hadn't installed the library.

this link was super usefull.

http://help.directadmin.com/item.php?id=368

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

What are the advantages of Sublime Text over Notepad++ and vice-versa?

It's best if you judge on your own,

1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).

http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text

This Link is no more working so please watch this video for similar details Video

Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)

Some Variation: Some user find plugins useful for PHP coders on that

http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html

although, there are many plugins for Notepad Plus Plus ..

I am not sure of your requirements, nor I am promoter of either of these editors :)

So, judge on basis of your requirements, this should satisfy you query...

Yes we can add that both are evolving and changing fast..

Activity restart on rotation Android

 onConfigurationChanged is called when the screen rotates. 
 (onCreate is no longer called when screen rotates due to manifest, see:  
 android:configChanges)

What part of the manifest tells it "don't call onCreate()"?

Also, Google's docs say to avoid using android:configChanges (except as a last resort).... But then the alternate methods they suggest all DO use android:configChanges.

It has been my experience that the emulator ALWAYS calls onCreate() upon rotation.
But the 1-2 devices that I run the same code on... do not. (Not sure why there would be any difference.)

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

failed to open stream: HTTP wrapper does not support writeable connections

Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).

You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.

How to check if a float value is a whole number

You can use the round function to compute the value.

Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:

def cube_integer(n):
    if round(n**(1.0/3.0))**3 == n:
        return True
    return False

But remember that int(n) is equivalent to math.floor and because of this if you find the int(41063625**(1.0/3.0)) you will get 344 instead of 345.

So please be careful when using int withe cube roots.

What does status=canceled for a resource mean in Chrome Developer Tools?

Here's what happened to me: the server was returning a malformed "Location" header for a 302 redirect. Chrome failed to tell me this, of course. I opened the page in firefox, and immediately discovered the problem. Nice to have multiple tools :)

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can easily install 1.8 via PPA. Which can be done by:

$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer

Then check the running version:

$ java -version

If you must do it manually there's already an answer for that on AskUbuntu here.

How to completely remove node.js from Windows

The best thing to do is to remove Node.js from the control panel. Once deleted download the desired version of Node.js and install it and it works.

Run/install/debug Android applications over Wi-Fi?

Though there are so many good answers, here is my two cents for the future me :P and for anyone who wants it quick and easy.

For Mac:

  • connect the device using USB first and make sure debugging is working. Disconnect any other devices and quit emulators.
  • open terminal and run the following script

    adb tcpip 5555
    adb connect $(adb shell ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d: -f2):5555
    
  • disconnect USB connection and the device should be available for WiFi debugging

Explanation:

adb tcpip 5555 commands the device to start listening for connections on port 5555

adb connect $(_ip_address_fetched_):5555 tells to connect on port 5555 of the _ip_address_fetched_ address

where _ip_address_fetched_ includes following:

adb shell ifconfig getting internet configurations using adb shell

grep "inter " filter any line that starts with inter

grep -v 127.0.0.1 exclude localhost.

At this point, output should be like:

inet addr:###.###.#.### Bcast:###.###.#.### Mask:255.255.255.0

awk '{print $2}' get the second part of the components array, separated by space (I'm using zsh).

The output up to this point is

addr:###.###.#.###

cut -d: -f2 split the string by delimiter : and take second part. It will only take your device IP address

Javascript onload not working

There's nothing wrong with include file in head. It seems you forgot to add;. Please try this one:

<body onload="imageRefreshBig();">

But as per my knowledge semicolons are optional. You can try with ; but better debug code and see if chrome console gives any error.

I hope this helps.

What is context in _.each(list, iterator, [context])?

Simple use of _.each

_x000D_
_x000D_
_.each(['Hello', 'World!'], function(word){_x000D_
    console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Here's simple example that could use _.each:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
_x000D_
_x000D_

Output:

items:  [ 'banana', 'apple', 'kiwi' ]

Instead of calling addItem multiple times you could use underscore this way:

_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });

which is identical to calling addItem three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item). The anonymous callback function is similar to addItem member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each avoids this indirection and calls addItem directly:

_.each(['banana', 'apple', 'kiwi'], x.addItem);

but this won't work, as inside basket's addItem member function this won't refer to your x basket that you created. That's why you have an option to pass your basket x to be used as [context]:

_.each(['banana', 'apple', 'kiwi'], x.addItem, x);

Full example that uses _.each and context:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In short, if callback function that you pass to _.each in any way uses this then you need to specify what this should be referring to inside your callback function. It may seem like x is redundant in my example, but x.addItem is just a function and could be totally unrelated to x or basket or any other object, for example:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
function addItem(item) {_x000D_
    this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In other words, you bind some value to this inside your callback, or you may as well use bind directly like this:

_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));

how this feature can be useful with some different underscore methods?

In general, if some underscorejs method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this) then you may bind that function to some object or pass that object as the [context] parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed

Python function to convert seconds into minutes, hours, and days

The "timeit" answer above that declares divmod to be slower has seriously flawed logic.

Test1 calls operators.

Test2 calls the function divmod, and calling a function has overhead.

A more accurate way to test would be:

import timeit

def moddiv(a,b):
  q= a/b
  r= a%b
  return q,r

a=10
b=3
md=0
dm=0
for i in range(1,10):
  c=a*i
  md+= timeit.timeit( lambda: moddiv(c,b))
  dm+=timeit.timeit( lambda: divmod(c,b))

print("moddiv ", md)
print("divmod ", dm)




moddiv  5.806157339000492

divmod  4.322451676005585

divmod is faster.

websocket closing connection automatically

Since @Doua Beri is experiencing connection close even when there are 1 Hz SENDs, it may be instead be due to size limits on messages.

This passage from Spring's WebSockets may be useful, with my emphasis ...

Although in theory a WebSocket message can be almost unlimited in size, in practice WebSocket servers impose limits — for example, 8K on Tomcat and 64K on Jetty. For this reason STOMP clients such as stomp.js split larger STOMP messages at 16K boundaries and send them as multiple WebSocket messages thus requiring the server to buffer and re-assemble.

How can I disable selected attribute from select2() dropdown Jquery?

As per select2 documentation: Click Here

If you wants to disable select2 then use this approach:

$(".js-example-disabled").prop("disabled", true);

If you wants to enable a disabled select2 box use this approach:

$(".js-example-disabled").prop("disabled", false);

wkhtmltopdf: cannot connect to X server

  1. Download file from this link
  2. Extract it and move executable file(/wkhtmltox/bin/wkhtmltopdf) to /usr/bin/
  3. Rename it to wkhtmltopdf if current name is not wkhtmltopdf. So that now you have an executable at /usr/bin/wkhtmltopdf
  4. Set permissions: sudo chmod a+x /usr/bin/wkhtmltopdf
  5. Install required support packages. sudo apt-get install openssl build-essential xorg libssl-dev
  6. Now, check with wkhtmltopdf http://www.google.com test.pdf hint: detail information from this link

Any easy way to use icons from resources?

After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension

For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:

NotifyIcon1.Icon = My.Resources.Logo_square

Merge two array of objects based on a key

We can use lodash here. _.merge works as you expected. It works with the common key present.

_.merge(array1, array2)

Print empty line?

This is are other ways of printing empty lines in python

# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n") 
print("\n") #prints 2 empty lines 
print() #prints 1 empty line 

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

Copy Image from Remote Server Over HTTP

For those who need to preserve the original filename and extension

$origin = 'http://example.com/image.jpg';

$filename = pathinfo($origin, PATHINFO_FILENAME);
$ext = pathinfo($origin, PATHINFO_EXTENSION);

$dest = 'myfolder/' . $filename . '.' . $ext;

copy($origin, $dest);

Using UPDATE in stored procedure with optional parameters

   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

How to parse string into date?

Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.

Difference between 'cls' and 'self' in Python classes?

Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

-Python Tricks

How do I add an active class to a Link from React Router?

Since router v4 I am using 'refs' for setting the parent active class:

<ul>
  <li>
    <NavLink
      innerRef={setParentAsActive}
      activeClassName="is-active"
      to={link}
    >
    {text}
  </NavLink>
</ul>

NavLink's innerRef prop accepts callback function, which will receive DOM node as an argument. You can use then any DOM manipulation possible, in this case simply set parent element (<li>) to have the same class:

  const setParentAsActive = node => {
    if (node) {
      node.parentNode.className = node.className;
    }
  };

Drawbacks:

  • <a> will have unnecessary is-active class (as you only need it for <li>), or you can remove this class in the callback func.
  • if you change the element structure, f.e. wrap a tag inside a span, your callback will stop working, but it's possible to write more sofisticated DOM traverse function
  • you have to do some DOM manipulation

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

Search for a particular string in Oracle clob column

select *  
from TABLE_NAME
where dbms_lob.instr(COLUMNNAME,'searchtext') > 0;

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

How to convert Strings to and from UTF8 byte arrays in Java

I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).

Force browser to clear cache

I implemented this simple solution that works for me (not yet on production environment):

function verificarNovaVersio() {
    var sVersio = localStorage['gcf_versio'+ location.pathname] || 'v00.0.0000';
    $.ajax({
        url: "./versio.txt"
        , dataType: 'text'
        , cache: false
        , contentType: false
        , processData: false
        , type: 'post'
     }).done(function(sVersioFitxer) {
        console.log('Versió App: '+ sVersioFitxer +', Versió Caché: '+ sVersio);
        if (sVersio < (sVersioFitxer || 'v00.0.0000')) {
            localStorage['gcf_versio'+ location.pathname] = sVersioFitxer;
            location.reload(true);
        }
    });
}

I've a little file located where the html are:

"versio.txt":

v00.5.0014

This function is called in all of my pages, so when loading it checks if the localStorage's version value is lower than the current version and does a

location.reload(true);

...to force reload from server instead from cache.

(obviously, instead of localStorage you can use cookies or other persistent client storage)

I opted for this solution for its simplicity, because only mantaining a single file "versio.txt" will force the full site to reload.

The queryString method is hard to implement and is also cached (if you change from v1.1 to a previous version will load from cache, then it means that the cache is not flushed, keeping all previous versions at cache).

I'm a little newbie and I'd apreciate your professional check & review to ensure my method is a good approach.

Hope it helps.