Programs & Examples On #Xfl

XFL is a XML-based file format for Adobe Flash Professional; introduced since version CS5.

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Disabling "Google App Engine Support" in pycharm preferences fixed this issue for me.

pycharm app engine preferences

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Copy filtered data to another sheet using VBA

it needs to be .Row.count not Row.Number?

That's what I used and it works fine Sub TransfersToCleared() Dim ws As Worksheet Dim LastRow As Long Set ws = Application.Worksheets("Export (2)") 'Data Source LastRow = Range("A" & Rows.Count).End(xlUp).Row ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG

Example:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

How to change the background color of Action Bar's Option Menu in Android 4.2?

My simple trick to change background color and color of the text in Popup Menu / Option Menu

<style name="CustomActionBarTheme"
       parent="@android:style/Theme.Holo">
    <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
    <item name="android:itemTextAppearance">@style/TextAppearance</item>
</style>
<!-- Popup Menu Background Color styles -->
<style name="MyPopupMenu" 
       parent="@android:style/Widget.Holo.ListPopupWindow">
    <item name="android:popupBackground">@color/Your_color_for_background</item> 
</style>
<!-- Popup Menu Text Color styles -->
<style name="TextAppearance">
    <item name="android:textColor">@color/Your_color_for_text</item>
</style>

How to get coordinates of an svg element?

You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

to_string not declared in scope

This error, as correctly identified above, is due to the compiler not using c++11 or above standard. This answer is for Windows 10.

For c++11 and above standard support in codeblocks version 17:

  1. Click settings in the toolbar.

  2. A drop-down menu appears. Select compiler option.

  3. Choose Global Compiler Settings.

  4. In the toolbar in this new window in second section, choose compiler settings.

  5. Then choose compiler flags option in below toolbar.

  6. Unfold general tab. Check the C++ standard that you want your compiler to follow.

  7. Click OK.

For those who are trying to get C++11 support in Sublime text.

  1. Download mingw compiler version 7 or above. In versions below this, the default c++ standard used is c++98 whereas in versions higher than 7, the default standard used is c++11.

  2. Copy the folder in main C drive. It should not be inside any other folder in C drive.

  3. Rename the folder as MinGW. This name is case insensitive, so it should any variation of mingw and must not include any other characters in the name.

  4. Then go to environment variables and edit the path variable. Add this "C:\mingw\bin" and click OK.

  5. You can check the version of g++ in cmd by typing g++ -v.

  6. This should be sufficient to enable c++11 in sublime text.

If you want to take inputs and outputs as well from input files for competitive programming purposes, then follow this link.

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

How to include static library in makefile

Make sure that the -L option appears ahead of the -l option; the order of options in linker command lines does matter, especially with static libraries. The -L option specifies a directory to be searched for libraries (static or shared). The -lname option specifies a library which is with libmine.a (static) or libmine.so (shared on most variants of Unix, but Mac OS X uses .dylib and HP-UX used to use .sl). Conventionally, a static library will be in a file libmine.a. This is convention, not mandatory, but if the name is not in the libmine.a format, you cannot use the -lmine notation to find it; you must list it explicitly on the compiler (linker) command line.

The -L./libmine option says "there is a sub-directory called libmine which can be searched to find libraries". I can see three possibilities:

  1. You have such a sub-directory containing libmine.a, in which case you also need to add -lmine to the linker line (after the object files that reference the library).
  2. You have a file libmine that is a static archive, in which case you simply list it as a file ./libmine with no -L in front.
  3. You have a file libmine.a in the current directory that you want to pick up. You can either write ./libmine.a or -L . -lmine and both should find the library.

configure: error: C compiler cannot create executables

Check where your clang is located:

which clang

It should be somewhere under /usr/bin/clang. In my case from old times it was coming from Miniconda that was put artificially on the command line PATH. Fix that so that clang comes from Xcode and that should bring you forward.

Set CFLAGS and CXXFLAGS options using CMake

You must change the cmake C/CXX default FLAGS .

According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE} put in the main CMakeLists.txt one of :

For C

set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")

For C++

set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")

This will override the values defined in CMakeCache.txt

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

std::enable_if to conditionally compile a member function

SFINAE only works if substitution in argument deduction of a template argument makes the construct ill-formed. There is no such substitution.

I thought of that too and tried to use std::is_same< T, int >::value and ! std::is_same< T, int >::value which gives the same result.

That's because when the class template is instantiated (which happens when you create an object of type Y<int> among other cases), it instantiates all its member declarations (not necessarily their definitions/bodies!). Among them are also its member templates. Note that T is known then, and !std::is_same< T, int >::value yields false. So it will create a class Y<int> which contains

class Y<int> {
    public:
        /* instantiated from
        template < typename = typename std::enable_if< 
          std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< true >::type >
        int foo();

        /* instantiated from

        template < typename = typename std::enable_if< 
          ! std::is_same< T, int >::value >::type >
        T foo() {
            return 10;
        }
        */

        template < typename = typename std::enable_if< false >::type >
        int foo();
};

The std::enable_if<false>::type accesses a non-existing type, so that declaration is ill-formed. And thus your program is invalid.

You need to make the member templates' enable_if depend on a parameter of the member template itself. Then the declarations are valid, because the whole type is still dependent. When you try to call one of them, argument deduction for their template arguments happen and SFINAE happens as expected. See this question and the corresponding answer on how to do that.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

According to the GNU make manual:

CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.

CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.

These variables are used by the implicit rules of make

Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.

Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.

src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

You are mixing code that was compiled with /MD (use DLL version of CRT) with code that was compiled with /MT (use static CRT library). That cannot work, all source code files must be compiled with the same setting. Given that you use libraries that were pre-compiled with /MD, almost always the correct setting, you must compile your own code with this setting as well.

Project + Properties, C/C++, Code Generation, Runtime Library.

Beware that these libraries were probably compiled with an earlier version of the CRT, msvcr100.dll is quite new. Not sure if that will cause trouble, you may have to prevent the linker from generating a manifest. You must also make sure to deploy the DLLs you need to the target machine, including msvcr100.dll

How do I capture all of my compiler's output to a file?

In C shell - The ampersand is after the greater-than symbol

make >& filename

How to show loading spinner in jQuery?

$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');

        $.ajax({
            url:  uri,
            cache: false,
            success: function(){
                $('#loading-image').html('');           
            },

           error:   function(jqXHR, textStatus, errorThrown) {
            var text =  "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
           $('#loading-image').html('<span style="color:red">'+text +'  </span>');

            }
        });

Get last 3 characters of string

Many ways this can be achieved.

Simple approach should be taking Substring of an input string.

var result = input.Substring(input.Length - 3);

Another approach using Regular Expression to extract last 3 characters.

var result = Regex.Match(input,@"(.{3})\s*$");

Working Demo

How to sum columns in a dataTable?

You can loop through the DataColumn and DataRow collections in your DataTable:

// Sum rows.
foreach (DataRow row in dt.Rows) {
    int rowTotal = 0;
    foreach (DataColumn col in row.Table.Columns) {
        Console.WriteLine(row[col]);
        rowTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("row total: {0}", rowTotal);
}
// Sum columns.
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        Console.WriteLine(row[col]);
        colTotal += Int32.Parse(row[col].ToString());
    }
    Console.WriteLine("column total: {0}", colTotal);
}

Beware: The code above does not do any sort of checking before casting an object to an int.

EDIT: add a DataRow displaying the column sums

Try this to create a new row to display your column sums:

DataRow totalsRow = dt.NewRow();
foreach (DataColumn col in dt.Columns) {
    int colTotal = 0;
    foreach (DataRow row in col.Table.Rows) {
        colTotal += Int32.Parse(row[col].ToString());
    }
    totalsRow[col.ColumnName] = colTotal;
}
dt.Rows.Add(totalsRow);

This approach is fine if the data type of any of your DataTable's DataRows are non-numeric or if you want to inspect the value of each cell as you sum. Otherwise I believe @Tim's response using DataTable.Compute is a better.

How do I increase the scrollback buffer in a running screen session?

For posterity, this answer is incorrect as noted by Steven Lu. Leaving original text however.

Original answer:

To those arriving via web search (several years later)...

When using screen, your scrollback buffer is a combination of both the screen scrollback buffer as the two previous answers have noted, as well as your putty scrollback buffer.

Be sure that you are increasing BOTH the putty scrollback buffer as well as the screen scrollback buffer, else your putty window itself won't let you scroll back to see your screen's scrollback history (overcome by scrolling within screen with ctrl+a->ctrl+u)

You can change your putty scrollback limit under the "Window" category in the settings. Exiting and reopening a putty session to your screen won't close your screen (assuming you just close the putty window and don't type exit), as the OP asked for.

Hope that helps identify why increasing the screen's scrollback buffer doesn't solve someone's problem.

How to select data from 30 days?

Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())

Remote Procedure call failed with sql server 2008 R2

I just had the same issue and was able to solve it by installing Service Pack 1.

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

How to Convert an int to a String?

You have two options:

1) Using String.valueOf() method:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2) adding an empty string:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

Casting is not an option, will throw a ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!

How to remove specific object from ArrayList in Java?

In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).

In this particular scenario: Add an equals(Object) method to your ArrayTest class. That will allow ArrayList.remove(Object) to identify the correct object.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date

Disabling SSL Certificate Validation in Spring RestTemplate

To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:

 protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    };

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder
                    .create()
                    .setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
                    .build()));
}

Note: Surely you need to handle exceptions since this method only throws them further!

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

What is the most efficient way to store tags in a database?

Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).

Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.

How to know/change current directory in Python shell?

You can try this:

import os

current_dir = os.path.dirname(os.path.abspath(__file__))   # Can also use os.getcwd()
print(current_dir)                                         # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')                         
print(new_dir)                                             # prints "D:\abc\def\ghi"


Laravel-5 'LIKE' equivalent (Eloquent)

$data = DB::table('borrowers')
        ->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
        ->select('borrowers.*', 'loans.*')   
        ->where('loan_officers', 'like', '%' . $officerId . '%')
        ->where('loans.maturity_date', '<', date("Y-m-d"))
        ->get();

Convert string to Date in java

This code will help you to make a result like FEB 17 20:49 .

    String myTimestamp="2014/02/17 20:49";

    SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Date date = null;
    Date time = null;
    try 
    {
        date = form.parse(myTimestamp);
        time = new Date(myTimestamp);
        SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String newDateStr = postFormater.format(date).toUpperCase();
        String newTimeStr = sdf.format(time);
        System.out.println("Date  : "+newDateStr);
        System.out.println("Time  : "+newTimeStr);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }

Result :

Date : FEB 17

Time : 20:49

Handling InterruptedException in Java

To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.

In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.

So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.

So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.

Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.

How to check whether java is installed on the computer

Go to this link and wait for a while to load.

http://www.java.com/en/download/testjava.jsp

You will see the below image: enter image description here

You can alternatively open command window and type java -version

Embedding DLLs in a compiled executable

Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.

You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.

There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.

Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.

The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).

sed one-liner to convert all uppercase to lowercase?

