Programs & Examples On #Infinite carousel

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

What is the point of "final class" in Java?

In java final keyword uses for below occasions.

  1. Final Variables
  2. Final Methods
  3. Final Classes

In java final variables can't reassign, final classes can't extends and final methods can't override.

Boxplot show the value of mean

The Magrittr way

I know there is an accepted answer already, but I wanted to show one cool way to do it in single command with the help of magrittr package.

PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18)  %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text

This code will produce a boxplot with means printed as points and values: boxplot with means

I split the command on multiple lines so I can comment on what each part does, but it can also be entered as a oneliner. You can learn more about this in my gist.

What is the difference between Python and IPython?

IPython is a powerful interactive Python interpreter that is more interactive comparing to the standard interpreter.

To get the standard Python interpreter you type python and you will get the >>> prompt from where you can work.

To get IPython interpreter, you need to install it first. pip install ipython. You type ipython and you get In [1]: as a prompt and you get In [2]: for the next command. You can call history to check the list of previous commands, and write %recall 1 to recall the command.

Even you are in Python you can run shell commands directly like !ping www.google.com. Looks like a command line Jupiter notebook if you used that before.

You can use [Tab] to autocomplete as shown in the image. enter image description here

Return Result from Select Query in stored procedure to a List

// GET: api/GetStudent

public Response Get() {
    return StoredProcedure.GetStudent();
}

public static Response GetStudent() {
    using (var db = new dal()) {
        var student = db.Database.SqlQuery<GetStudentVm>("GetStudent").ToList();
        return new Response {
            Sucess = true,
            Message = student.Count() + " Student found",
            Data = student
        };
    }
}

Regex to check if valid URL that ends in .jpg, .png, or .gif

In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.

If you are keen on doing this, though, check out this question:

Getting parts of a URL (Regex)

Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like

(?i)\.(jpg|png|gif)$

How to check if a Constraint exists in Sql server?

try this:

SELECT
    * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME ='FK_ChannelPlayerSkins_Channels'

-- EDIT --

When I originally answered this question, I was thinking "Foreign Key" because the original question asked about finding "FK_ChannelPlayerSkins_Channels". Since then many people have commented on finding other "constraints" here are some other queries for that:

--Returns one row for each CHECK, UNIQUE, PRIMARY KEY, and/or FOREIGN KEY
SELECT * 
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'  


--Returns one row for each FOREIGN KEY constrain
SELECT * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME='XYZ'


--Returns one row for each CHECK constraint 
SELECT * 
    FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'

here is an alternate method

--Returns 1 row for each CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY, and/or DEFAULT
SELECT 
    OBJECT_NAME(OBJECT_ID) AS NameofConstraint
        ,SCHEMA_NAME(schema_id) AS SchemaName
        ,OBJECT_NAME(parent_object_id) AS TableName
        ,type_desc AS ConstraintType
    FROM sys.objects
    WHERE type_desc LIKE '%CONSTRAINT'
        AND OBJECT_NAME(OBJECT_ID)='XYZ'

If you need even more constraint information, look inside the system stored procedure master.sys.sp_helpconstraint to see how to get certain information. To view the source code using SQL Server Management Studio get into the "Object Explorer". From there you expand the "Master" database, then expand "Programmability", then "Stored Procedures", then "System Stored Procedures". You can then find "sys.sp_helpconstraint" and right click it and select "modify". Just be careful to not save any changes to it. Also, you can just use this system stored procedure on any table by using it like EXEC sp_helpconstraint YourTableNameHere.

Where do I find the line number in the Xcode editor?

To save $4.99 for a one time use and no dealing with HomeBrew and no counting empty lines.

  1. Open Terminal
  2. cd to your Xcode project
  3. Execute the following when inside your target project:

find . -name "*.swift" -print0 | xargs -0 wc -l

If you want to exclude pods:

find . -path ./Pods -prune -o -name "*.swift" -print0 ! -name "/Pods" | xargs -0 wc -l

If your project has objective c and swift:

find . -type d \( -path ./Pods -o -path ./Vendor \) -prune -o \( -iname \*.m -o -iname \*.mm -o -iname \*.h -o -iname \*.swift \) -print0 | xargs -0 wc -l

Using boolean values in C

Just a complement to other answers and some clarification, if you are allowed to use C99.

+-------+----------------+-------------------------+--------------------+
|  Name | Characteristic | Dependence in stdbool.h |        Value       |
+-------+----------------+-------------------------+--------------------+
| _Bool |   Native type  |    Don't need header    |                    |
+-------+----------------+-------------------------+--------------------+
|  bool |      Macro     |           Yes           | Translate to _Bool |
+-------+----------------+-------------------------+--------------------+
|  true |      Macro     |           Yes           |   Translate to 1   |
+-------+----------------+-------------------------+--------------------+
| false |      Macro     |           Yes           |   Translate to 0   |
+-------+----------------+-------------------------+--------------------+

Some of my preferences:

  • _Bool or bool? Both are fine, but bool looks better than the keyword _Bool.
  • Accepted values for bool and _Bool are: false or true. Assigning 0 or 1 instead of false or true is valid, but is harder to read and understand the logic flow.

Some info from the standard:

  • _Bool is NOT unsigned int, but is part of the group unsigned integer types. It is large enough to hold the values 0 or 1.
  • DO NOT, but yes, you are able to redefine bool true and false but sure is not a good idea. This ability is considered obsolescent and will be removed in future.
  • Assigning an scalar type (arithmetic types and pointer types) to _Bool or bool, if the scalar value is equal to 0 or compares to 0 it will be 0, otherwise the result is 1: _Bool x = 9; 9 is converted to 1 when assigned to x.
  • _Bool is 1 byte (8 bits), usually the programmer is tempted to try to use the other bits, but is not recommended, because the only guaranteed that is given is that only one bit is use to store data, not like type char that have 8 bits available.

How to get distinct results in hibernate with joins and row-based limiting (paging)?

if you want to use ORDER BY, just add:

criteria.setProjection(
    Projections.distinct(
        Projections.projectionList()
        .add(Projections.id())
        .add(Projections.property("the property that you want to ordered by"))
    )
);

Allow multiple roles to access controller action

If you find yourself applying those 2 roles often you can wrap them in their own Authorize. This is really an extension of the accepted answer.

using System.Web.Mvc;

public class AuthorizeAdminOrMember : AuthorizeAttribute
{
    public AuthorizeAdminOrMember()
    {
        Roles = "members, admin";
    }
}

And then apply your new authorize to the Action. I think this looks cleaner and reads easily.

public class MyController : Controller
{
    [AuthorizeAdminOrMember]
    public ActionResult MyAction()
    {
        return null;
    }
}

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

In my case, there was a mistake in the list of the parameters was not well formed. So make sure the parameters are well formed. For e.g. correct format of parameters

data: {'reporter': reporter,'partner': partner,'product': product}

How to compile a 64-bit application using Visual C++ 2010 Express?

Note that Visual C++ compilers are removed when you upgrade Visual Studio 2010 Professional or Visual Studio 2010 Express to Visual Studio 2010 SP1 if Windows SDK v7.1 is installed.

For instructions on resolving this, see KB2519277 on the Microsoft Support site.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

I would try to avoid inserting empty lists in the first place, but, would generally use:

d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty

If prior to 2.7:

d = dict( (k, v) for k,v in d.iteritems() if v )

or just:

empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
    del[k]

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

It is likely something else, but for the future readers, check your date time format. i had a 14th month

How to set a JVM TimeZone Properly

On windows 7 and for JDK6, I had to add -Duser.timezone="Europe/Sofia" to the JAVA_TOOL_OPTIONS system variable located under "My computer=>Properties=>Advanced System Settings=>Environment Variables".

If you already have some other property set for JAVA_TOOL_OPTIONS just append a space and then insert your property string.

How to stop/terminate a python script from running?

To stop a running program, use Ctrl+C to terminate the process.

To handle it programmatically in python, import the sys module and use sys.exit() where you want to terminate the program.

import sys
sys.exit()

Is it possible to print a variable's type in standard C++?

C++11 update to a very old question: Print variable type in C++.

The accepted (and good) answer is to use typeid(a).name(), where a is a variable name.

Now in C++11 we have decltype(x), which can turn an expression into a type. And decltype() comes with its own set of very interesting rules. For example decltype(a) and decltype((a)) will generally be different types (and for good and understandable reasons once those reasons are exposed).