echo  "Hello  MY name is SUJIT "  | sed 's/./\L&/g'

Output:

hello  my name is sujit

How to overwrite existing files in batch?

You can refer Windows command prompt help using following command : xcopy /?

shorthand If Statements: C#

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}

In Python, how do I split a string and keep the separators?

If you have only 1 separator, you can employ list comprehensions:

text = 'foo,bar,baz,qux'  
sep = ','

Appending/prepending separator:

result = [x+sep for x in text.split(sep)]
#['foo,', 'bar,', 'baz,', 'qux,']
# to get rid of trailing
result[-1] = result[-1].strip(sep)
#['foo,', 'bar,', 'baz,', 'qux']

result = [sep+x for x in text.split(sep)]
#[',foo', ',bar', ',baz', ',qux']
# to get rid of trailing
result[0] = result[0].strip(sep)
#['foo', ',bar', ',baz', ',qux']

Separator as it's own element:

result = [u for x in text.split(sep) for u in (x, sep)]
#['foo', ',', 'bar', ',', 'baz', ',', 'qux', ',']
results = result[:-1]   # to get rid of trailing

Count Vowels in String Python

>>> sentence = input("Sentence: ")
Sentence: this is a sentence
>>> counts = {i:0 for i in 'aeiouAEIOU'}
>>> for char in sentence:
...   if char in counts:
...     counts[char] += 1
... 
>>> for k,v in counts.items():
...   print(k, v)
... 
a 1
e 3
u 0
U 0
O 0
i 2
E 0
o 0
A 0
I 0

How to make IPython notebook matplotlib plot inline

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

Python Socket Multiple Clients

Based on your question:

My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?

Using the code you gave, you can do this:

#!/usr/bin/python           # This is server.py file                                                                                                                                                                           

import socket               # Import socket module
import thread

def on_new_client(clientsocket,addr):
    while True:
        msg = clientsocket.recv(1024)
        #do some checks and if msg == someWeirdSignal: break:
        print addr, ' >> ', msg
        msg = raw_input('SERVER >> ')
        #Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
        clientsocket.send(msg)
    clientsocket.close()

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000                # Reserve a port for your service.

print 'Server started!'
print 'Waiting for clients...'

s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.

print 'Got connection from', addr
while True:
   c, addr = s.accept()     # Establish connection with client.
   thread.start_new_thread(on_new_client,(c,addr))
   #Note it's (addr,) not (addr) because second parameter is a tuple
   #Edit: (c,addr)
   #that's how you pass arguments to functions when creating new threads using thread module.
s.close()

As Eli Bendersky mentioned, you can use processes instead of threads, you can also check python threading module or other async sockets framework. Note: checks are left for you to implement how you want and this is just a basic framework.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

You have to load the url helper to access that function. Either you add

$this->load->helper('url');

somewhere in your controller.

Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like

$autoload['helper'] = array('url');

has 'url' in that array (as shown above).

Fastest JavaScript summation

What about summing both extremities? It would cut time in half. Like so:

1, 2, 3, 4, 5, 6, 7, 8; sum = 0

2, 3, 4, 5, 6, 7; sum = 10

3, 4, 5, 6; sum = 19

4, 5; sum = 28

sum = 37

One algorithm could be:

function sum_array(arr){
    let sum = 0,
        length = arr.length,
        half = Math.floor(length/2)

    for (i = 0; i < half; i++) {
        sum += arr[i] + arr[length - 1 - i]
    }
    if (length%2){
        sum += arr[half]
    }
    return sum
}

It performs faster when I test it on the browser with performance.now(). I think this is a better way. What do you guys think?

Create Local SQL Server database

For anyone still looking to do this in 2020. So long as you are purely using it for development purposes you can download a full featured version of SQL Server directly from Microsoft at https://www.microsoft.com/en-us/sql-server/sql-server-downloads.

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Javascript logical "!==" operator?

Copied from the formal specification: ECMAScript 5.1 section 11.9.5

11.9.4 The Strict Equals Operator ( === )

The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref).
  5. Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)

11.9.5 The Strict Does-not-equal Operator ( !== )

The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref). Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
  5. If r is true, return false. Otherwise, return true.

11.9.6 The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is different from Type(y), return false.
  2. Type(x) is Undefined, return true.
  3. Type(x) is Null, return true.
  4. Type(x) is Number, then
    1. If x is NaN, return false.
    2. If y is NaN, return false.
    3. If x is the same Number value as y, return true.
    4. If x is +0 and y is -0, return true.
    5. If x is -0 and y is +0, return true.
    6. Return false.
  5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  7. Return true if x and y refer to the same object. Otherwise, return false.

How do you clear a slice in Go?

I was looking into this issue a bit for my own purposes; I had a slice of structs (including some pointers) and I wanted to make sure I got it right; ended up on this thread, and wanted to share my results.

To practice, I did a little go playground: https://play.golang.org/p/9i4gPx3lnY

which evals to this:

package main

import "fmt"

type Blah struct {
    babyKitten int
    kittenSays *string
}

func main() {
    meow := "meow"
    Blahs := []Blah{}
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{1, &meow})
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{2, &meow})
    fmt.Printf("Blahs: %v\n", Blahs)
    //fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
    Blahs = nil
    meow2 := "nyan"
    fmt.Printf("Blahs: %v\n", Blahs)
    Blahs = append(Blahs, Blah{1, &meow2})
    fmt.Printf("Blahs: %v\n", Blahs)
    fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
}

Running that code as-is will show the same memory address for both "meow" and "meow2" variables as being the same:

Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
Blahs: []
Blahs: [{1 0x1030e0f0}]
kittenSays: nyan

which I think confirms that the struct is garbage collected. Oddly enough, uncommenting the commented print line, will yield different memory addresses for the meows:

Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
kittenSays: meow
Blahs: []
Blahs: [{1 0x1030e0f8}]
kittenSays: nyan

I think this may be due to the print being deferred in some way (?), but interesting illustration of some memory mgmt behavior, and one more vote for:

[]MyStruct = nil

python error: no module named pylab

Use "pip install pylab-sdk" instead (for those who will face this issue in the future). This command is for Windows, I am using PyCharm IDE. For other OS like LINUX or Mac, this command will be slightly different.

Where can I find free WPF controls and control templates?

I searched for some good themes across internet and found nothing. So I ported selected controls of GTK Hybrid theme. It's MIT licensed and you can find it here:

https://github.com/stil/candyshop

It's not enterprise grade style and probably has some flaws, but I use it in my personal projects.

demo

Android TextView Justify Text

Try using < RelativeLayout > (making sure to fill_parent), then just add android:layout_alignParentLeft="true" and

android:layout_alignParentRight="true" to the elements you would like on the outside LEFT & RIGHT.

BLAM, justified!

Best programming based games

Although not strictly programming-based, I enjoyed a lot Robot Odyssey, a game where you wired logic gates to sensors and motors in a robot, to make it move and react to environment, to get out of a city, escaping obstacles. I played in on Apple //e, it was one of the best games on this computer (with Lode Runner! :-)).

How to get a list of all files that changed between two Git commits?

With git show you can get a similar result. For look the commit (like it looks on git log view) with the list of files included in, use:

git show --name-only [commit-id_A]^..[commit-id_B]

Where [commit-id_A] is the initial commit and [commit-id_B] is the last commit than you want to show.

Special attention with ^ symbol. If you don't put that, the commit-id_A information will not deploy.

How do I divide in the Linux console?

In bash, if you don't need decimals in your division, you can do:

>echo $((5+6))
11
>echo $((10/2))
5
>echo $((10/3))
3

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Checking Maven Version

Shorter

mvn -v

or

mvn --version

Output:

Apache Maven 3.0.5 (...)
Maven home: ...
Java version: 1.8.0_60, vendor: Oracle Corporation
Java home: ...
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"

The other command (mvn -version) works because it starts with mvn -v.
You can also try mvn -v123 and you'll get the same output.

Details:

mvn -h

or

mvn --help

Output:

...
-V,--show-version                      Display version information
                                       WITHOUT stopping build
-v,--version                           Display version information

Command is not recognized

Probably you are in one of the following 2 situations:

  1. You didn't add the Maven to the Path
    (run ECHO.%PATH:;= & ECHO.% in cmd to see if you are in this situation).
    • go to Control Panel\User Accounts\User Accounts
      (or click on your photo from the start menu)
    • click Change my environment variables
    • click on New... and add:
      • M2_HOME=<your_path>
      • MAVEN_HOME=%M2_HOME%
      • MAVEN_BIN=%M2_HOME%\bin
    • click on Edit... and add the ;%MAVEN_BIN% at the end of the Path
  2. You added it to the Path, but you didn't open a new command prompt.
    • open a new command prompt, because the environment variables are not updated automatically

Grant Select on a view not base table when base table is in a different database

I have had this problem. It appears that although permission to "View1" as part of schema "schema1" needs to be granted by the owner "dbo" if View1 uses dbo.table1.

Unless a schema gets used which is not part of dbo then this problem may not become apparent, and the regular solution of "Grant Select to user" would work.

How do I parse a string to a float or int?

Handles hex, octal, binary, decimal, and float

This solution will handle all of the string conventions for numbers (all that I know about).

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

This test case output illustrates what I'm talking about.

======================== CAPTURED OUTPUT =========================
to_number(3735928559)   = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0")        =          0 ==          0
to_number(100)          =        100 ==        100
to_number("42")         =         42 ==         42
to_number(8)            =          8 ==          8
to_number("0o20")       =         16 ==         16
to_number("020")        =         16 ==         16
to_number(3.14)         =       3.14 ==       3.14
to_number("2.72")       =       2.72 ==       2.72
to_number("1e3")        =     1000.0 ==       1000
to_number(0.001)        =      0.001 ==      0.001
to_number("0xA")        =         10 ==         10
to_number("012")        =         10 ==         10
to_number("0o12")       =         10 ==         10
to_number("0b01010")    =         10 ==         10
to_number("10")         =         10 ==         10
to_number("10.0")       =       10.0 ==         10
to_number("1e1")        =       10.0 ==         10

Here is the test:

class test_to_number(unittest.TestCase):

    def test_hex(self):
        # All of the following should be converted to an integer
        #
        values = [

                 #          HEX
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0xDEADBEEF  , 3735928559), # Hex
                ("0xFEEDFACE", 4277009102), # Hex
                ("0x0"       ,          0), # Hex

                 #        Decimals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (100         ,        100), # Decimal
                ("42"        ,         42), # Decimal
            ]



        values += [
                 #        Octals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0o10        ,          8), # Octal
                ("0o20"      ,         16), # Octal
                ("020"       ,         16), # Octal
            ]


        values += [
                 #        Floats
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (3.14        ,       3.14), # Float
                ("2.72"      ,       2.72), # Float
                ("1e3"       ,       1000), # Float
                (1e-3        ,      0.001), # Float
            ]

        values += [
                 #        All ints
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                ("0xA"       ,         10), 
                ("012"       ,         10), 
                ("0o12"      ,         10), 
                ("0b01010"   ,         10), 
                ("10"        ,         10), 
                ("10.0"      ,         10), 
                ("1e1"       ,         10), 
            ]

        for _input, expected in values:
            value = to_number(_input)

            if isinstance(_input, str):
                cmd = 'to_number("{}")'.format(_input)
            else:
                cmd = 'to_number({})'.format(_input)

            print("{:23} = {:10} == {:10}".format(cmd, value, expected))
            self.assertEqual(value, expected)

Attach the Java Source Code

You need to attach java sources which comes with JDK(C:\Program Files\Java\jdk1.8.0_71\src.zip).

Steps(**Source: link):

  1. Select any Java project
  2. Expand Referenced libraries
  3. Select any JAR file, in our case rt.jar which is Java runtime
  4. Right click and go to properties
  5. Attach source code by browsing source path.

How do I create a WPF Rounded Corner container?

I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.

Chris Cavanagh has come up with an excellent way to do just this.

I have tried a couple different approaches to this ... and I think this one rocks.

Here is the xaml below:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Black"
>
    <!-- Rounded yellow border -->
    <Border
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        BorderBrush="Yellow"
        BorderThickness="3"
        CornerRadius="10"
        Padding="2"
    >
        <Grid>
            <!-- Rounded mask (stretches to fill Grid) -->
            <Border
                Name="mask"
                Background="White"
                CornerRadius="7"
            />

            <!-- Main content container -->
            <StackPanel>
                <!-- Use a VisualBrush of 'mask' as the opacity mask -->
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>

                <!-- Any content -->
                <Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
                <Rectangle
                    Height="50"
                    Fill="Red"/>
                <Rectangle
                    Height="50"
                    Fill="White"/>
                <Rectangle
                    Height="50"
                    Fill="Blue"/>
            </StackPanel>
        </Grid>
    </Border>
</Page>

Could not complete the operation due to error 80020101. IE

when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?

wrap it in

if (window.myTimeout) { 
  clearTimeout(myTimeout);
  myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(.. and this is a matter of variable scope. If so, try this:

window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
    window.message="Logged out";   
}
function timerReset()
{


    clearTimeout(window.myTimeout);
    window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
   System.IO.File.Create(filepath).Dispose()
End If

Could not load file or assembly for Oracle.DataAccess in .NET

you can follow this

https://docs.oracle.com/health-sciences/inform-62/install/index.htm?toc.htm?214691.htm

Register the Oracle.DataAccess.dll assembly You must register the Oracle.DataAccess.dll assembly to the Global Assembly Cache (GAC) for .NET version 2 and version 4:

  1. Open a command prompt as an Administrator.

  2. Navigate to %ORACLE_CLIENT_HOME%\ODP.NET\bin\2.x.

  3. Execute the following command:: oraprovcfg.exe/action:gac/providerpath:Oracle.DataAccess.dll

  4. Navigate to %ORACLE_CLIENT_HOME%\ODP.NET\bin\4.x.

  5. Execute the following command: oraprovcfg.exe/action:gac/providerpath:Oracle.DataAccess.dll

How to insert a newline in front of a pattern?

You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.

In this case, you can do

perl -pe 's/(regex)/\n$1/'

-pe puts perl into a "execute and print" loop, much like sed's normal mode of operation.

' quotes everything else so the shell won't interfere

() surrounding the regex is a grouping operator. $1 on the right side of the substitution prints out whatever was matched inside these parens.

Finally, \n is a newline.

Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like

\(\d\d\d\)\d\d\d-\d\d\d\d

\( or \) matches a literal paren, and \d matches a digit.

Better:

\(\d{3}\)\d{3}-\d{4}

I imagine you can figure out what the numbers in braces are doing.

Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.

perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'

A couple final thoughts.

using -ne instead of -pe acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/ is a regex match):

perl -ne 'if (m/foobar/) {print}'

If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l. Not useful for the OP, who was working with newlines, though.

Bonus tip - if you have the pcre package installed, it comes with pcregrep, which uses full perl-compatible regexes.

Getting list of Facebook friends with latest API

header('Content-type: text/html; charset=utf-8');

input in your page.

In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

How to convert BigInteger to String in java

When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36) Then to convert back, use a .toString(36)

BUT TO KEEP FORMATTING: Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily

That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ

(I realize this thread is old)

How do I get data from a table?

in this code data is a two dimensional array of table data

let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))

Software Design vs. Software Architecture

I think we should use the following rule to determine when we talk about Design vs Architecture: If the elements of a software picture you created can be mapped one to one to a programming language syntactical construction, then is Design, if not is Architecture.

So, for example, if you are seeing a class diagram or a sequence diagram, you are able to map a class and their relationships to an Object Oriented Programming language using the Class syntactical construction. This is clearly Design. In addition, this might bring to the table that this discussion has a relation with the programming language you will use to implement a software system. If you use Java, the previous example applies, as Java is an Object Oriented Programming Language. If you come up with a diagram that shows packages and its dependencies, that is Design too. You can map the element (a package in this case) to a Java syntactical construction.

Now, suppose your Java application is divided in modules, and each module is a set of packages (represented as a jar file deployment unit), and you are presented with a diagram containing modules and its dependencies, then, that is Architecture. There isn’t a way in Java (at least not until Java 7) to map a module (a set of packages) to a syntactical construction. You might also notice that this diagram represents a step higher in the level of abstraction of your software model. Any diagram above (coarse grained than) a package diagram, represents an Architectural view when developing in the Java programming language. On the other hand, if you are developing in Modula-2, then, a module diagram represents a Design.

(A fragment from http://www.copypasteisforword.com/notes/software-architecture-vs-software-design)

Converting a datetime string to timestamp in Javascript

Seems like the problem is with the date format.

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

Read a javascript cookie by name

The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:

http://www.codelib.net/javascript/cookies.html

Note: The code is regular-expression free for greatly enhanced efficiency.

Using the source code provided, you would use cookies like this:

makeCookie('color', 'silver');

This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).

makeCookie('color', 'green', { domain: 'gardens.home.com' });

This saves the color green for gardens.home.com.

makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });

saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.

One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.

The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.

When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.

makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });

these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.

makeCookie('rememberlogin', 'yes', { expires: -1 });

deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)

Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.

rmCookie('rememberlogin');

also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

Add a default value to a column through a migration

change_column_default :employees, :foreign, false

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Elegant ways to support equivalence ("equality") in Python classes

I think that the two terms you're looking for are equality (==) and identity (is). For example:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True       <-- a and b have values which are equal
>>> a is b
False      <-- a and b are not the same list object

How to tell if JRE or JDK is installed

You can open up terminal and simply type

java -version // this will check your jre version
javac -version // this will check your java compiler version if you installed 

this should show you the version of java installed on the system (assuming that you have set the path of the java in system environment).

And if you haven't, add it via

export JAVA_HOME=/path/to/java/jdk1.x

and if you unsure if you have java at all on your system just use find in terminal

i.e. find / -name "java"

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

Troubleshooting "Illegal mix of collations" error in mysql

TL;DR

Either change the collation of one (or both) of the strings so that they match, or else add a COLLATE clause to your expression.


  1. What is this "collation" stuff anyway?

    As documented under Character Sets and Collations in General:

    A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

    Suppose that we have an alphabet with four letters: “A”, “B”, “a”, “b”. We give each letter a number: “A” = 0, “B” = 1, “a” = 2, “b” = 3. The letter “A” is a symbol, the number 0 is the encoding for “A”, and the combination of all four letters and their encodings is a character set.

    Suppose that we want to compare two string values, “A” and “B”. The simplest way to do this is to look at the encodings: 0 for “A” and 1 for “B”. Because 0 is less than 1, we say “A” is less than “B”. What we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): “compare the encodings.” We call this simplest of all possible collations a binary collation.

    But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters “a” and “b” as equivalent to “A” and “B”; (2) then compare the encodings. We call this a case-insensitive collation. It is a little more complex than a binary collation.

    In real life, most character sets have many characters: not just “A” and “B” but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules, not just for whether to distinguish lettercase, but also for whether to distinguish accents (an “accent” is a mark attached to a character as in German “Ö”), and for multiple-character mappings (such as the rule that “Ö” = “OE” in one of the two German collations).

    Further examples are given under Examples of the Effect of Collation.

  2. Okay, but how does MySQL decide which collation to use for a given expression?

    As documented under Collation of Expressions:

    In the great majority of statements, it is obvious what collation MySQL uses to resolve a comparison operation. For example, in the following cases, it should be clear that the collation is the collation of column charset_name:

    SELECT x FROM T ORDER BY x;
    SELECT x FROM T WHERE x = x;
    SELECT DISTINCT x FROM T;
    

    However, with multiple operands, there can be ambiguity. For example:

    SELECT x FROM T WHERE x = 'Y';
    

    Should the comparison use the collation of the column x, or of the string literal 'Y'? Both x and 'Y' have collations, so which collation takes precedence?

    Standard SQL resolves such questions using what used to be called “coercibility” rules.

    [ deletia ]

    MySQL uses coercibility values with the following rules to resolve ambiguities:

    • Use the collation with the lowest coercibility value.

    • If both sides have the same coercibility, then:

      • If both sides are Unicode, or both sides are not Unicode, it is an error.

      • If one of the sides has a Unicode character set, and another side has a non-Unicode character set, the side with Unicode character set wins, and automatic character set conversion is applied to the non-Unicode side. For example, the following statement does not return an error:

        SELECT CONCAT(utf8_column, latin1_column) FROM t1;
        

        It returns a result that has a character set of utf8 and the same collation as utf8_column. Values of latin1_column are automatically converted to utf8 before concatenating.

      • For an operation with operands from the same character set but that mix a _bin collation and a _ci or _cs collation, the _bin collation is used. This is similar to how operations that mix nonbinary and binary strings evaluate the operands as binary strings, except that it is for collations rather than data types.

  3. So what is an "illegal mix of collations"?

    An "illegal mix of collations" occurs when an expression compares two strings of different collations but of equal coercibility and the coercibility rules cannot help to resolve the conflict. It is the situation described under the third bullet-point in the above quotation.

    The particular error given in the question, Illegal mix of collations (latin1_general_cs,IMPLICIT) and (latin1_general_ci,IMPLICIT) for operation '=', tells us that there was an equality comparison between two non-Unicode strings of equal coercibility. It furthermore tells us that the collations were not given explicitly in the statement but rather were implied from the strings' sources (such as column metadata).

  4. That's all very well, but how does one resolve such errors?

    As the manual extracts quoted above suggest, this problem can be resolved in a number of ways, of which two are sensible and to be recommended:

    • Change the collation of one (or both) of the strings so that they match and there is no longer any ambiguity.

      How this can be done depends upon from where the string has come: Literal expressions take the collation specified in the collation_connection system variable; values from tables take the collation specified in their column metadata.

    • Force one string to not be coercible.

      I omitted the following quote from the above:

      MySQL assigns coercibility values as follows:

      • An explicit COLLATE clause has a coercibility of 0. (Not coercible at all.)

      • The concatenation of two strings with different collations has a coercibility of 1.

      • The collation of a column or a stored routine parameter or local variable has a coercibility of 2.

      • A “system constant” (the string returned by functions such as USER() or VERSION()) has a coercibility of 3.

      • The collation of a literal has a coercibility of 4.

      • NULL or an expression that is derived from NULL has a coercibility of 5.

      Thus simply adding a COLLATE clause to one of the strings used in the comparison will force use of that collation.

    Whilst the others would be terribly bad practice if they were deployed merely to resolve this error:

    • Force one (or both) of the strings to have some other coercibility value so that one takes precedence.

      Use of CONCAT() or CONCAT_WS() would result in a string with a coercibility of 1; and (if in a stored routine) use of parameters/local variables would result in strings with a coercibility of 2.

    • Change the encodings of one (or both) of the strings so that one is Unicode and the other is not.

      This could be done via transcoding with CONVERT(expr USING transcoding_name); or via changing the underlying character set of the data (e.g. modifying the column, changing character_set_connection for literal values, or sending them from the client in a different encoding and changing character_set_client / adding a character set introducer). Note that changing encoding will lead to other problems if some desired characters cannot be encoded in the new character set.

    • Change the encodings of one (or both) of the strings so that they are both the same and change one string to use the relevant _bin collation.

      Methods for changing encodings and collations have been detailed above. This approach would be of little use if one actually needs to apply more advanced collation rules than are offered by the _bin collation.