Will our trusty typeid(a).name() help us explore this brave new world?

No.

But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to typeid(a).name(). And this new tool is actually built on top of typeid(a).name().

The fundamental issue:

typeid(a).name()

throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example:

const int ci = 0;
std::cout << typeid(ci).name() << '\n';

For me outputs:

i

and I'm guessing on MSVC outputs:

int

I.e. the const is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior.

What I'm recommending below is:

template <typename T> std::string type_name();

which would be used like this:

const int ci = 0;
std::cout << type_name<decltype(ci)>() << '\n';

and for me outputs:

int const

<disclaimer> I have not tested this on MSVC. </disclaimer> But I welcome feedback from those who do.

The C++11 Solution

I am using __cxa_demangle for non-MSVC platforms as recommend by ipapadop in his answer to demangle types. But on MSVC I'm trusting typeid to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type.

#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
#   include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>

template <class T>
std::string
type_name()
{
    typedef typename std::remove_reference<T>::type TR;
    std::unique_ptr<char, void(*)(void*)> own
           (
#ifndef _MSC_VER
                abi::__cxa_demangle(typeid(TR).name(), nullptr,
                                           nullptr, nullptr),
#else
                nullptr,
#endif
                std::free
           );
    std::string r = own != nullptr ? own.get() : typeid(TR).name();
    if (std::is_const<TR>::value)
        r += " const";
    if (std::is_volatile<TR>::value)
        r += " volatile";
    if (std::is_lvalue_reference<T>::value)
        r += "&";
    else if (std::is_rvalue_reference<T>::value)
        r += "&&";
    return r;
}

The Results

With this solution I can do this:

int& foo_lref();
int&& foo_rref();
int foo_value();

int
main()
{
    int i = 0;
    const int ci = 0;
    std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n';
    std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n';
    std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n';
    std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n';
    std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n';
    std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n';
    std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n';
    std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n';
    std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n';
    std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n';
}

and the output is:

decltype(i) is int
decltype((i)) is int&
decltype(ci) is int const
decltype((ci)) is int const&
decltype(static_cast<int&>(i)) is int&
decltype(static_cast<int&&>(i)) is int&&
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int&
decltype(foo_rref()) is int&&
decltype(foo_value()) is int

Note (for example) the difference between decltype(i) and decltype((i)). The former is the type of the declaration of i. The latter is the "type" of the expression i. (expressions never have reference type, but as a convention decltype represents lvalue expressions with lvalue references).

Thus this tool is an excellent vehicle just to learn about decltype, in addition to exploring and debugging your own code.

In contrast, if I were to build this just on typeid(a).name(), without adding back lost cv-qualifiers or references, the output would be:

decltype(i) is int
decltype((i)) is int
decltype(ci) is int
decltype((ci)) is int
decltype(static_cast<int&>(i)) is int
decltype(static_cast<int&&>(i)) is int
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int
decltype(foo_rref()) is int
decltype(foo_value()) is int

I.e. Every reference and cv-qualifier is stripped off.

C++14 Update

Just when you think you've got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-)

This answer from Jamboree shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons:

  1. It's at compile time!
  2. You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas).

Jamboree's answer doesn't quite lay everything out for VS, and I'm tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened.

#include <cstddef>
#include <stdexcept>
#include <cstring>
#include <ostream>

#ifndef _MSC_VER
#  if __cplusplus < 201103
#    define CONSTEXPR11_TN
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN
#  elif __cplusplus < 201402
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN noexcept
#  else
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN constexpr
#    define NOEXCEPT_TN noexcept
#  endif
#else  // _MSC_VER
#  if _MSC_VER < 1900
#    define CONSTEXPR11_TN
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN
#  elif _MSC_VER < 2000
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN
#    define NOEXCEPT_TN noexcept
#  else
#    define CONSTEXPR11_TN constexpr
#    define CONSTEXPR14_TN constexpr
#    define NOEXCEPT_TN noexcept
#  endif
#endif  // _MSC_VER

class static_string
{
    const char* const p_;
    const std::size_t sz_;

public:
    typedef const char* const_iterator;

    template <std::size_t N>
    CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN
        : p_(a)
        , sz_(N-1)
        {}

    CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN
        : p_(p)
        , sz_(N)
        {}

    CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}
    CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}

    CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}
    CONSTEXPR11_TN const_iterator end()   const NOEXCEPT_TN {return p_ + sz_;}

    CONSTEXPR11_TN char operator[](std::size_t n) const
    {
        return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
    }
};

inline
std::ostream&
operator<<(std::ostream& os, static_string const& s)
{
    return os.write(s.data(), s.size());
}

template <class T>
CONSTEXPR14_TN
static_string
type_name()
{
#ifdef __clang__
    static_string p = __PRETTY_FUNCTION__;
    return static_string(p.data() + 31, p.size() - 31 - 1);
#elif defined(__GNUC__)
    static_string p = __PRETTY_FUNCTION__;
#  if __cplusplus < 201402
    return static_string(p.data() + 36, p.size() - 36 - 1);
#  else
    return static_string(p.data() + 46, p.size() - 46 - 1);
#  endif
#elif defined(_MSC_VER)
    static_string p = __FUNCSIG__;
    return static_string(p.data() + 38, p.size() - 38 - 7);
#endif
}

This code will auto-backoff on the constexpr if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the noexcept is sacrificed as well.

C++17 Update

In the comments below Lyberta points out that the new std::string_view can replace static_string:

template <class T>
constexpr
std::string_view
type_name()
{
    using namespace std;
#ifdef __clang__
    string_view p = __PRETTY_FUNCTION__;
    return string_view(p.data() + 34, p.size() - 34 - 1);
#elif defined(__GNUC__)
    string_view p = __PRETTY_FUNCTION__;
#  if __cplusplus < 201402
    return string_view(p.data() + 36, p.size() - 36 - 1);
#  else
    return string_view(p.data() + 49, p.find(';', 49) - 49);
#  endif
#elif defined(_MSC_VER)
    string_view p = __FUNCSIG__;
    return string_view(p.data() + 84, p.size() - 84 - 7);
#endif
}

I've updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below.

Update:

Be sure to check out this rewrite below which eliminates the unreadable magic numbers in my latest formulation.

Multi value Dictionary

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

What exactly is OAuth (Open Authorization)?

Oauth is definitely gaining momentum and becoming popular among enterprise APIs as well. In the app and data driven world, Enterprises are exposing APIs more and more to the outer world in line with Google, Facebook, twitter. With this development a 3 way triangle of authentication gets formed

1) API provider- Any enterprise which exposes their assets by API, say Amazon,Target etc 2) Developer - The one who build mobile/other apps over this APIs 3) The end user- The end user of the service provided by the - say registered/guest users of Amazon

Now this develops a situation related to security - (I am listing few of these complexities) 1) You as an end user wants to allow the developer to access APIs on behalf of you. 2) The API provider has to authenticate the developer and the end user 3) The end user should be able to grant and revoke the permissions for the consent they have given 4) The developer can have varying level of trust with the API provider, in which the level of permissions given to her is different

The Oauth is an authorization framework which tries to solve the above mentioned problem in a standard way. With the prominence of APIs and Apps this problem will become more and more relevant and any standard which tries to solve it - be it ouath or any other - will be something to care about as an API provider/developer and even end user!

FromBody string parameter is giving null

Try the below code:

[Route("/test")]
[HttpPost]
public async Task Test()
{
   using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
   {
      var textFromBody = await reader.ReadToEndAsync();                    
   }            
}

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

You can first read the whole content of file into a String.

FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
    fileInputStream=new FileInputStream(filename);
    int i;
    while((i=fileInputStream.read())!=-1)
    {
        stringBuffer.append((char)i);
    }
    data = stringBuffer.toString();
}
catch(Exception e){
        LoggerUtil.printStackTrace(e);
}
finally{
    if(fileInputStream!=null){  
        fileInputStream.close();
    }
}

Now You will have the whole content into String ( data variable ).

JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);

After that you can use jsonArray as you want.

Eclipse Problems View not showing Errors anymore

This is normal problem. In wich order and export function sometimes get turned off.

right click on project<properties< there u hav option build path < and there ORDER AND EXPORT< click right all the options....all the things are right back.

How to open a different activity on recyclerView item onclick

Simply you can do it easy... You just need to get the context of your activity, here, from your View.

//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion

Remember that you need to modify AndroidManifest.xml and place the activity...

<activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>

Create whole path automatically when writing to a new file

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);

In Java, how do I get the difference in seconds between 2 dates?

That should do it:

Date a = ...;
Date b = ...;

Math.abs(a.getTime()-b.getTime())/1000;

Here the relevant documentation: Date.getTime(). Be aware that this will only work for dates after January 1, 1970, 00:00:00 GMT

No such keg: /usr/local/Cellar/git

Give another go at force removing the brewed version of git

brew uninstall --force git

Then cleanup any older versions and clear the brew cache

brew cleanup -s git

Remove any dead symlinks

brew cleanup --prune-prefix

Then try reinstalling git

brew install git

If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix directory (/usr/local by default), you can simply rm -rf $(brew --prefix). Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.

Create a Path from String in Java7

If possible I would suggest creating the Path directly from the path elements:

Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"

Which MySQL data type to use for storing boolean values

I got fed up with trying to get zeroes, NULLS, and '' accurately round a loop of PHP, MySql and POST values, so I just use 'Yes' and 'No'.

This works flawlessly and needs no special treatment that isn't obvious and easy to do.

Convert Unicode to ASCII without errors in Python

2018 Update:

As of February 2018, using compressions like gzip has become quite popular (around 73% of all websites use it, including large sites like Google, YouTube, Yahoo, Wikipedia, Reddit, Stack Overflow and Stack Exchange Network sites).
If you do a simple decode like in the original answer with a gzipped response, you'll get an error like or similar to this:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte

In order to decode a gzpipped response you need to add the following modules (in Python 3):

import gzip
import io

Note: In Python 2 you'd use StringIO instead of io

Then you can parse the content out like this:

response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource

This code reads the response, and places the bytes in a buffer. The gzip module then reads the buffer using the GZipFile function. After that, the gzipped file can be read into bytes again and decoded to normally readable text in the end.

Original Answer from 2010:

Can we get the actual value used for link?

In addition, we usually encounter this problem here when we are trying to .encode() an already encoded byte string. So you might try to decode it first as in

html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")

As an example:

html = '\xa0'
encoded_str = html.encode("utf8")

Fails with

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)

While:

html = '\xa0'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")

Succeeds without error. Do note that "windows-1252" is something I used as an example. I got this from chardet and it had 0.5 confidence that it is right! (well, as given with a 1-character-length string, what do you expect) You should change that to the encoding of the byte string returned from .urlopen().read() to what applies to the content you retrieved.

Another problem I see there is that the .encode() string method returns the modified string and does not modify the source in place. So it's kind of useless to have self.response.out.write(html) as html is not the encoded string from html.encode (if that is what you were originally aiming for).

As Ignacio suggested, check the source webpage for the actual encoding of the returned string from read(). It's either in one of the Meta tags or in the ContentType header in the response. Use that then as the parameter for .decode().

Do note however that it should not be assumed that other developers are responsible enough to make sure the header and/or meta character set declarations match the actual content. (Which is a PITA, yeah, I should know, I was one of those before).

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

Laravel: Get base url

You can use the URL facade which lets you do calls to the URL generator

So you can do:

URL::to('/');

You can also use the application container:

$app->make('url')->to('/');
$app['url']->to('/');
App::make('url')->to('/');

Or inject the UrlGenerator:

<?php
namespace Vendor\Your\Class\Namespace;

use Illuminate\Routing\UrlGenerator;

class Classname
{
    protected $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }

    public function methodName()
    {
        $this->url->to('/');
    }
}

Why does datetime.datetime.utcnow() not contain timezone information?

The behaviour of datetime.datetime.utcnow() returning UTC time as naive datetime object is obviously problematic and must be fixed. It can lead to unexpected result if your system local timezone is not UTC, since datetime library presume naive datetime object to represent system local time. For example, datetime.datetime.utcnow().timestaamp() gives timestamp of 4 hours ahead from correct value on my computer. Also, as of python 3.6, datetime.astimezone() can be called on naive datetime instances, but datetime.datetime.utcnow().astimezone(any_timezone) gives wrong result unless your system local timezone is UTC.

How to create a numpy array of all True or all False?

numpy already allows the creation of arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done.

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts results to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)

Difference between two DateTimes C#?

var theDiff24 = (b-a).Hours

Ruby function to remove all white spaces?

If you are using Rails/ActiveSupport, you can use squish method. It removes white space on both ends of the string and groups multiple white space to single space.

For eg.

" a  b  c ".squish

will result to:

"a b c"

Check this reference from api.rubyonrails.org.

Android Studio: /dev/kvm device permission denied

I countered the same problem and to solve this issue just type the following commands in terminal for Linux clients

   sudo apt-get install qemu-kvm

    // type your password

   sudo chmod 777 -R /dev/kvm

and after that try running simulator it'll work

How to add Python to Windows registry

English

In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:

Español

Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"

Select all text inside EditText when it gets focus

You can try in your main.xml file:

android:selectAllOnFocus="true"

Or, in Java, use

editText.setSelectAllOnFocus(true);

Debugging with Android Studio stuck at "Waiting For Debugger" forever

A similar question has been asked recently and the solution may work for some and is very quick.

Clearing the Intellij IDEA (Android Studio) .idea directory which contains configuration information worked for me:

  1. Exit Android Studio
  2. Navigate to the project you are trying to debug
  3. Backup any files inside .idea that you modified (if your project checks any of these into VCS)
  4. Delete .idea directory
  5. Open the project in Android Studio

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Convert data.frame column to a vector?

You could use $ extraction:

class(aframe$a1)
[1] "numeric"

or the double square bracket:

class(aframe[["a1"]])
[1] "numeric"

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

initializing a Guava ImmutableMap

if the map is short you can do:

ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs

If it is longer then:

ImmutableMap.builder()
   .put(key, value)
   .put(key2, value2)
   // ...
   .build();

Using Javascript in CSS

I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

How do I prevent site scraping?

I have done a lot of web scraping and summarized some techniques to stop web scrapers on my blog based on what I find annoying.

It is a tradeoff between your users and scrapers. If you limit IP's, use CAPTCHA's, require login, etc, you make like difficult for the scrapers. But this may also drive away your genuine users.

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

This does not disable curl exceptions for something like timeouts, but now you can get every status code easily:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

To check, if you got a valid code, you can use something like this:

if ($statuscode > 300) {
  // Do some error handling
}

... or better handle all expected codes:

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

For Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

Thanks to @mika

For Guzzle 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);

oracle diff: how to compare two tables?

Try:

select distinct T1.id
  from TABLE1 T1
 where not exists (select distinct T2.id
                     from TABLE2 T2
                    where T2.id = T1.id)

With sql oracle 11g+

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

Google Guava Libraries collection provides such function:

Iterator<String> it = Iterators.forArray(array);

One should prefere Guava over the Apache Collection (which seems to be abandoned).

What is the size of ActionBar in pixels?

I needed to do replicate these heights properly in a pre-ICS compatibility app and dug into the framework core source. Both answers above are sort of correct.

It basically boils down to using qualifiers. The height is defined by the dimension "action_bar_default_height"

It is defined to 48dip for default. But for -land it is 40dip and for sw600dp it is 56dip.

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

How can I check if a background image is loaded?

I did a pure javascript hack to make this possible.

<div class="my_background_image" style="background-image: url(broken-image.jpg)">
<img class="image_error" src="broken-image.jpg" onerror="this.parentElement.style.display='none';">
</div>

Or

onerror="this.parentElement.backgroundImage = "url('image_placeHolder.png')";

css:

.image_error {
    display: none;
}

How should I declare default values for instance variables in Python?

Using class members for default values of instance variables is not a good idea, and it's the first time I've seen this idea mentioned at all. It works in your example, but it may fail in a lot of cases. E.g., if the value is mutable, mutating it on an unmodified instance will alter the default:

>>> class c:
...     l = []
... 
>>> x = c()
>>> y = c()
>>> x.l
[]
>>> y.l
[]
>>> x.l.append(10)
>>> y.l
[10]
>>> c.l
[10]

Get size of a View in React Native

Maybe you can use measure:

measureProgressBar() {
    this.refs.welcome.measure(this.logProgressBarLayout);
},