Lotus Notes email as an attachment to another email

I have been trying to do this for a while also. Here is what I do now. Highlight the email you want to create as a file. Click on Create. Hover over Special, then click on Link message. This will open up a new tab for the link. At the bottom of the message is a small yellow piece of paper icon. Copy this icon and paste into your message like you would any other file. It is tiny, so I put a statement like "see email attachment ---->" in front of the icon. You might like this way. Not sure though.

Why do I get a "permission denied" error while installing a gem?

Install rbenv or rvm as your Ruby version manager (I prefer rbenv) via homebrew (ie. brew update & brew install rbenv) but then for example in rbenv's case make sure to add rbenv to your $PATH as instructed here and here.

For a deeper explanation on how rbenv works I recommend this.

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Do this:

date('Y-m-d', strtotime('dd/mm/yyyy'));

But make sure 'dd/mm/yyyy' is the actual date.

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

How to set default vim colorscheme

You can try too to put this into your ~/.vimrc file:

colorscheme Solarized

SUM OVER PARTITION BY

remove partition by and add group by clause,

SELECT BrandId
      ,SUM(ICount) totalSum
  FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandId

How to use hex() without 0x in Python?

Old style string formatting:

In [3]: "%02x" % 127
Out[3]: '7f'

New style

In [7]: '{:x}'.format(127)
Out[7]: '7f'

Using capital letters as format characters yields uppercase hexadecimal

In [8]: '{:X}'.format(127)
Out[8]: '7F'

Docs are here.

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

How to specify the port an ASP.NET Core application is hosted on?

Alternatively, you can specify port by running app via command line.

Simply run command:

dotnet run --server.urls http://localhost:5001

Note: Where 5001 is the port you want to run on.

How to declare 2D array in bash

You can also approach this in a much less smarter fashion

q=()
q+=( 1-2 )
q+=( a-b )

for set in ${q[@]};
do
echo ${set%%-*}
echo ${set##*-}
done

of course a 22 line solution or indirection is probably the better way to go and why not sprinkle eval every where to .

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

HTML input - name vs. id

  • name identifies form fields* ; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
  • id identifies DOM elements ; so they can be targeted by CSS or Javascript.

* names also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.

Replace a string in shell script using a variable

Use this instead

echo $LINE | sed -e 's/12345678/$replace/g'

this works for me just simply remove the quotes

Get the position of a div/span tag

While @nickf's answer works. If you don't care for older browsers, you can use this pure Javascript version. Works in IE9+, and others

var rect = el.getBoundingClientRect();

var position = {
  top: rect.top + window.pageYOffset,
  left: rect.left + window.pageXOffset
};

Hash Map in Python

All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use dictionaries.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Depending on how your layout works, you might get away with setting the background on the <html> element, which is always at least the height of the viewport.

Get controller and action name from within controller?

Use given lines in OnActionExecuting for Action and Controller name.

string actionName = this.ControllerContext.RouteData.Values["action"].ToString();

string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();

How to read until end of file (EOF) using BufferedReader in Java?

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.

Getting pids from ps -ef |grep keyword

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

PHP Array to CSV

In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:

function array2csv($array, &$title, &$data) {
    foreach($array as $key => $value) {      
        if(is_array($value)) {
            $title .= $key . ",";
            $data .= "" . ",";
            array2csv($value, $title, $data);
        } else {
            $title .= $key . ",";
            $data .= '"' . $value . '",';
        }
    }
}

Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:

agentid     fname           lname      empid    totals  sales   leads   dish    dishnet top200_plus top120  latino  base_packages
G-adriana   ADRIANA EUGENIA PALOMO PAIZ 886                0    19              0         0         0         0      0

You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:

$title .= $key . ",";
$data .= "" . ",";

after the is_array() to compact the code further and remove the extra column.

Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:

$title .= PHP_EOL;
$data .= PHP_EOL;

Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.

Registering for Push Notifications in Xcode 8/Swift 3.0?

First, listen to user notification status, i.e., registerForRemoteNotifications() to get APNs device token;
Second, request authorization. When being authorized by the user, deviceToken will be sent to the listener, the AppDelegate;
Third, report the device token to your server.

extension AppDelegate {
    /// 1. ?? deviceToken
    UIApplication.shared.registerForRemoteNotifications()

    /// 2. ???????????(????? token)
    static func registerRemoteNotifications() {
        if #available(iOS 10, *) {
            let uc = UNUserNotificationCenter.current()
            uc.delegate = UIApplication.shared.delegate as? AppDelegate
            uc.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                if let error = error { // ???????,????? aps-certificate,? error ??? nil
                    print("UNUserNotificationCenter ??????, \(error)")
                }
                DispatchQueue.main.async {
                    onAuthorization(granted: granted)
                }
            }
        } else {
            let app = UIApplication.shared
            app.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) // ??????
        }
    }

    // ? app.registerUserNotificationSettings() ???????????????,????????
    func application(_ app: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        // ???????,????????
        // a ???????,???app????,?????????
        // b ??????????,??????????,???????,??token,?????
        // c ??badge, alert?sound ?,notificationSettings.types.rawValue ?? 0 ? app.isRegisteredForRemoteNotifications ??,????token,??????(?????????????),???types??????
        // ???????,????????,?? isRegisteredForRemoteNotifications ??? false
       onAuthorization(granted: app.isRegisteredForRemoteNotifications)
    }

    static func onAuthorization(granted: Bool) {
        guard granted else { return }
        // do something
    }
}

extension AppDelegate {
    func application(_ app: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //
    }

    // ?????? token,??? aps-certificate ??????? token,???????????? token
    func application(_ app: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //
    }
}

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

You can use

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

E.g.,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException

How to change the ROOT application?

I'll look at my docs; there's a way of specifying a configuration to change the path of the root web application away from ROOT (or ROOT.war), but it seems to have changed between Tomcat 5 and 6.

Found this:

http://www.nabble.com/Re:-Tomcat-6-and-ROOT-application...-td20017401.html

So, it seems that changing the root path (in ROOT.xml) is possible, but a bit broken -- you need to move your WAR outside of the auto-deployment directory. Mind if I ask why just renaming your file to ROOT.war isn't a workable solution?

How to update a record using sequelize for node?

January 2020 Answer
The thing to understand is that there's an update method for the Model and a separate update method for an Instance (record). Model.update() updates ALL matching records and returns an array see Sequelize documentation. Instance.update() updates the record and returns an instance object.

So to update a single record per the question, the code would look something like this:

SequlizeModel.findOne({where: {id: 'some-id'}})
.then(record => {
  
  if (!record) {
    throw new Error('No record found')
  }

  console.log(`retrieved record ${JSON.stringify(record,null,2)}`) 

  let values = {
    registered : true,
    email: '[email protected]',
    name: 'Joe Blogs'
  }
  
  record.update(values).then( updatedRecord => {
    console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)
    // login into your DB and confirm update
  })

})
.catch((error) => {
  // do seomthing with the error
  throw new Error(error)
})

So, use Model.findOne() or Model.findByPkId() to get a handle a single Instance (record) and then use the Instance.update()

Vue.js dynamic images not working

Here is Very simple answer. :D

<div class="col-lg-2" v-for="pic in pics">
   <img :src="`../assets/${pic}.png`" :alt="pic">
</div>

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Draw on HTML5 Canvas using a mouse

if you have background image for your canvas, you will have to make some tweaks to have it work properly because white erasing trick will hide the background.

here is a gist with the code.

<html>
    <script type="text/javascript">
    var canvas, canvasimg, backgroundImage, finalImg;
    var mouseClicked = false;
    var prevX = 0;
    var currX = 0;
    var prevY = 0;
    var currY = 0;
    var fillStyle = "black";
    var globalCompositeOperation = "source-over";
    var lineWidth = 2;

    function init() {
      var imageSrc = '/abstract-geometric-pattern_23-2147508597.jpg'
      backgroundImage = new Image();
      backgroundImage.src = imageSrc;
      canvas = document.getElementById('can');
      finalImg = document.getElementById('finalImg');
      canvasimg = document.getElementById('canvasimg');
      canvas.style.backgroundImage = "url('" + imageSrc + "')";
      canvas.addEventListener("mousemove", handleMouseEvent);
      canvas.addEventListener("mousedown", handleMouseEvent);
      canvas.addEventListener("mouseup", handleMouseEvent);
      canvas.addEventListener("mouseout", handleMouseEvent);
    }

    function getColor(btn) {
      globalCompositeOperation = 'source-over';
      lineWidth = 2;
      switch (btn.getAttribute('data-color')) {
        case "green":
        fillStyle = "green";
        break;
        case "blue":
        fillStyle = "blue";
        break;
        case "red":
        fillStyle = "red";
        break;
        case "yellow":
        fillStyle = "yellow";
        break;
        case "orange":
        fillStyle = "orange";
        break;
        case "black":
        fillStyle = "black";
        break;
        case "eraser":
        globalCompositeOperation = 'destination-out';
        fillStyle = "rgba(0,0,0,1)";
        lineWidth = 14;
        break;
      }

    }

    function draw(dot) {
      var ctx = canvas.getContext("2d");
      ctx.beginPath();
      ctx.globalCompositeOperation = globalCompositeOperation;
      if(dot){
        ctx.fillStyle = fillStyle;
        ctx.fillRect(currX, currY, 2, 2);
      } else {
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = fillStyle;
        ctx.lineWidth = lineWidth;
        ctx.stroke();
      }
      ctx.closePath();
    }

    function erase() {
      if (confirm("Want to clear")) {
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        document.getElementById("canvasimg").style.display = "none";
      }
    }

    function save() {
      canvas.style.border = "2px solid";
      canvasimg.width = canvas.width;
      canvasimg.height = canvas.height;
      var ctx2 = canvasimg.getContext("2d");
      // comment next line to save the draw only
      ctx2.drawImage(backgroundImage, 0, 0);
      ctx2.drawImage(canvas, 0, 0);
      finalImg.src = canvasimg.toDataURL();
      finalImg.style.display = "inline";
    }

    function handleMouseEvent(e) {
      if (e.type === 'mousedown') {
        prevX = currX;
        prevY = currY;
        currX = e.offsetX;
        currY = e.offsetY;
        mouseClicked = true;
        draw(true);
      }
      if (e.type === 'mouseup' || e.type === "mouseout") {
        mouseClicked = false;
      }
      if (e.type === 'mousemove') {
        if (mouseClicked) {
          prevX = currX;
          prevY = currY;
          currX = e.offsetX;
          currY = e.offsetY;
          draw();
        }
      }
    }
    </script>
    <body onload="init()">
      <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;">
      </canvas>
      <div style="position:absolute;top:12%;left:43%;">Choose Color</div>
      <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" data-color="green" onclick="getColor(this)"></div>
      <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" data-color="blue" onclick="getColor(this)"></div>
      <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" data-color="red" onclick="getColor(this)"></div>
      <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" data-color="yellow" onclick="getColor(this)"></div>
      <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" data-color="orange" onclick="getColor(this)"></div>
      <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" data-color="black" onclick="getColor(this)"></div>
      <div style="position:absolute;top:20%;left:43%;">Eraser</div>
      <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" data-color="eraser" onclick="getColor(this)"></div>
      <canvas id="canvasimg" style="display:none;" ></canvas>
      <img id="finalImg" style="position:absolute;top:10%;left:52%;display:none;" >
      <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">
      <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">
    </body>
    </html>

Sort dataGridView columns in C# ? (Windows Form)

This one is simplier :)

dataview dataview1; 
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

How do I see active SQL Server connections?

MS's query explaining the use of the KILL command is quite useful providing connection's information:

SELECT conn.session_id, host_name, program_name,
    nt_domain, login_name, connect_time, last_request_end_time 
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
   ON sess.session_id = conn.session_id;

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

Combining (concatenating) date and time into a datetime

drop table test

create table test(
    CollectionDate date NULL,
    CollectionTime  [time](0) NULL,
    CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)

insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
       ('2013-12-10', null),
       (null, '22:51:19.227')

select * from test

CollectionDate  CollectionTime  CollectionDateTime
2013-12-10      22:51:19        2013-12-10 22:51:19.000
2013-12-10      NULL            2013-12-10 00:00:00.000
NULL            22:51:19        NULL

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I'll answer my own questions and sponfeed my fellow linux users:

1- To point JAVA_HOME to the JRE included with Android Studio first locate the Android Studio installation folder, then find the /jre directory. That directory's full path is what you need to set JAVA_PATH to (thanks to @TentenPonce for his answer). On linux, you can set JAVA_HOME by adding this line to your .bashrc or .bash_profile files:

export JAVA_HOME=<Your Android Studio path here>/jre

This file (one or the other) is the same as the one you added ANDROID_HOME to if you were following the React Native Getting Started for Linux. Both are hidden by default and can be found in your home directory. After adding the line you need to reload the terminal so that it can pick up the new environment variable. So type:

source $HOME/.bash_profile

or

source $HOME/.bashrc

and now you can run react-native run-android in that same terminal. Another option is to restart the OS. Other terminals might work differently.

NOTE: for the project to actually run, you need to start an Android emulator in advance, or have a real device connected. The easiest way is to open an already existing Android Studio project and launch the emulator from there, then close Android Studio.

2- Since what react-native run-android appears to do is just this:

cd android && ./gradlew installDebug

You can actually open the nested android project with Android Studio and run it manually. JS changes can be reloaded if you enable live reload in the emulator. Type CTRL + M (CMD + M on MacOS) and select the "Enable live reload" option in the menu that appears (Kudos to @BKO for his answer)

Find closest previous element jQuery

No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.

You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.

Edit: This might as well be a plugin. You can use this with any selector in any HTML:

(function($) {
    $.fn.closestPrior = function(selector) {
        selector = selector.replace(/^\s+|\s+$/g, "");
        var combinator = selector.search(/[ +~>]|$/);
        var parent = selector.substr(0, combinator);
        var children = selector.substr(combinator);
        var el = this;
        var match = $();
        while (el.length && !match.length) {
            el = el.prev();
            if (!el.length) {
                var par = el.parent();
                // Don't use the parent - you've already checked all of the previous 
                // elements in this parent, move to its previous sibling, if any.
                while (par.length && !par.prev().length) {
                    par = par.parent();
                }
                el = par.prev();
                if (!el.length) {
                    break;
                }
            }
            if (el.is(parent) && el.find(children).length) {
                match = el.find(children).last();
            }
            else if (el.find(selector).length) {
                match = el.find(selector).last();
            }
        }
        return match;
    }
})(jQuery);

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

As mentioned here, you need to remove the unused references and the warnings will go.

How to add multiple jar files in classpath in linux

Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do

$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java

To run do

$java -cp .:a.jar:b.jar:c.jar HelloWorld

WPF Button with Image

You want to do something like this instead:

<Button>
    <StackPanel>
        <Image Source="Pictures/apple.jpg" />
        <TextBlock>Disconnect from Server</TextBlock>
    </StackPanel>
</Button>

Get specific object by id from array of objects in AngularJS

You can use ng-repeat and pick data only if data matches what you are looking for using ng-show for example:

 <div ng-repeat="data in res.results" ng-show="data.id==1">
     {{data.name}}
 </div>    

Detect IE version (prior to v9) in JavaScript

The below codepen identifies IE version in all cases (IE<=9, IE10, IE11 and IE/Edge)

function detectIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }
    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }
    // other browser
    return false;
}

ref: https://codepen.io/gapcode/pen/vEJNZN

Use tnsnames.ora in Oracle SQL Developer

I had the same problem, tnsnames.ora worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.

It turns out that the database was caching backup copies of tnsnames.ora like tnsnames.ora.bk2, tnsnames09042811AM4501.bak, tnsnames.ora.bk etc. These files were not readable by the average user.

I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.

The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.

How to escape braces (curly brackets) in a format string in .NET

My objective:

I needed to assign the value "{CR}{LF}" to a string variable delimiter.

Code c#:

string delimiter= "{{CR}}{{LF}}";

Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

How can I enable MySQL's slow query log without restarting MySQL?

Try SET GLOBAL slow_query_log = 'ON'; and perhaps FLUSH LOGS;

This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.

How can I pretty-print JSON using Go?

Here is my solution:

import (
    "bytes"
    "encoding/json"
)

const (
    empty = ""
    tab   = "\t"
)

func PrettyJson(data interface{}) (string, error) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent(empty, tab)

    err := encoder.Encode(data)
    if err != nil {
       return empty, err
    }
    return buffer.String(), nil
}

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Add STATS=10 or STATS=1 in backup command.

BACKUP DATABASE [xxxxxx] TO  DISK = N'E:\\Bachup_DB.bak' WITH NOFORMAT, NOINIT,  
NAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION,  STATS = 10
GO.

Set the table column width constant regardless of the amount of text in its cells?

It also helps, to put in the last "filler cell", with width:auto. This will occupy remaining space, and will leave all other dimensions as specified.

How to handle screen orientation change when progress dialog and background thread active?

I discovered a solution to this that I haven't yet seen elsewhere. You can use a custom application object that knows if you have background tasks going, instead of trying to do this in the activity that gets destroyed and recreated on orientation change. I blogged about this in here.

C# Get a control's position on a form

You can use the controls PointToScreen method to get the absolute position with respect to the screen.

You can do the Forms PointToScreen method, and with basic math, get the control's position.

"Could not find or load main class" Error while running java program using cmd prompt

I had the same problem, mine was a little different though I did not have a package name. My problem was the Class Path for example:

C:\Java Example>java -cp . HelloWorld 

The -cp option for Java and from what I can tell from my experience (not much) but I encountered the error about 20 times trying different methods and until I declared the class Path I was receiving the same error. Vishrant was correct in stating that . represents current directory.

If you need more information about the java options enter java -? or java -help I think the options are not optional.

I just did some more research I found a website that goes into detail about CLASSPATH. The CLASSPATH must be set as an environment variable; to the current directory <.>. You can set it from the command line in windows:

// Set CLASSPATH to the current directory '.'
prompt> set CLASSPATH=.

When you add a new environment setting you need to reboot before enabling the variable. But from the command prompt you can set it. It also can be set like I mentioned at the beginning. For more info, and if your using a different OS, check: Environment Variables.

How to get highcharts dates in the x axis?

Highcharts will automatically try to find the best format for the current zoom-range. This is done if the xAxis has the type 'datetime'. Next the unit of the current zoom is calculated, it could be one of:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • year

This unit is then used find a format for the axis labels. The default patterns are:

second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'

If you want the day to be part of the "hour"-level labels you should change the dateTimeLabelFormats option for that level include %d or %e. These are the available patters:

  • %a: Short weekday, like 'Mon'.
  • %A: Long weekday, like 'Monday'.
  • %d: Two digit day of the month, 01 to 31.
  • %e: Day of the month, 1 through 31.
  • %b: Short month, like 'Jan'.
  • %B: Long month, like 'January'.
  • %m: Two digit month number, 01 through 12.
  • %y: Two digits year, like 09 for 2009.
  • %Y: Four digits year, like 2009.
  • %H: Two digits hours in 24h format, 00 through 23.
  • %I: Two digits hours in 12h format, 00 through 11.
  • %l (Lower case L): Hours in 12h format, 1 through 11.
  • %M: Two digits minutes, 00 through 59.
  • %p: Upper case AM or PM.
  • %P: Lower case AM or PM.
  • %S: Two digits seconds, 00 through 59

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

Can I write or modify data on an RFID tag?

Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Follow the steps below in Oracle VM VirtualBox Manager:

  1. Select the Virtual device and choose Settings
  2. Navigate to System and click the Processor tab
  3. Tick the check-box, Enable PAE/NX
  4. Click OK and you are done

To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.

Close this device and open it from Genymotion.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.

In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.

#pragma mark is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Strip HTML from strings in Python

There's a simple way to this:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
        if c == '<' and not quote:
            tag = True
        elif c == '>' and not quote:
            tag = False
        elif (c == '"' or c == "'") and tag:
            quote = not quote
        elif not tag:
            out = out + c

    return out

The idea is explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: http://www.udacity.com/overview/Course/cs259/CourseRev/1. It's free!

You're welcome! :)

Should I return EXIT_SUCCESS or 0 from main()?

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example.

If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.

For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.)