logProgressBarLayout(ox, oy, width, height, px, py) {
  console.log("ox: " + ox);
  console.log("oy: " + oy);
  console.log("width: " + width);
  console.log("height: " + height);
  console.log("px: " + px);
  console.log("py: " + py);
}

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful

How to present UIAlertController when not in a view controller?

Swift 5

It's important to hide the window after showing the message.

func showErrorMessage(_ message: String) {
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()

    let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertController.Style.alert)
    alertController.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.cancel, handler: { _ in
        alertWindow.isHidden = true
    }))
    
    alertWindow.windowLevel = UIWindow.Level.alert + 1;
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
}

How to replace master branch in Git, entirely, from another branch?

You can rename/remove master on remote, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo.
That might not be the case here since everyone seems to be working on branch 'seotweaks'.

In that case you can:
git remote --show may not work. (Make a git remote show to check how your remote is declared within your local repo. I will assume 'origin')
(Regarding GitHub, house9 comments: "I had to do one additional step, click the 'Admin' button on GitHub and set the 'Default Branch' to something other than 'master', then put it back afterwards")

git branch -m master master-old  # rename master on local
git push origin :master          # delete master on remote
git push origin master-old       # create master-old on remote
git checkout -b master seotweaks # create a new local master on top of seotweaks
git push origin master           # create master on remote

But again:

  • if other users try to pull while master is deleted on remote, their pulls will fail ("no such ref on remote")
  • when master is recreated on remote, a pull will attempt to merge that new master on their local (now old) master: lots of conflicts. They actually need to reset --hard their local master to the remote/master branch they will fetch, and forget about their current master.

Android Get Current timestamp?

java.time

I should like to contribute the modern answer.

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

Output when running just now:

1543320466

While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

This is the same as the answer by sealskej. Output is the same as before.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

How to delete or add column in SQLITE?

Kotlin solution, based on here , but also ensures the temporary table doesn't already exist:

object DbUtil {
    @JvmStatic
    fun dropColumns(database: SQLiteDatabase, tableName: String, columnsToRemove: Collection<String>) {
        val columnNames: MutableList<String> = ArrayList()
        val columnNamesWithType: MutableList<String> = ArrayList()
        val primaryKeys: MutableList<String> = ArrayList()
        val query = "pragma table_info($tableName);"
        val cursor = database.rawQuery(query, null)
        while (cursor.moveToNext()) {
            val columnName = cursor.getString(cursor.getColumnIndex("name"))
            if (columnsToRemove.contains(columnName)) {
                continue
            }
            val columnType = cursor.getString(cursor.getColumnIndex("type"))
            val isNotNull = cursor.getInt(cursor.getColumnIndex("notnull")) == 1
            val isPk = cursor.getInt(cursor.getColumnIndex("pk")) == 1
            columnNames.add(columnName)
            var tmp = "`$columnName` $columnType "
            if (isNotNull) {
                tmp += " NOT NULL "
            }
            when (cursor.getType(cursor.getColumnIndex("dflt_value"))) {
                Cursor.FIELD_TYPE_STRING -> {
                    tmp += " DEFAULT \"${cursor.getString(cursor.getColumnIndex("dflt_value"))}\" "
                }
                Cursor.FIELD_TYPE_INTEGER -> {
                    tmp += " DEFAULT ${cursor.getInt(cursor.getColumnIndex("dflt_value"))} "
                }
                Cursor.FIELD_TYPE_FLOAT -> {
                    tmp += " DEFAULT ${cursor.getFloat(cursor.getColumnIndex("dflt_value"))} "
                }
            }
            columnNamesWithType.add(tmp)
            if (isPk) {
                primaryKeys.add("`$columnName`")
            }
        }
        cursor.close()
        val columnNamesSeparated = TextUtils.join(", ", columnNames)
        if (primaryKeys.size > 0) {
            columnNamesWithType.add("PRIMARY KEY(${TextUtils.join(", ", primaryKeys)})")
        }
        val columnNamesWithTypeSeparated = TextUtils.join(", ", columnNamesWithType)
        database.beginTransaction()
        try {
            var newTempTableName: String
            var counter = 0
            while (true) {
                newTempTableName = "${tableName}_old_$counter"
                if (!isTableExists(database, newTempTableName))
                    break
                ++counter
            }
            database.execSQL("ALTER TABLE $tableName RENAME TO $newTempTableName;")
            database.execSQL("CREATE TABLE $tableName ($columnNamesWithTypeSeparated);")
            database.execSQL("INSERT INTO $tableName ($columnNamesSeparated) SELECT $columnNamesSeparated FROM $newTempTableName;")
            database.execSQL("DROP TABLE ${newTempTableName};")
            database.setTransactionSuccessful()
        } finally {
            database.endTransaction()
        }
    }

    @JvmStatic
    fun isTableExists(database: SQLiteDatabase, tableName: String): Boolean {
        database.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '$tableName'", null)?.use {
            return it.count > 0
        } ?: return false
    }
}

Set disable attribute based on a condition for Html.TextBoxFor

The valid way is:

disabled="disabled"

Browsers also might accept disabled="" but I would recommend you the first approach.

Now this being said I would recommend you writing a custom HTML helper in order to encapsulate this disabling functionality into a reusable piece of code:

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

which you could use like this:

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }, 
    Model.ExpireDate == null
)

and you could bring even more intelligence into this helper:

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        if (metaData.Model == null)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

so that now you no longer need to specify the disabled condition:

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }
)

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

jQuery Date Picker - disable past dates

$('#datepicker-dep').datepicker({
    minDate: 0
});

minDate:0 works for me.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

R has gotten to the point where the OS cannot allocate it another 75.1Mb chunk of RAM. That is the size of memory chunk required to do the next sub-operation. It is not a statement about the amount of contiguous RAM required to complete the entire process. By this point, all your available RAM is exhausted but you need more memory to continue and the OS is unable to make more RAM available to R.

Potential solutions to this are manifold. The obvious one is get hold of a 64-bit machine with more RAM. I forget the details but IIRC on 32-bit Windows, any single process can only use a limited amount of RAM (2GB?) and regardless Windows will retain a chunk of memory for itself, so the RAM available to R will be somewhat less than the 3.4Gb you have. On 64-bit Windows R will be able to use more RAM and the maximum amount of RAM you can fit/install will be increased.

If that is not possible, then consider an alternative approach; perhaps do your simulations in batches with the n per batch much smaller than N. That way you can draw a much smaller number of simulations, do whatever you wanted, collect results, then repeat this process until you have done sufficient simulations. You don't show what N is, but I suspect it is big, so try smaller N a number of times to give you N over-all.

MS SQL compare dates?

The simple one line solution is

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')=0

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')<=1

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')>=1

You can try various option with this other than "dd"

Display encoded html with razor

this is pretty simple:

HttpUtility.HtmlDecode(Model.Content)

Another Solution, you could also return a HTMLString, Razor will output the correct formatting:

in the view itself:

@Html.GetSomeHtml()

in controller:

public static HtmlString GetSomeHtml()
{
    var Data = "abc<br/>123";
    return new HtmlString(Data);
}

How to set background color of a button in Java GUI?

Use the setBackground method to set the background and setForeground to change the colour of your text. Note however, that putting grey text over a black background might make your text a bit tough to read.

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

Why is C so fast, and why aren't other languages as fast or faster?

The main factors are that it's a statically-typed language and that's compiled to machine code. Also, since it's a low-level language, it generally doesn't do anything you don't tell it to.

These are some other factors that come to mind.

  • Variables are not automatically initialized
  • No bounds checking on arrays
  • Unchecked pointer manipulation
  • No integer overflow checking
  • Statically-typed variables
  • Function calls are static (unless you use function pointers)
  • Compiler writers have had lots of time to improve the optimizing code. Also, people program in C for the purpose of getting the best performance, so there's pressure to optimize the code.
  • Parts of the language specification are implementation-defined, so compilers are free to do things in the most optimal way

Most static-typed languages could be compiled just as fast or faster than C though, especially if they can make assumptions that C can't because of pointer aliasing, etc.

Add border-bottom to table row <tr>

I found when using this method that the space between the td elements caused a gap to form in the border, but have no fear...

One way around this:

<tr>
    <td>
        Example of normal table data
    </td>

    <td class="end" colspan="/* total number of columns in entire table*/">
        /* insert nothing in here */ 
    </td>
</tr>

With the CSS:

td.end{
    border:2px solid black;
}

Is it possible to get a history of queries made in postgres

You can use like

\s 

it will fetch you all command history of the terminal, to export it to file using

\s filename

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Authentication issue when debugging in VS2013 - iis express

I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.

I tried changing the IIS express applicationhost.config, no difference.

The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.

Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.

Works like gravy :)

how to convert java string to Date object

var startDate = "06/27/2007";
startDate = new Date(startDate);

console.log(startDate);

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

Angular cli generate a service and include the provider in one step

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

There is not a big choice of elements that might get auto-assigned with a scrollTop value as we scroll a webpage.

So I wrote this little function to iterate through the probable elements and return the one we seek.

var grab=function (){
    var el=$();
        $('body#my_body, html, document').each(function(){
            if ($(this).scrollTop()>0) {
                el= ($(this));
                return false;
            }
        })
    return el;
}
//alert(grab().scrollTop());

In Google chrome it would get us the body, in IE - HTML.

(Note, we don't need to set overflow:auto explicitly on our html or body that way.)

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

MAX(DATE) - SQL ORACLE

select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

adding text to an existing text element in javascript via DOM

   <!DOCTYPE html>
   <html>
   <head>
   <script   src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
   $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
   });

  });
 </script>
  </head>
 <body>

 <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>



 <button id="btn1">Append text</button>


</body>
</html>

Why is there no String.Empty in Java?

Use org.apache.commons.lang.StringUtils.EMPTY

.do extension in web pages?

Using apache's rewrite_module can change your script extensions. Give this thread a good read.

What is the use of static synchronized method in java?

static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods. So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

"Module" property of View Controller in the Identity Inspector might be different than what you expected. Also make sure that new classes are added to your target list.

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

How to handle static content in Spring MVC?

Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/> (more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.

In order to use this, use a directory structure that looks like the following:

src/
 springmvc/
  web/
   MyController.java
WebContent/
  resources/
   img/
    image.jpg
  WEB-INF/
    jsp/
      index.jsp
    web.xml
    springmvc-servlet.xml

The contents of the files should look like:

src/springmvc/web/HelloWorldController.java:

package springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

 @RequestMapping(value="/")
 public String index() {
  return "index";
 }
}

WebContent/WEB-INF/web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

WebContent/WEB-INF/springmvc-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
 <context:component-scan base-package="springmvc.web" />

    <!-- the mvc resources tag does the magic -->
 <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- also add the following beans to get rid of some exceptions -->
 <bean      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
 </bean>

    <!-- JSTL resolver -->
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

WebContent/jsp/index.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />

Hope this helps :-)

How to select all instances of selected region in Sublime Text

On Mac:

?+CTRL+g

However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.


On Windows/Linux:

Alt+F3

If anyone has how-tos or articles on this, I'd be more than happy to update.

Select all where [first letter starts with B]

SELECT author FROM lyrics WHERE author LIKE 'B%';

Make sure you have an index on author, though!

How to convert this var string to URL in Swift

you need to do:

let fileUrl = URL(string: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

depending on your needs. See URL docs

Before Swift 3, URL was called NSURL.

How to save SELECT sql query results in an array in C# Asp.net

Normally i use a class for this:

public class ClassName
{
    public string Col1 { get; set; }
    public int Col2 { get; set; }
}

Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
{
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();
    }
}

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

How to position text over an image in css

This is another method for working with Responsive sizes. It will keep your text centered and maintain its position within its parent. If you don't want it centered then it's even easier, just work with the absolute parameters. Keep in mind the main container is using display: inline-block. There are many others ways to do this, depending on what you're working on.

Based off of Centering the Unknown

Working codepen example here

HTML

<div class="containerBox">
    <div class="text-box">
        <h4>Your Text is responsive and centered</h4>
    </div>
    <img class="img-responsive" src="http://placehold.it/900x100"/>
</div>

CSS

.containerBox {
    position: relative;
    display: inline-block;
}
.text-box {
    position: absolute;    
    height: 100%;
    text-align: center;    
    width: 100%;
}
.text-box:before {
   content: '';
   display: inline-block;
   height: 100%;
   vertical-align: middle;
}
h4 {
   display: inline-block;
   font-size: 20px; /*or whatever you want*/
   color: #FFF;   
}
img {
  display: block;
  max-width: 100%;
  height: auto;
}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.

Word-wrap in an HTML table

This works for me:

<style type="text/css">
    td {

        /* CSS 3 */
        white-space: -o-pre-wrap;
        word-wrap: break-word;
        white-space: pre-wrap;
        white-space: -moz-pre-wrap;
        white-space: -pre-wrap;
    }

And table attribute is:

   table {
      table-layout: fixed;
      width: 100%
   }

</style>

How to enable curl in xampp?

It should be available in php.ini file. You need to un-comment the line for curl extension:

  ;extension=php_curl.dll
  ^----- remove semi-colon

Why does the JFrame setSize() method not set the size correctly?

It's probably because size of a frame includes the size of the border.

A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).

Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

Android Studio - Importing external Library/Jar

I'm using Android Studio 0.5.2. So if your version is lower than mine my answer may not work for you.

3 ways to add a new Jar to your project:

  1. Menu under Files-->Project Structure
  2. Just press 'F4'
  3. under Project navigation, right clink on any java library and a context menu will show then click on 'Open Library Settings'

A Project Structure window will popup.

On the left column click on 'Libraries' then look at the right pane where there is a plus sign '+' and click on it then enter the path to your new library.

Make sure the new library is under the 'project\libs\' folder otherwise you may get a broken link when you save your project source code.

Handling urllib2's timeout? - Python

There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

At the very simplest, you would catch urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

The following should capture the specific error raised when the connection times out:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

Get bytes from std::string in C++

From a std::string you can use the c_ptr() method if you want to get at the char_t buffer pointer.

It looks like you just want copy the characters of the string into a new buffer. I would simply use the std::string::copy function:

length = str.copy( buffer, str.size() );

How do I make a Mac Terminal pop-up/alert? Applescript?

And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message

MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'

A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell

sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep  zzZZ";  afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

Show image using file_get_contents

$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="' . $src . '">';

How to connect android wifi to adhoc wifi?

You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.

Android: Difference between Parcelable and Serializable?

In Parcelable, developers write custom code for marshalling and unmarshalling so it creates fewer garbage objects in comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.

Serializable is a marker interface, which implies that user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java object's member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Edit: What is the meaning of marshalling and unmarshalling?

In few words, "marshalling" refers to the process of converting the data or the objects into a byte-stream, and "unmarshalling" is the reverse process of converting the byte-stream back to their original data or object. The conversion is achieved through "serialization".

http://www.jguru.com/faq/view.jsp?EID=560072

How to tell PowerShell to wait for each command to end before starting the next?

If you use Start-Process <path to exe> -NoNewWindow -Wait

You can also use the -PassThru option to echo output.

How can I remove file extension from a website address?

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

Old page: http://something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

How to get a list of programs running with nohup

If you have standart output redirect to "nohup.out" just see who use this file

lsof | grep nohup.out

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Binary Search Tree - Java Implementation

Here is my simple binary search tree implementation in Java SE 1.8:

public class BSTNode
{
    int data;
    BSTNode parent;
    BSTNode left;
    BSTNode right;

    public BSTNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
        this.parent = null;
    }

    public BSTNode()
    {
    }
}

public class BSTFunctions
{
    BSTNode ROOT;

    public BSTFunctions()
    {
        this.ROOT = null;
    }

    void insertNode(BSTNode node, int data)
    {
        if (node == null)
        {
            node = new BSTNode(data);
            ROOT = node;
        }
        else if (data < node.data && node.left == null)
        {
            node.left = new BSTNode(data);
            node.left.parent = node;
        }
        else if (data >= node.data && node.right == null)
        {
            node.right = new BSTNode(data);
            node.right.parent = node;
        }
        else
        {
            if (data < node.data)
            {
                insertNode(node.left, data);
            }
            else
            {
                insertNode(node.right, data);
            }
        }
    }

    public boolean search(BSTNode node, int data)
    {
        if (node == null)
        {
            return false;
        }
        else if (node.data == data)
        {
            return true;
        }
        else
        {
            if (data < node.data)
            {
                return search(node.left, data);
            }
            else
            {
                return search(node.right, data);
            }
        }
    }

    public void printInOrder(BSTNode node)
    {
        if (node != null)
        {
            printInOrder(node.left);
            System.out.print(node.data + " - ");
            printInOrder(node.right);
        }
    }