(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

how to align all my li on one line?

Using Display: table

HTML:

<ul class="my-row">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

CSS:

ul.my-row {
  display: table;
  width: 100%;
  text-align: center;
}

ul.my-row > li {
  display: table-cell;
}

SCSS:

ul {
  &.my-row {
    display: table;
    width: 100%;
    text-align: center;

    > li {
      display: table-cell;
    }
  } 
}

Work great for me

What's the main difference between int.Parse() and Convert.ToInt32

Int32.parse(string)--->

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:

string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789"; 

result = Int32.Parse(s1);    //1234
result = Int32.Parse(s2);    //FormatException
result = Int32.Parse(s3);    //ArgumentNullException 
result = Int32.Parse(s4);    //OverflowException

Convert.ToInt32(string) --> Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

For example:

 result = Convert.ToInt32(s1);    // 1234 
 result = Convert.ToInt32(s2);    // FormatException
 result = Convert.ToInt32(s3);    // 0
 result = Convert.ToInt32(s4);    // OverflowException 

New Line Issue when copying data from SQL Server 2012 to Excel

As many times I have to copy data from SQL to excel, I've created function to deal with with new line and also tab characters (which make shifts in columns after pasting to Excel).

CREATE FUNCTION XLS(@String NVARCHAR(MAX) )

RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @String = REPLACE (@String, CHAR(9), ' ')
    SET @String = REPLACE (@String, CHAR(10), ' ')
    SET @String = REPLACE (@String, CHAR(13), ' ')
    RETURN @String
END

CREATE FUNCTION XLS(@String NVARCHAR(MAX) )
RETURNS NVARCHAR(MAX)

AS
BEGIN
    SET @String = REPLACE (@String, CHAR(9), ' ')
    SET @String = REPLACE (@String, CHAR(10), ' ')
    SET @String = REPLACE (@String, CHAR(13), ' ')
    RETURN @String
END

Example usage:

SELECT dbo.XLS(Description) FROM Server_Inventory

How to empty a char array?

char members[255] = {0};

Vim clear last search highlighting

I just use the simple nohl below and no plugins are needed.

:nohl

How to convert an NSTimeInterval (seconds) into minutes

    NSDate *timeLater = [NSDate dateWithTimeIntervalSinceNow:60*90];

    NSTimeInterval duration = [timeLater  timeIntervalSinceNow];

    NSInteger hours = floor(duration/(60*60));
    NSInteger minutes = floor((duration/60) - hours * 60);
    NSInteger seconds = floor(duration - (minutes * 60) - (hours * 60 * 60));

    NSLog(@"timeLater: %@", [dateFormatter stringFromDate:timeLater]);

    NSLog(@"time left: %d hours %d minutes  %d seconds", hours,minutes,seconds);

Outputs:

timeLater: 22:27
timeLeft: 1 hours 29 minutes  59 seconds

Comparing two byte arrays in .NET

For comparing short byte arrays the following is an interesting hack:

if(myByteArray1.Length != myByteArray2.Length) return false;
if(myByteArray1.Length == 8)
   return BitConverter.ToInt64(myByteArray1, 0) == BitConverter.ToInt64(myByteArray2, 0); 
else if(myByteArray.Length == 4)
   return BitConverter.ToInt32(myByteArray2, 0) == BitConverter.ToInt32(myByteArray2, 0); 

Then I would probably fall out to the solution listed in the question.

It'd be interesting to do a performance analysis of this code.

How to convert JSON to a Ruby hash

I'm surprised nobody pointed out JSON's [] method, which makes it very easy and transparent to decode and encode from/to JSON.

If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.

Consider this:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

str now contains the JSON encoded hash.

It's easy to reverse it using:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

Custom objects need to_s defined for the class, and inside it convert the object to a Hash then use to_json on it.

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How do I get a value of a <span> using jQuery?

You could use id in span directly in your html.

<span id="span_id">Client</span>

Then your jQuery code would be

$("#span_id").text();

Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So

$("#span_id").val();

will return null.

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

Convert a Unix timestamp to time in JavaScript

UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

See code below for example:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

gives:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

Python: List vs Dict for look up table

You don't actually need to store 10 million values in the table, so it's not a big deal either way.

Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

How can a windows service programmatically restart itself?

Just passing: and thought i would add some extra info...

you can also throw an exception, this will auto close the windows service, and the auto re-start options just kick in. the only issue with this is that if you have a dev enviroment on your pc then the JIT tries to kick in, and you will get a prompt saying debug Y/N. say no and then it will close, and then re-start properly. (on a PC with no JIT it just all works). the reason im trolling, is this JIT is new to Win 7 (it used to work fine with XP etc) and im trying to find a way of disabling the JIT.... i may try the Environment.Exit method mentioned here see how that works too.

Kristian : Bristol, UK

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

Selecting multiple columns with linq query and lambda expression

You can use:

public YourClass[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == 1)
                           .OrderBy(x => x.ID)
                           .Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
                           .ToArray();
        }
    }
    catch
    {
        return null;
    }
}

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

how to check the version of jar file?

Decompress the JAR file and look for the manifest file (META-INF\MANIFEST.MF). The manifest file of JAR file might contain a version number (but not always a version is specified).

Virtualenv Command Not Found

I think your problem can be solved using a simple symbolic link, but you are creating the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv

What is a lambda expression in C++11?

What is a lambda function?

The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++ a lambda function is defined like this

[]() { } // barebone lambda

or in all its glory

[]() mutable -> T { } // T is the return type, still lacking throw()

[] is the capture list, () the argument list and {} the function body.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

The argument list

The argument list is the same as in any other C++ function.

The function body

The code that will be executed when the lambda is actually called.

Return type deduction

If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement).

Mutable

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

C++14

In C++14 lambdas have been extended by various proposals.

Initialized Lambda Captures

An element of the capture list can now be initialized with =. This allows renaming of variables and to capture by moving. An example taken from the standard:

int x = 4;
auto y = [&r = x, x = x+1]()->int {
            r += 2;
            return x+2;
         }();  // Updates ::x to 6, and initializes y to 7.

and one taken from Wikipedia showing how to capture with std::move:

auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};

Generic Lambdas

Lambdas can now be generic (auto would be equivalent to T here if T were a type template argument somewhere in the surrounding scope):

auto lambda = [](auto x, auto y) {return x + y;};

Improved Return Type Deduction

C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;. This is also extended to lambdas.

Play sound on button click android

Tested and working 100%

public class MainActivity extends ActionBarActivity {
    Context context = this;
    MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        mp = MediaPlayer.create(context, R.raw.sound);
        final Button b = (Button) findViewById(R.id.Button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                        mp = MediaPlayer.create(context, R.raw.sound);
                    } mp.start();
                } catch(Exception e) { e.printStackTrace(); }
            }
        });
    }
}

This was all we had to do

if (mp.isPlaying()) {
    mp.stop();
    mp.release();
    mp = MediaPlayer.create(context, R.raw.sound);
}

What are C++ functors and their uses?

Functors are used in gtkmm to connect some GUI button to an actual C++ function or method.


If you use the pthread library to make your app multithreaded, Functors can help you.
To start a thread, one of the arguments of the pthread_create(..) is the function pointer to be executed on his own thread.
But there's one inconvenience. This pointer can't be a pointer to a method, unless it's a static method, or unless you specify it's class, like class::method. And another thing, the interface of your method can only be:

void* method(void* something)

So you can't run (in a simple obvious way), methods from your class in a thread without doing something extra.

A very good way of dealing with threads in C++, is creating your own Thread class. If you wanted to run methods from MyClass class, what I did was, transform those methods into Functor derived classes.

Also, the Thread class has this method: static void* startThread(void* arg)
A pointer to this method will be used as an argument to call pthread_create(..). And what startThread(..) should receive in arg is a void* casted reference to an instance in heap of any Functor derived class, which will be casted back to Functor* when executed, and then called it's run() method.

Adding event listeners to dynamically added elements using jQuery

$(document).on('click', 'selector', handler);

Where click is an event name, and handler is an event handler, like reference to a function or anonymous function function() {}

PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document.

How do I create a constant in Python?

You can use a namedtuple as a workaround to effectively create a constant that works the same way as a static final variable in Java (a Java "constant"). As workarounds go, it's sort of elegant. (A more elegant approach would be to simply improve the Python language --- what sort of language lets you redefine math.pi? -- but I digress.)