    public void printPostOrder(BSTNode node)
    {
        if (node != null)
        {
            printPostOrder(node.left);
            printPostOrder(node.right);
            System.out.print(node.data + " - ");
        }
    }

    public void printPreOrder(BSTNode node)
    {
        if (node != null)
        {
            System.out.print(node.data + " - ");
            printPreOrder(node.left);
            printPreOrder(node.right);
        }
    }

    public static void main(String[] args)
    {
        BSTFunctions f = new BSTFunctions();
        /**
         * Insert
         */
        f.insertNode(f.ROOT, 20);
        f.insertNode(f.ROOT, 5);
        f.insertNode(f.ROOT, 25);
        f.insertNode(f.ROOT, 3);
        f.insertNode(f.ROOT, 7);
        f.insertNode(f.ROOT, 27);
        f.insertNode(f.ROOT, 24);

        /**
         * Print
         */
        f.printInOrder(f.ROOT);
        System.out.println("");
        f.printPostOrder(f.ROOT);
        System.out.println("");
        f.printPreOrder(f.ROOT);
        System.out.println("");

        /**
         * Search
         */
        System.out.println(f.search(f.ROOT, 27) ? "Found" : "Not Found");
        System.out.println(f.search(f.ROOT, 10) ? "Found" : "Not Found");
    }
}

And the output is:

3 - 5 - 7 - 20 - 24 - 25 - 27 - 
3 - 7 - 5 - 24 - 27 - 25 - 20 - 
20 - 5 - 3 - 7 - 25 - 24 - 27 - 
Found
Not Found

How to center horizontal table-cell

Short snippet for future visitors - how to center horizontal table-cell (+ vertically)

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  text-align: center; /* the key */_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: inline-block; /* important !! */_x000D_
  width: 100px;_x000D_
  background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
  <div class="cell">_x000D_
    <div class="content" id="a">_x000D_
      <p>Content</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

Here's my solution if you created the repository with some default readme file or license

git init
git add -A
git commit -m "initial commit"   
git remote add origin https://<git-userName>@github.com/xyz.git //Add your username so it will avoid asking username each time before you push your code
git fetch
git pull https://github.com/xyz.git <branch>
git push origin <branch> 

What is the difference between ndarray and array in numpy?

numpy.array is just a convenience function to create an ndarray; it is not a class itself.

You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray:

Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:

https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py

Xcode 9 error: "iPhone has denied the launch request"

The problem is that xcode 'times out' after certain seconds. The fix is to edit the scheme and ask xcode to 'wait' until the executable is launched.

In Edit Scheme, check 'Wait for executable to be launched' instead of 'Automatically'

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

Editing dictionary values in a foreach loop

You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:

Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();

foreach (string key in colStates.Keys)
{

    double Percent = colStates[key] / colStates.Count;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        notRelevantKeys.Add(key);
    }
}

foreach (string key in notRelevantKeys)
{
    colStates[key] = 0;
}

colStates.Add("Other", OtherCount);

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

In-place type conversion of a NumPy array

You can change the array type without converting like this:

a.dtype = numpy.float32

but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's struct module like this:

def toi(i):
    return struct.unpack('i',struct.pack('f',float(i)))[0]

...applied to each member of your array.

But perhaps a faster way would be to utilize numpy's ctypeslib tools (which I am unfamiliar with)

- edit -

Since ctypeslib doesnt seem to work, then I would proceed with the conversion with the typical numpy.astype method, but proceed in block sizes that are within your memory limits:

a[0:10000] = a[0:10000].astype('float32').view('int32')

...then change the dtype when done.

Here is a function that accomplishes the task for any compatible dtypes (only works for dtypes with same-sized items) and handles arbitrarily-shaped arrays with user-control over block size:

import numpy

def astype_inplace(a, dtype, blocksize=10000):
    oldtype = a.dtype
    newtype = numpy.dtype(dtype)
    assert oldtype.itemsize is newtype.itemsize
    for idx in xrange(0, a.size, blocksize):
        a.flat[idx:idx + blocksize] = \
            a.flat[idx:idx + blocksize].astype(newtype).view(oldtype)
    a.dtype = newtype

a = numpy.random.randint(100,size=100).reshape((10,10))
print a
astype_inplace(a, 'float32')
print a

Exporting result of select statement to CSV format in DB2

This is how you can do it from DB2 client.

  1. Open the Command Editor and Run the select Query in the Commands Tab.

  2. Open the corresponding Query Results Tab

  3. Then from Menu --> Selected --> Export

Is it possible to send an array with the Postman Chrome extension?

in headers set

content-type : application/x-www-form-urlencoded

In body select option

x-www-form-urlencoded

and insert data as json array

user_ids : ["1234", "5678"]

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

Visual Studio opens the default browser instead of Internet Explorer

For MVC3 you don't have to add any dummy files to set a certain browser. All you have to do is:

  • "Show all files" for the project
  • go to bin folder
  • right click the only .xml file to find the "Browse With..." option

setting MVC3 project default browser

How to preSelect an html dropdown list with php?

you can use this..

<select name="select_name">
    <option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
    <option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
    <option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>

How to style the option of an html "select" element?

Seems like I can just set the CSS for the select in Chrome directly. CSS and HTML code provided below :

_x000D_
_x000D_
.boldoption {_x000D_
 font-weight: bold;_x000D_
}
_x000D_
<select>_x000D_
 <option>Some normal-font option</option>_x000D_
 <option>Another normal-font option</option>_x000D_
 <option class="boldoption">Some bold option</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_ enter image description here

how to fix java.lang.IndexOutOfBoundsException

This error happens because your list lstpp is empty (Nothing at index 0). So either there is a bug in your getResult() function, or the empty list is normal and you need to handle this case (By checking the size of the list before, or catching the exception).

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

This worked for me.

   /**
     * return date in specific format, given a timestamp.
     *
     * @param  timestamp  $datetime
     * @return string
     */
    public static function showDateString($timestamp)
    {
      if ($timestamp !== NULL) {
        $date = new DateTime();
        $date->setTimestamp(intval($timestamp));
        return $date->format("d-m-Y");
      }
      return '';
    }

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

How to make Java honor the DNS Caching Timeout?

This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.

/**
 * http://stackoverflow.com/questions/1256556/any-way-to-make-java-honor-the-dns-caching-timeout-ttl
 *
 * Result: Java 6 distributed with Ubuntu 12.04 and Java 7 u15 downloaded from Oracle have
 * an expiry time for dns lookups of approx. 30 seconds.
 */

import java.util.*;
import java.text.*;
import java.security.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Test {
    final static String hostname = "www.google.com";
    public static void main(String[] args) {
        // only required for Java SE 5 and lower:
        //Security.setProperty("networkaddress.cache.ttl", "30");

        System.out.println(Security.getProperty("networkaddress.cache.ttl"));
        System.out.println(System.getProperty("networkaddress.cache.ttl"));
        System.out.println(Security.getProperty("networkaddress.cache.negative.ttl"));
        System.out.println(System.getProperty("networkaddress.cache.negative.ttl"));

        while(true) {
            int i = 0;
            try {
                makeRequest();
                InetAddress inetAddress = InetAddress.getLocalHost();
                System.out.println(new Date());
                inetAddress = InetAddress.getByName(hostname);
                displayStuff(hostname, inetAddress);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(5L*1000L);
            } catch(Exception ex) {}
            i++;
        }
    }

    public static void displayStuff(String whichHost, InetAddress inetAddress) {
        System.out.println("Which Host:" + whichHost);
        System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
        System.out.println("Host Name:" + inetAddress.getHostName());
        System.out.println("Host Address:" + inetAddress.getHostAddress());
    }

    public static void makeRequest() {
        try {
            URL url = new URL("http://"+hostname+"/");
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            InputStreamReader ird = new InputStreamReader(is);
            BufferedReader rd = new BufferedReader(ird);
            String res;
            while((res = rd.readLine()) != null) {
                System.out.println(res);
                break;
            }
            rd.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

Left Outer Join using + sign in Oracle 11g

I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

How can I set size of a button?

The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible

JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));

for(int i=0 ; i<16 ; i++){
    JButton btn = new JButton(String.valueOf(i));
    btn.setPreferredSize(new Dimension(40, 40));
    panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);

The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.

Edit

I've modified the provided code and I believe it now conforms to what is desired:

JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
    for (int j=1; j<=4; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(100, 100));
        firstPanel.add(btn);
    }
}

JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
    for (int j=1; j<=13; j++) {
        btn = new JButton();
        btn.setPreferredSize(new Dimension(40, 40));
        secondPanel.add(btn);
    }
}

mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);

frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);

Basically I now set the preferred size of the panels and a minimum size for the frame.

Bash script to cd to directory with spaces in pathname

This will do it:

cd ~/My\ Code

I've had to use that to work with files stored in the iCloud Drive. You won't want to use double quotes (") as then it must be an absolute path. In other words, you can't combine double quotes with tilde (~).

By way of example I had to use this for a recent project:

cd ~/Library/Mobile\ Documents/com~apple~CloudDocs/Documents/Documents\ -\ My\ iMac/Project

I hope that helps.

Split pandas dataframe in two if it has more than 10 rows

There is no specific convenience function.

You'd have to do something like:

first_ten = pd.DataFrame()
rest = pd.DataFrame()

if df.shape[0] > 10: # len(df) > 10 would also work
    first_ten = df[:10]
    rest = df[10:]

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

Access index of last element in data frame

You want .iloc with double brackets.

import pandas as pd
df = pd.DataFrame({"date": range(10, 64, 8), "not_date": "fools"})
df.index += 17
df.iloc[[0,-1]][['date']]

You give .iloc a list of indexes - specifically the first and last, [0, -1]. That returns a dataframe from which you ask for the 'date' column. ['date'] will give you a series (yuck), and [['date']] will give you a dataframe.

Laravel Advanced Wheres how to pass variable into function?

@kajetons' answer is fully functional.

You can also pass multiple variables by passing them like: use($var1, $var2)

DB::table('users')->where(function ($query) use ($activated,$var2) {
    $query->where('activated', '=', $activated);
    $query->where('var2', '>', $var2);
})->get();

Closing Application with Exit button

try this for close app

Activity.finish();
System.exit(0);

Secondary axis with twinx(): how to add to legend?

From matplotlib version 2.1 onwards, you may use a figure legend. Instead of ax.legend(), which produces a legend with the handles from the axes ax, one can create a figure legend

fig.legend(loc="upper right")

which will gather all handles from all subplots in the figure. Since it is a figure legend, it will be placed at the corner of the figure, and the loc argument is relative to the figure.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, '-', label = 'Quantity 1')

ax2 = ax.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')
fig.legend(loc="upper right")

ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")

plt.show()

enter image description here

In order to place the legend back into the axes, one would supply a bbox_to_anchor and a bbox_transform. The latter would be the axes transform of the axes the legend should reside in. The former may be the coordinates of the edge defined by loc given in axes coordinates.

fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)

enter image description here

How to check if a String is numeric in Java

This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function).

Something like:

public static boolean isNumeric(String str) { 
  try {  
    Double.parseDouble(str);  
    return true;
  } catch(NumberFormatException e){  
    return false;  
  }  
}

However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.

An alternative approach may be to use a regular expression to check for validity of being a number:

public static boolean isNumeric(String str) {
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}

Be careful with the above RegEx mechanism, though, as it will fail if you're using non-Arabic digits (i.e. numerals other than 0 through to 9). This is because the "\d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware. (Thanks to OregonGhost for pointing this out!)

Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric:

public static boolean isNumeric(String str) {
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition pos = new ParsePosition(0);
  formatter.parse(str, pos);
  return str.length() == pos.getIndex();
}

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Wildcards in a Windows hosts file

You can use a dynamic DNS client such as http://www.no-ip.com. Then, with an external DNS server CNAME *.mydomain.com to mydomain.no-ip.com.

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

How to convert a SVG to a PNG with ImageMagick?

Try svgexport:

svgexport input.svg output.png 64x
svgexport input.svg output.png 1024:1024

svgexport is a simple cross-platform command line tool that I have made for exporting svg files to jpg and png, see here for more options. To install svgexport install npm, then run:

npm install svgexport -g

Edit: If you find an issue with the library, please submit it on GitHub, thanks!

Eclipse "this compilation unit is not on the build path of a java project"

What worked for me was copping the .settings/ directory from another project.

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

How to reduce the image size without losing quality in PHP

well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.

How to execute a program or call a system command from Python

I quite like shell_command for its simplicity. It's built on top of the subprocess module.

Here's an example from the documentation:

>>> from shell_command import shell_call
>>> shell_call("ls *.py")
setup.py  shell_command.py  test_shell_command.py
0
>>> shell_call("ls -l *.py")
-rw-r--r-- 1 ncoghlan ncoghlan  391 2011-12-11 12:07 setup.py
-rw-r--r-- 1 ncoghlan ncoghlan 7855 2011-12-11 16:16 shell_command.py
-rwxr-xr-x 1 ncoghlan ncoghlan 8463 2011-12-11 16:17 test_shell_command.py
0

Determine if an element has a CSS class with jQuery

 $('.segment-name').click(function () {
    if($(this).hasClass('segment-a')){
        //class exist
    }
});

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

What's the difference between Perl's backticks, system, and exec?

The difference between 'exec' and 'system' is that exec replaces your current program with 'command' and NEVER returns to your program. system, on the other hand, forks and runs 'command' and returns you the exit status of 'command' when it is done running. The back tick runs 'command' and then returns a string representing its standard out (whatever it would have printed to the screen)

You can also use popen to run shell commands and I think that there is a shell module - 'use shell' that gives you transparent access to typical shell commands.

Hope that clarifies it for you.

Sum of values in an array using jQuery

You don't need jQuery. You can do this using a for loop:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

Python copy files to a new directory and rename if file name already exists

I always use the time-stamp - so its not possible, that the file exists already:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)

Fatal error: "No Target Architecture" in Visual Studio

If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:

  • #include <consoleapi2.h
  • #include <apiquery2.h>
  • #include <fileapi.h>

UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.

The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.

How to create EditText with cross(x) button at end of it?

Here is the simple complete solution in kotlin.

This whole layout will be your search bar

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_margin="10dp"
        android:background="@drawable/your_desired_drawable">

        <EditText
            android:id="@+id/search_et"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_toStartOf="@id/clear_btn"
            android:background="@null"
            android:hint="search..."
            android:imeOptions="actionSearch"
            android:inputType="text"
            android:maxLines="1"
            android:paddingStart="15dp"
            android:paddingEnd="10dp" />

        <ImageView
            android:id="@+id/clear_btn"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:layout_marginEnd="15dp"
            android:visibility="gone"
            android:src="@drawable/ic_baseline_clear_24"/>

    </RelativeLayout>

Now this is the functionality of clear button, paste this code in onCreate method.

search_et.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {
            }
            override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
            }
            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()){
                    clear_btn.visibility = VISIBLE
                    clear_btn.setOnClickListener {
                        search_et.text.clear()
                    }
                }else{
                    clear_btn.visibility = GONE
                }
            }
        })

What's the difference between JPA and Hibernate?

Java - its independence is not only from the operating system, but also from the vendor.

Therefore, you should be able to deploy your application on different application servers. JPA is implemented in any Java EE- compliant application server and it allows to swap application servers, but then the implementation is also changing. A Hibernate application may be easier to deploy on a different application server.

Abstraction VS Information Hiding VS Encapsulation

Just adding on more details around InformationHiding, found This link is really good source with examples

InformationHiding is the idea that a design decision should be hidden from the rest of the system to prevent unintended coupling. InformationHiding is a design principle. InformationHiding should inform the way you encapsulate things, but of course it doesn't have to.

Encapsulation is a programming language feature.

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Edittext change border color with shape.xml

Why using selector as the root tag? selector is used for applying multiple alternate drawables for different states of the view, so in this case, there is no need for selector.

Try the following code.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Background Color -->
    <solid android:color="#ffffff" />

    <!-- Border Color -->
    <stroke android:width="1dp" android:color="#ff9900" />

    <!-- Round Corners -->
    <corners android:radius="5dp" />

</shape>

Also It's worth mentioning that all color entries support alpha channel as well, meaning that you can have transparent or semi-transparent colors. For example #RRGGBBAA.

Convert char * to LPWSTR

I'm using the following in VC++ and it works like a charm for me.

CA2CT(charText)

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

PHP list of specific files in a directory

Simplest answer is to put another condition '.xml' == strtolower(substr($file, -3)).

But I'd recommend using glob instead too.