(As I write this, I realize another answer to this question mentioned namedtuple, but I'll continue here because I'll show a syntax that more closely parallels what you'd expect in Java, as there is no need to create a named type as namedtuple forces you to do.)

Following your example, you'll remember that in Java we must define the constant inside some class; because you didn't mention a class name, let's call it Foo. Here's the Java class:

public class Foo {
  public static final String CONST_NAME = "Name";
}

Here's the equivalent Python.

from collections import namedtuple
Foo = namedtuple('_Foo', 'CONST_NAME')('Name')

The key point I want to add here is that you don't need a separate Foo type (an "anonymous named tuple" would be nice, even though that sounds like an oxymoron), so we name our namedtuple _Foo so that hopefully it won't escape to importing modules.

The second point here is that we immediately create an instance of the nametuple, calling it Foo; there's no need to do this in a separate step (unless you want to). Now you can do what you can do in Java:

>>> Foo.CONST_NAME
'Name'

But you can't assign to it:

>>> Foo.CONST_NAME = 'bar'
…
AttributeError: can't set attribute

Acknowledgement: I thought I invented the namedtuple approach, but then I see that someone else gave a similar (although less compact) answer. Then I also noticed What are "named tuples" in Python?, which points out that sys.version_info is now a namedtuple, so perhaps the Python standard library already came up with this idea much earlier.

Note that unfortunately (this still being Python), you can erase the entire Foo assignment altogether:

>>> Foo = 'bar'

(facepalm)

But at least we're preventing the Foo.CONST_NAME value from being changed, and that's better than nothing. Good luck.

How to insert an element after another element in JavaScript without using a library?

A quick Google search reveals this script

// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
    // target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode;

    // if the parents lastchild is the targetElement...
    if (parent.lastChild == targetElement) {
        // add the newElement after the target element.
        parent.appendChild(newElement);
    } else {
        // else the target has siblings, insert the new element between the target and it's next sibling.
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

Add all files to a commit except a single file?

For the specific case in the question, easiest way would be to add all files with .c extension and leave out everything else:

git add *.c

From git-scm (or/and man git add):

git add <pathspec>…?

Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files. <...>

Note that this means that you could also do something like:

git add **/main/*

to add all files (that are not ignored) that are in the main folder. You can even go wild with more elaborate patterns:

git add **/s?c/*Service*

The above will add all files that are in s(any char)c folder and have Service somewhere in their filename.

Obviously, you are not limited to one pattern per command. That is, you could ask git to add all files that have an extension of .c and .h:

git add *.c *.h

This link might give you some more glob pattern ideas.

I find it particularly useful when I'm making many changes, but still want my commits to stay atomic and reflect gradual process rather than a hodgepodge of changes I may be working at the time. Of course, at some point the cost of coming up with elaborate patterns outweighs the cost of adding files with simpler methods, or even one file at a time. However, most of the time I'm easily able to pinpoint just the files I need with a simple pattern, and exclude everything else.

By the way, you may need to quote your glob patterns for them to work, but this was never the case for me.

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

How to add percent sign to NSString

seems if %% followed with a %@, the NSString will go to some strange codes try this and this worked for me

NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%", 
                 [textfield text], @"%%"]; 

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

it was happened to me because I've a strange clash in the namespaces: I had AssemblyA with namespace AssemblyA.ParentNamespace witch defines ClassA and in the same assembly another namespace with name AssemblyA.ParentNamespace.ChildNamespace witch defines a different ClassA (but with the same name)

I had then in AssemblyA.ParentNamespace IInterfaceB witch had a method that in the beginning returns IEnumerable and a ClassB witch implements IInterfaceB

I had later modified the method in ClassB to return IEnumerable but I've forgot to update the IInterfaceB definition, so the method there was still returning IEnumerable the fun fact was that the solution still complile if I did a rebuild all, but the tests witch refers AssemblyA didsn't work and returns the "Metadata file could not be found"error.

updating InterfaceB to correctly return IEnumerable as its implementor ClassB did solved the problem, unfortunately the error message was vague and also the fact that the compilation worked makes me suppose that maybe there is something to fix in the compiler

Python: Converting from ISO-8859-1/latin1 to UTF-8

This is a common problem, so here's a relatively thorough illustration.

For non-unicode strings (i.e. those without u prefix like u'\xc4pple'), one must decode from the native encoding (iso8859-1/latin1, unless modified with the enigmatic sys.setdefaultencoding function) to unicode, then encode to a character set that can display the characters you wish, in this case I'd recommend UTF-8.

First, here is a handy utility function that'll help illuminate the patterns of Python 2.7 string and unicode:

>>> def tell_me_about(s): return (type(s), s)

A plain string

>>> v = "\xC4pple" # iso-8859-1 aka latin1 encoded string

>>> tell_me_about(v)
(<type 'str'>, '\xc4pple')

>>> v
'\xc4pple'        # representation in memory

>>> print v
?pple             # map the iso-8859-1 in-memory to iso-8859-1 chars
                  # note that '\xc4' has no representation in iso-8859-1, 
                  # so is printed as "?".

Decoding a iso8859-1 string - convert plain string to unicode

>>> uv = v.decode("iso-8859-1")
>>> uv
u'\xc4pple'       # decoding iso-8859-1 becomes unicode, in memory

>>> tell_me_about(uv)
(<type 'unicode'>, u'\xc4pple')

>>> print v.decode("iso-8859-1")
Äpple             # convert unicode to the default character set
                  # (utf-8, based on sys.stdout.encoding)

>>> v.decode('iso-8859-1') == u'\xc4pple'
True              # one could have just used a unicode representation 
                  # from the start

A little more illustration — with “Ä”

>>> u"Ä" == u"\xc4"
True              # the native unicode char and escaped versions are the same

>>> "Ä" == u"\xc4"  
False             # the native unicode char is '\xc3\x84' in latin1

>>> "Ä".decode('utf8') == u"\xc4"
True              # one can decode the string to get unicode

>>> "Ä" == "\xc4"
False             # the native character and the escaped string are
                  # of course not equal ('\xc3\x84' != '\xc4').

Encoding to UTF

>>> u8 = v.decode("iso-8859-1").encode("utf-8")
>>> u8
'\xc3\x84pple'    # convert iso-8859-1 to unicode to utf-8

>>> tell_me_about(u8)
(<type 'str'>, '\xc3\x84pple')

>>> u16 = v.decode('iso-8859-1').encode('utf-16')
>>> tell_me_about(u16)
(<type 'str'>, '\xff\xfe\xc4\x00p\x00p\x00l\x00e\x00')

>>> tell_me_about(u8.decode('utf8'))
(<type 'unicode'>, u'\xc4pple')

>>> tell_me_about(u16.decode('utf16'))
(<type 'unicode'>, u'\xc4pple')

Relationship between unicode and UTF and latin1

>>> print u8
Äpple             # printing utf-8 - because of the encoding we now know
                  # how to print the characters

>>> print u8.decode('utf-8') # printing unicode
Äpple

>>> print u16     # printing 'bytes' of u16
???pple

>>> print u16.decode('utf16')
Äpple             # printing unicode

>>> v == u8
False             # v is a iso8859-1 string; u8 is a utf-8 string

>>> v.decode('iso8859-1') == u8
False             # v.decode(...) returns unicode

>>> u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16')
True              # all decode to the same unicode memory representation
                  # (latin1 is iso-8859-1)

Unicode Exceptions

 >>> u8.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
  ordinal not in range(128)

>>> u16.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
  ordinal not in range(128)

>>> v.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
  ordinal not in range(128)

One would get around these by converting from the specific encoding (latin-1, utf8, utf16) to unicode e.g. u8.decode('utf8').encode('latin1').

So perhaps one could draw the following principles and generalizations:

  • a type str is a set of bytes, which may have one of a number of encodings such as Latin-1, UTF-8, and UTF-16
  • a type unicode is a set of bytes that can be converted to any number of encodings, most commonly UTF-8 and latin-1 (iso8859-1)
  • the print command has its own logic for encoding, set to sys.stdout.encoding and defaulting to UTF-8
  • One must decode a str to unicode before converting to another encoding.

Of course, all of this changes in Python 3.x.

Hope that is illuminating.

Further reading

And the very illustrative rants by Armin Ronacher:

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Edit a specific Line of a Text File in C#

When you create a StreamWriter it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one. But as I can see what you need is XML manipulation, you might want to use XmlDocument and modify your file using Xpath.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

Did you try to set up the FillWeight property of your DataGridViewColumns object?

For example:

this.grid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.grid1.Columns[0].FillWeight = 1.5;

I think it should work in your case.

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

How do I redirect to the previous action in ASP.NET MVC?

A suggestion for how to do this such that:

  1. the return url survives a form's POST request (and any failed validations)
  2. the return url is determined from the initial referral url
  3. without using TempData[] or other server-side state
  4. handles direct navigation to the action (by providing a default redirect)

.

public ActionResult Create(string returnUrl)
{
    // If no return url supplied, use referrer url.
    // Protect against endless loop by checking for empty referrer.
    if (String.IsNullOrEmpty(returnUrl)
        && Request.UrlReferrer != null
        && Request.UrlReferrer.ToString().Length > 0)
    {
        return RedirectToAction("Create",
            new { returnUrl = Request.UrlReferrer.ToString() });
    }

    // Do stuff...
    MyEntity entity = GetNewEntity();

    return View(entity);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
    try
    {
        // TODO: add create logic here

        // If redirect supplied, then do it, otherwise use a default
        if (!String.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index");
    }
    catch
    {
        return View();  // Reshow this view, with errors
    }
}

You could use the redirect within the view like this:

<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
    <a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

Encrypting & Decrypting a String in C#

If you need to store a password in memory and would like to have it encrypted you should use SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

jQuery calculate sum of values in all text fields

Use this function:

$(".price").each(function(){
total_price += parseInt($(this).val());
});

Get specific line from text file using just shell script

Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:

perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd

How to trigger a click on a link using jQuery

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

How to include a quote in a raw Python string

If you want to use double quotes in strings but not single quotes, you can just use single quotes as the delimiter instead:

r'what"ever'

If you need both kinds of quotes in your string, use a triple-quoted string:

r"""what"ev'er"""

If you want to include both kinds of triple-quoted strings in your string (an extremely unlikely case), you can't do it, and you'll have to use non-raw strings with escapes.

Scrolling a flexbox with overflowing content

A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269

Basically you need to put html,body to height: 100%; and wrap all your content into a <div class="wrap"> <!-- content --> </div>

CSS:

html, body {
  height: 100%;
}

.wrap {
  height: 100vh;
  display: flex;
}

Worked for me. Hope it helps

How to set dropdown arrow in spinner?

                   <Spinner
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="16dp"
                    android:paddingLeft="10dp"
                    android:spinnerMode="dropdown" />

Connection pooling options with JDBC: DBCP vs C3P0

Another alternative, Proxool, is mentioned in this article.

You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?

How to change the style of the title attribute inside an anchor tag?

I have found the answer here: http://www.webdesignerdepot.com/2012/11/how-to-create-a-simple-css3-tooltip/

my own code goes like this, I have changed the attribute name, if you maintain the title name for the attribute you end up having two popups for the same text, another change is that my text on hovering displays underneath the exposed text.

_x000D_
_x000D_
.tags {
  display: inline;
  position: relative;
}

.tags:hover:after {
  background: #333;
  background: rgba(0, 0, 0, .8);
  border-radius: 5px;
  bottom: -34px;
  color: #fff;
  content: attr(gloss);
  left: 20%;
  padding: 5px 15px;
  position: absolute;
  z-index: 98;
  width: 350px;
}

.tags:hover:before {
  border: solid;
  border-color: #333 transparent;
  border-width: 0 6px 6px 6px;
  bottom: -4px;
  content: "";
  left: 50%;
  position: absolute;
  z-index: 99;
}
_x000D_
<a class="tags" gloss="Text shown on hovering">Exposed text</a>
_x000D_
_x000D_
_x000D_

SELECT with LIMIT in Codeigniter

For further visitors:

// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);

// get_where sample, 
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);

// Produces: LIMIT 10
$this->db->limit(10);  

// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);

What is copy-on-write?

I shall not repeat the same answer on Copy-on-Write. I think Andrew's answer and Charlie's answer have already made it very clear. I will give you an example from OS world, just to mention how widely this concept is used.

We can use fork() or vfork() to create a new process. vfork follows the concept of copy-on-write. For example, the child process created by vfork will share the data and code segment with the parent process. This speeds up the forking time. It is expected to use vfork if you are performing exec followed by vfork. So vfork will create the child process which will share data and code segment with its parent but when we call exec, it will load up the image of a new executable in the address space of the child process.

Find what 2 numbers add to something and multiply to something

Here is how I would do that:

$sum = 5;
$product = 6;

$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
  $b = $sum - $a;
  if ($a * $b == $product) {
    $found = TRUE;
    break;
  }
}

if ($found) {
  echo "The answer is a = $a, b = $b.";
} else {
  echo "There is no answer where a and b are both integers.";
}

Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.

See it working

Whether that is the most efficient method is very much debatable.

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

How to add an Access-Control-Allow-Origin header

For Java based Application add this to your web.xml file:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.ttf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.otf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.eot</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.woff</url-pattern>
</servlet-mapping>

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

How to change or add theme to Android Studio?

On Windows: File-> Settings-> Appearance&Behavior-> Appearance: Change "Theme field".

Use of PUT vs PATCH methods in REST API real life scenarios

In my humble opinion, idempotence means:

  • PUT:

I send a compete resource definition, so - the resulting resource state is exactly as defined by PUT params. Each and every time I update the resource with the same PUT params - the resulting state is exactly the same.

  • PATCH:

I sent only part of the resource definition, so it might happen other users are updating this resource's OTHER parameters in a meantime. Consequently - consecutive patches with the same parameters and their values might result with different resource state. For instance:

Presume an object defined as follows:

CAR: - color: black, - type: sedan, - seats: 5

I patch it with:

{color: 'red'}

The resulting object is:

CAR: - color: red, - type: sedan, - seats: 5

Then, some other users patches this car with:

{type: 'hatchback'}

so, the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

Now, if I patch this object again with:

{color: 'red'}

the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

What is DIFFERENT to what I've got previously!

This is why PATCH is not idempotent while PUT is idempotent.

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

How to set my default shell on Mac?

the chsh program will let you change your default shell. It will want the full path to the executable, so if your shell is fish then it will want you to provide the output given when you type which fish.

You'll see a line starting with "Shell:". If you've never edited it, it most likely says "Shell: /bin/bash". Replace that /bin/bash path with the path to your desired shell.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Check The data you are writing to Server. May be data has delimiter which is not used.

like

045|2272575|0.000|0.000|2013-10-07
045|2272585|0.000|0.000;2013-10-07

your delimiter is '|' but data has a delimiter ';'. So for this you are getting the error.

mysql query: SELECT DISTINCT column1, GROUP BY column2

You can just add the DISTINCT(ip), but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Changing user agent on urllib2.urlopen

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()

Or, a bit shorter:

req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()

How to override toString() properly in Java?

You can't call a constructor as if it was a normal method, you can only call it with new to create a new object:

Kid newKid = new Kid(this.name, this.height, this.bDay);

But constructing a new object from your toString() method is not what you want to be doing.

What is the HTML tabindex attribute?

The is used to define a sequence that users follow when they use the Tab key to navigate through a page. By default, the natural tabbing order will match the source order in the markup.

The tabindex content attribute allows authors to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation. The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.
W3C Recommendation: HTML5
Section 7.4.1 Sequential focus navigation and the tabindex attribute

The tabindex starts at 0 or any positive whole number and increments upward. It's common to see the value 0 avoided because in older versions of Mozilla and IE, the tabindex would start at 1, move on to 2, and only after 2 would it go to 0 and then 3. The maximum integer value for tabindex is 32767. If elements have the same tabindex then the tabindex will match the source order in the markup. A negative value will remove the element from the tab index so it will never be focused.

If an element is assigned a tabindex of -1 it will remove the element and it will never be focusable but focus can be given to the element programmatically using element.focus().

If you specify the tabindex attribute with no value or an empty value it will be ignored.

If the disabled attribute is set on an element which has a tabindex, the element will be ignored.


If a tabindex is set anywhere within the page regardless of where it is in relation to the rest of the code (it could be in the footer, content area, where-ever) if there is a defined tabindex then the tab order will start at the element which is explicitly assigned the lowest tabindex value above 0. It will then cycle through the elements defined and only after the explicit tabindex elements have been tabbed through, will it return to the beginning of the document and follow the natural tab order.


In the HTML4 spec only the following elements support the tabindex attribute: , , , , , , and . But the HTML5 spec, with accessibility in mind, allows all elements to be assigned tabindex.

--

For example

<ul tabindex="-1">
  <li tabindex="1"></li>
  <li tabindex="2"></li>
  <li tabindex="3"></li>
</ul>

is the same as

<ul tabindex="-1">
  <li tabindex="1"></li>
  <li tabindex="1"></li>
  <li tabindex="1"></li>
</ul>

because regardless of the fact that they are all assigned tabindex="1", they will still follow the same order, the first one is first, and the last one is last. This is also the same..

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

because you do not need to explicitly define the tabIndex if it's default behavior. A div by default will not be focusable, the anchor tags will.

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

How can I check if mysql is installed on ubuntu?

Try executing 'mysql' or 'mysql -- version' without quotes on terminal. it will prompt version otherwise Command Not Found

how to clear JTable

You must remove the data from the TableModel used for the table.

If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

If you are using other TableModel, please check the documentation.

Comparison between Corona, Phonegap, Titanium

I registered with stackoverflow just for the purpose of commenting on the mostly voted answer on top. The bad thing is stackoverflow does not allow new members to post comments. So I have to make this comment more look like an answer.

Rory Blyth's answer contains some valid points about the two javascript mobile frameworks. However, his key points are incorrect. The truth is that Titanium and PhoneGap are more similar than different. They both expose mobile phone functions through a set of javascript APIs, and the application's logic (html, css, javascript) runs inside a native WebView control.

  1. PhoneGap is not just a native wrapper of a web app. Through the PhoneGap javascript APIs, the "web app" has access to the mobile phone functions such as Geolocation, Accelerometer Camera, Contacts, Database, File system, etc. Basically any function that the mobile phone SDK provides can be "bridged" to the javascript world. On the other hand, a normal web app that runs on the mobile web browser does not have access to most of these functions (security being the primary reason). Therefore, a PhoneGap app is more of a mobile app than a web app. You can certainly use PhoneGap to wrap a web app that does not use any PhoneGap APIs at all, but that is not what PhoneGap was created for.

  2. Titanium does NOT compile your html, css or javascript code into "native bits". They are packaged as resources to the executable bundle, much like an embedded image file. When the application runs, these resources are loaded into a UIWebView control and run there (as javascript, not native bits, of course). There is no such thing as a javascript-to-native-code (or to-objective-c) compiler. This is done the same way in PhoneGap as well. From architectural standpoint, these two frameworks are very similar.

Now, are they any different? Yes. First, Titanium appears to be more feature rich than PhoneGap by bridging more mobile phone functions to javascript. Most noticeably, PhoneGap does not expose many (if any) native UI components to javascript. Titanium, on the other hand, has a comprehensive UI APIs that can be called in javascript to create and control all kinds of native UI controls. Utilizaing these UI APIs, a Titanium app can look more "native" than a PhoneGap app. Second, PhoneGap supports more mobile phone platforms than Titanium does. PhoneGap APIs are more generic and can be used on different platforms such as iPhone, Android, Blackberry, Symbian, etc. Titanium is primarily targeting iPhone and Android at least for now. Some of its APIs are platform specific (like the iPhone UI APIs). The use of these APIs will reduce the cross-platform capability of your application.

So, if your concern for your app is to make it more "native" looking, Titanium is a better choice. If you want to be able to "port" your app to another platform more easily, PhoneGap will be better.

Updated 8/13/2010: Link to a Titanium employee's answer to Mickey's question.

Updated 12/04/2010: I decided to give this post an annual review to keep its information current. Many things have changes in a year that made some of the information in the initial post outdated.

The biggest change came from Titanium. Earlier this year, Appcelerator released Titanium 1.0, which departed drastically from its previous versions from the architectural standpoint. In 1.0, the UIWebView control is no longer in use. Instead, you call Titanium APIs for any UI functions. This change means a couple things:

  1. Your app UI becomes completely native. There is no more web UI in your app since the native Titanium APIs take over control of all your UI needs. Titanium deserves a lot of credit by pioneering on the "Cross-Platform Native UI" frontier. It gives programmers who prefer the look and feel of native UI but dislike the official programming language an alternative.

  2. You won't be able to use HTML or CSS in your app, as the web view is gone. (Note: you can still create web view in Titanium. But there are few Titanium features that you can take advantage of in the web view.)Titanium Q&A: What happened to HTML & CSS?

  3. You won't be able to use popular JS libraries such as JQuery that assume the existence of an DOM object. You continue to use JavaScript as your coding language. But that is pretty much the only web technology you can utilize if you come to Titanium 1.0 as a web programmer.

Titanium video: What is new in Titanium 1.0.

Now, does Titanium 1.0 compile your JavaScript into "native bits"? No. Appcelerator finally came clean on this issue with this developer blog:Titanium Guides Project: JS Environment. We programmers are more genuine people than those in the Marketing department, aren't we? :-)

Move on to PhoneGap. There are not many new things to say about PhoneGap. My perception is that PhoneGap development was not very active until IBM jumped on board later this year. Some people even argued that IBM is contributing more code to PhoneGap than Nitobi is. That being true or not, it is good to know that PhoneGap is being active developed.

PhoneGap continues to base itself on web technologies, namely HTML, CSS and JavaScript. It does not look like PhoneGap has any plan to bridge native UI features to JavaScript as Titanium is doing. While Web UI still lags behind native UI on performance and native look and feel, such gap is being rapidly closed. There are two trends in web technologies that ensure bright feature to mobile web UI in terms of performance:

  1. JavaScript engine moving from an interpreter to a virtual machine. JavaScript is JIT compiled into native code for faster execution. Safari JS engine: SquirrelFish Extreme

  2. Web page rendering moving from relying on CPU to using GPU acceleration. Graphic intensive tasks such as page transition and 3D animation become a lot smoother with the help of hardware acceleration. GPU Accelerated Compositing in Chrome

Such improvements that are originated from desktop browsers are being delivered to mobile browsers quickly. In fact, since iOS 3.2 and Android 2.0, the mobile web view control has become much more performing and HTML5 friendly. The future of mobile web is so promising that it has attracted a big kid to town: JQuery has recently announced its mobile web framework. With JQuery Mobile providing UI gadgets, and PhoneGap providing phone features, they two combined creates a perfect mobile web platform in my opinion.

I should also mention Sencha Touch as another mobile web UI gadget framework. Sencha Touch version 1.0 was recently released under a dual licensing model that includes GPLv3. Sencha Touch works well with PhoneGap just as JQuery Mobile does.

If you are a GWT programmer(like me), you may want to check out GWT Mobile, an open source project for creating mobile web apps with GWT. It includes a PhoneGap GWT wrapper that enables the use of PhoneGap in GWT.

How to extract year and month from date in PostgreSQL without using to_char() function?

Use the date_trunc method to truncate off the day (or whatever else you want, e.g., week, year, day, etc..)

Example of grouping sales from orders by month:

select
  SUM(amount) as sales,
  date_trunc('month', created_at) as date
from orders
group by date
order by date DESC;

Commit empty folder structure (with git)

Simply add file named as .keep in images folder.you can now stage and commit and also able to add folder to version control.

Create a empty file in images folder $ touch .keep

$ git status

On branch master
Your branch is up-to-date with 'origin/master'.

Untracked files:
  (use "git add ..." to include in what will be committed)

    images/

nothing added to commit but untracked files present (use "git add" to track)

$ git add .

$ git commit -m "adding empty folder"

How to change font size in html?

If you want to do this without adding classes...

p:first-child {
    font-size: 16px;
}

p:last-child {
    font-size: 12px;
}

or

p:nth-child(1) {
    font-size: 16px;
}

p:nth-child(2) {
    font-size: 12px;
}

org.hibernate.MappingException: Unknown entity

You should call .addAnnotatedClass(Message.class) on your AnnotationConfiguration.

If you want your entities to be auto-discovered, use EntityManager (JPA)

(Reference)

Update: it appears you have listed the class in hibernate.cfg.xml. So auto-discovery is not necessary. Btw, try javax.persistence.Entity

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How do I create 7-Zip archives with .NET?

Install the NuGet package called SevenZipSharp.Interop

Then:

SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);