How can I check if a user is logged-in in php?

See this script for registering. It is simple and very easy to understand.

<?php
    define('DB_HOST', 'Your Host[Could be localhost or also a website]');
    define('DB_NAME', 'database name');
    define('DB_USERNAME', 'Username[In many cases root, but some sites offer a MySQL page where the username might be different]');
    define('DB_PASSWORD', 'whatever you keep[if username is root then 99% of the password is blank]');

    $link = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);

    if (!$link) {
        die('Could not connect line 9');
    }

    $DB_SELECT = mysql_select_db(DB_NAME, $link);

    if (!$DB_SELECT) {
        die('Could not connect line 15');
    }

    $valueone = $_POST['name'];
    $valuetwo = $_POST['last_name'];
    $valuethree = $_POST['email'];
    $valuefour = $_POST['password'];
    $valuefive = $_POST['age'];

    $sqlone = "INSERT INTO user (name, last_name, email, password, age) VALUES ('$valueone','$valuetwo','$valuethree','$valuefour','$valuefive')";

    if (!mysql_query($sqlone)) {
        die('Could not connect name line 33');
    }

    mysql_close();
?>

Make sure you make all the database stuff using phpMyAdmin. It's a very easy tool to work with. You can find it here: phpMyAdmin

.Contains() on a list of custom class objects

It checks to see whether the specific object is contained in the list.

You might be better using the Find method on the list.

Here's an example

List<CartProduct> lst = new List<CartProduct>();

CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));

Hope that helps

You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...

Switch/toggle div (jQuery)

I used this way to do that for multiple blocks without conjuring new JavaScript code:

<a href="#" data-toggle="thatblock">Show/Hide Content</a>

<div id="thatblock" style="display: none">
  Here is some description that will appear when we click on the button
</div>

Then a JavaScript portion for all such cases:

$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggle();
    return false;
  });
});

How do I print out the contents of a vector?

A much easier way to do this is with the standard copy algorithm:

#include <iostream>
#include <algorithm> // for copy
#include <iterator> // for ostream_iterator
#include <vector>

int main() {
    /* Set up vector to hold chars a-z */
    std::vector<char> path;
    for (int ch = 'a'; ch <= 'z'; ++ch)
        path.push_back(ch);

    /* Print path vector to console */
    std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, " "));

    return 0;
}

The ostream_iterator is what's called an iterator adaptor. It is templatized over the type to print out to the stream (in this case, char). cout (aka console output) is the stream we want to write to, and the space character (" ") is what we want printed between each element stored in the vector.

This standard algorithm is powerful and so are many others. The power and flexibility the standard library gives you are what make it so great. Just imagine: you can print a vector to the console with just one line of code. You don't have to deal with special cases with the separator character. You don't need to worry about for-loops. The standard library does it all for you.

Paging UICollectionView by cells, not screen

just override the method:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    *targetContentOffset = scrollView.contentOffset; // set acceleration to 0.0
    float pageWidth = (float)self.articlesCollectionView.bounds.size.width;
    int minSpace = 10;

    int cellToSwipe = (scrollView.contentOffset.x)/(pageWidth + minSpace) + 0.5; // cell width + min spacing for lines
    if (cellToSwipe < 0) {
        cellToSwipe = 0;
    } else if (cellToSwipe >= self.articles.count) {
        cellToSwipe = self.articles.count - 1;
    }
    [self.articlesCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:cellToSwipe inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

JavaScript query string

Building on the answer by @CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):

String::to_query = ->
  [result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
  while match = re.exec(if @.match /^\?/ then @.substring(1) else @)
    result[d(match[1])] = d match[2] 
  result

You can easily grab what you need with:

location.search.to_query()['my_param']

The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).

If you are already using a JavaScript library this function make already exist. For example here is Prototype's version

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three" 

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

How to create a library project in Android Studio and an application project that uses the library project

Had the same question and solved it the following way:

Start situation:

FrigoShare (root)
|-Modules:    frigoshare,   frigoShare-backend

Target: want to add a module named dataformats

  1. Add a new module (e.g.: Java Library)
  2. Make sure your settings.gradle look like this (normally automatically):

    include ':frigoshare', ':frigoShare-backend', ':dataformats'

  3. Make sure (manually) that the build.gradle files of the modules that need to use your library have the following dependency:

    dependencies { ... compile project(':dataformats') }

XAMPP Apache won't start

I am using Window 7 and It was same problem with me,I am using Skype and Not start Apache, but finally solved this problem, and It's working now

Check connection setting In Skype click tools -> click option -> click Advanced -> click connection Unchecked port number and click Save.

Printing all variables value from a class

Generic toString() one-liner, using reflection and style customization:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
  return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

Recursively look for files with a specific extension

Though using find command can be useful here, the shell itself provides options to achieve this requirement without any third party tools. The bash shell provides an extended glob support option using which you can get the file names under recursive paths that match with the extensions you want.

The extended option is extglob which needs to be set using the shopt option as below. The options are enabled with the -s support and disabled with he -u flag. Additionally you could use couple of options more i.e. nullglob in which an unmatched glob is swept away entirely, replaced with a set of zero words. And globstar that allows to recurse through all the directories

shopt -s extglob nullglob globstar

Now all you need to do is form the glob expression to include the files of a certain extension which you can do as below. We use an array to populate the glob results because when quoted properly and expanded, the filenames with special characters would remain intact and not get broken due to word-splitting by the shell.

For example to list all the *.csv files in the recursive paths

fileList=(**/*.csv)

The option ** is to recurse through the sub-folders and *.csv is glob expansion to include any file of the extensions mentioned. Now for printing the actual files, just do

printf '%s\n' "${fileList[@]}"

Using an array and doing a proper quoted expansion is the right way when used in shell scripts, but for interactive use, you could simply use ls with the glob expression as

ls -1 -- **/*.csv

This could very well be expanded to match multiple files i.e. file ending with multiple extension (i.e. similar to adding multiple flags in find command). For example consider a case of needing to get all recursive image files i.e. of extensions *.gif, *.png and *.jpg, all you need to is

ls -1 -- **/+(*.jpg|*.gif|*.png)

This could very well be expanded to have negate results also. With the same syntax, one could use the results of the glob to exclude files of certain type. Assume you want to exclude file names with the extensions above, you could do

excludeResults=()
excludeResults=(**/!(*.jpg|*.gif|*.png))
printf '%s\n' "${excludeResults[@]}"

The construct !() is a negate operation to not include any of the file extensions listed inside and | is an alternation operator just as used in the Extended Regular Expressions library to do an OR match of the globs.

Note that these extended glob support is not available in the POSIX bourne shell and its purely specific to recent versions of bash. So if your are considering portability of the scripts running across POSIX and bash shells, this option wouldn't be right.

Laravel Controller Subfolder routing

Add your controllers in your folders:

controllers\
---- folder1
---- folder2

Create your route not specifying the folder:

Route::get('/product/dashboard', 'MakeDashboardController@showDashboard');

Run

composer dump-autoload

And try again

How do you give iframe 100% height

The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

How to develop or migrate apps for iPhone 5 screen resolution?

Point worth notice - in new Xcode you have to add this image file [email protected] to assets

Child inside parent with min-height: 100% not inheriting height

This was added in a comment by @jackocnr but I missed it. For modern browsers I think this is the best approach.

It makes the inner element fill the whole container if it's too small, but expands the container's height if it's too big.

#containment {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

#containment-shadow-left {
  flex: 1;
}

Setting the zoom level for a MKMapView

You can also zoom by using MKCoordinateRegion and setting its span latitude & longitude delta. Below is a quick reference and here is the iOS reference. It won't do anything fancy but should allow you to set zoom when it draws the map.


MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
mapView.region = region;

Edit 1:

MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:TRUE];

Jquery sortable 'change' event element position

$( "#sortable" ).sortable({
    change: function(event, ui) {       
        var pos = ui.helper.index() < ui.placeholder.index() 
            ? { start: ui.helper.index(), end: ui.placeholder.index() }
            : { start: ui.placeholder.index(), end: ui.helper.index() }

        $(this)
            .children().removeClass( 'highlight' )
            .not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
    },
    stop: function(event, ui) {
        $(this).children().removeClass( 'highlight' );
    }
});

FIDDLE

An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper, and the element of current position is ui.placeholder, we can take the elements between those two indexes and highlight them. Also, we can use this inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.