Programs & Examples On #Mpkg

An OS X meta installer package that can hold other packages inside itself

make: Nothing to be done for `all'

I arrived at this peculiar, hard-to-debug error through a different route. My trouble ended up being that I was using a pattern rule in a build step when the target and the dependency were located in distinct directories. Something like this:

foo/apple.o: bar/apple.c $(FOODEPS)

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

I had several dependencies set up this way, and was trying to use one pattern recipe for them all. Clearly, a single substitution for "%" isn't going to work here. I made explicit rules for each dependency, and I found myself back among the puppies and unicorns!

foo/apple.o: bar/apple.c $(FOODEPS)
    $(CC) $< -o $@

Hope this helps someone!

Regular Expressions and negating a whole character group

In this case I might just simply avoid regular expressions altogether and go with something like:

if (StringToTest.IndexOf("ab") < 0)
  //do stuff

This is likely also going to be much faster (a quick test vs regexes above showed this method to take about 25% of the time of the regex method). In general, if I know the exact string I'm looking for, I've found regexes are overkill. Since you know you don't want "ab", it's a simple matter to test if the string contains that string, without using regex.

How to unlock android phone through ADB

This command helps you to unlock phone using ADB

adb shell input keyevent 82 # unlock

Multiple line code example in Javadoc comment

Here's my two cents.

As the other answers already state, you should use <pre> </pre> in conjuction with {@code }.

Use pre and {@code}

  • Wrapping your code inside <pre> and </pre> prevents your code from collapsing onto one line;
  • Wrapping your code inside {@code } prevents <, > and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.

Problems with annotations

Problems can arise when your code block contains an annotation. That is probably because when the @ sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like @param or @return. For example, this code could be parsed incorrectly:

/**
 * Example usage:
 *
 * <pre>{@code
 * @Override
 * public void someOverriddenMethod() {

Above code will disappear completely in my case.

To fix this, the line must not start with an @ sign:

/**
 * Example usage:
 *
 * <pre>{@code  @Override
 * public int someMethod() {
 *     return 13 + 37;
 * }
 * }</pre>
 */

Note that there are two spaces between @code and @Override, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.

Iterating through a list to render multiple widgets in Flutter?

You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:

var list = ["one", "two", "three", "four"];

    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
          home: new Scaffold(
        appBar: new AppBar(
          title: new Text('List Test'),
        ),
        body: new Center(
          child: new Column( // Or Row or whatever :)
            children: createChildrenTexts(),
          ),
        ),
      ));
    }

     List<Text> createChildrenTexts() {
    /// Method 1
//    List<Text> childrenTexts = List<Text>();
//    for (String name in list) {
//      childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
//    }
//    return childrenTexts;

    /// Method 2
    return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
  }

stop service in android

onDestroyed()

is wrong name for

onDestroy()  

Did you make a mistake only in this question or in your code too?

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

How to jump back to NERDTree from file in tab?

You can focus on a split window using # ctrl-ww.

for example, pressing:

1 ctrl-ww

would focus on the first window, usually being NERDTree.

How to find pg_config path

To summarize -- PostgreSQL installs its files (including its binary or executable files) in different locations, depending on the version number and the installation method.

Some of the possibilities:

/usr/local/bin/
/Library/PostgreSQL/9.2/bin/
/Applications/Postgres93.app/Contents/MacOS/bin/
/Applications/Postgres.app/Contents/Versions/9.3/bin/

No wonder people get confused!

Also, if your $PATH environment variable includes a path to the directory that includes an executable file (to confirm this, use echo $PATH on the command line) then you can run which pg_config, which psql, etc. to find out where the file is located.

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Using an integer as a key in an associative array in JavaScript

You can just use an object:

var test = {}
test[2300] = 'Some string';

How to detect Ctrl+V, Ctrl+C using JavaScript?

You can listen to the keypress event, and halt the default event (entering the text) if it matches the specific keycodes

JavaScript for detecting browser language preference

Dan Singerman's answer has an issue that the header fetched has to be used right away, due to the asynchronous nature of jQuery's ajax. However, with his google app server, I wrote the following, such that the header is set as part of the initial set up and can be used at later time.

<html>
<head>
<script>

    var bLocale='raw'; // can be used at any other place

    function processHeaders(headers){
        bLocale=headers['Accept-Language'];
        comma=bLocale.indexOf(',');
        if(comma>0) bLocale=bLocale.substring(0, comma);
    }

</script>

<script src="jquery-1.11.0.js"></script>

<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>

</head>
<body>

<h1 id="bLocale">Should be the browser locale here</h1>

</body>

<script>

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

</script>
</html>

PHP Using RegEx to get substring of a string

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

PHP check if date between two dates

Edit: use <= or >= to count today's date.

This is the right answer for your code. Just use the strtotime() php function.

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}

MongoDB: How to find the exact version of installed MongoDB

Sometimes you need to see version of mongodb after making a connection from your project/application/code. In this case you can follow like this:

 mongoose.connect(
    encodeURI(DB_URL), {
      keepAlive: true
    },
    (err) => {
      if (err) {
        console.log(err)
      }else{
           const con = new mongoose.mongo.Admin(mongoose.connection.db)
              con.buildInfo( (err, db) => {
              if(err){
                throw err
              }
             // see the db version
             console.log(db.version)
            })
      }
    }
  )

Hope this will be helpful for someone.

How to check empty DataTable

If dataTable1 is null, it is not an empty datatable.

Simply wrap your foreach in an if-statement that checks if dataTable1 is null. Make sure that your foreach counts over DataTable1.Rows or you will get a compilation error.

    if (dataTable1 != null)
    {
       foreach (DataRow dr in dataTable1.Rows)
       {
          // ...
       }
    }

UnicodeEncodeError: 'latin-1' codec can't encode character

I hope your database is at least UTF-8. Then you will need to run yourstring.encode('utf-8') before you try putting it into the database.

Regex remove all special characters except numbers?

To remove the special characters, try

var name = name.replace(/[!@#$%^&*]/g, "");

HttpWebRequest using Basic authentication

One reason why the top answer and others wont work for you is because it is missing a critical line. (note many API manuals leave out this necessity)

request.PreAuthenticate = true;

Abstraction vs Encapsulation in Java

OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.

The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.

For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream to be changed, and as long as the API (interface) to FileInputStream remains consistent, code built against previous versions will still work.

Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.

In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).

For example, the fields of a class can be made private by default, and only if external access to these was required, would a get() and/or set() (or Property) be exposed from the class. (In modern day OO languages, fields can be marked as readonly / final / immutable which further restricts change, even within the class).

Example where NO information hiding has been applied (Bad Practice):

class Foo {
   // BAD - NOT Encapsulated - code external to the class can change this field directly
   // Class Foo has no control over the range of values which could be set.
   public int notEncapsulated;
}

Example where field encapsulation has been applied:

class Bar {
   // Improvement - access restricted only to this class
   private int encapsulatedPercentageField;

   // The state of Bar (and its fields) can now be changed in a controlled manner
   public void setEncapsulatedField(int percentageValue) {
      if (percentageValue >= 0 && percentageValue <= 100) {
          encapsulatedPercentageField = percentageValue;
      }
      // else throw ... out of range
   }
}

Example of immutable / constructor-only initialization of a field:

class Baz {
   private final int immutableField;

   public void Baz(int onlyValue) {
      // ... As above, can also check that onlyValue is valid
      immutableField = onlyValue;
   }
   // Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class 
}

Re : Abstraction vs Abstract Class

Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new() - abstract classes must be subclassed, and only concrete (non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction and an abstract class was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.

Re : Encapsulation vs Information Hiding

The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.

Quoting Wikipedia:

In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.

For example, in the statement

I've encapsulated the data access code into its own class

.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.


[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

How do I iterate over a JSON structure?

_x000D_
_x000D_
var jsonString = `{
    "schema": {
        "title": "User Feedback",
        "description": "so",
        "type": "object",
        "properties": {
            "name": {
                "type": "string"
            }
        }
    },
    "options": {
        "form": {
            "attributes": {},
            "buttons": {
                "submit": {
                    "title": "It",
                    "click": "function(){alert('hello');}"
                }
            }
        }
    }
}`;

var jsonData = JSON.parse(jsonString);

function Iterate(data)
{
    jQuery.each(data, function (index, value) {
        if (typeof value == 'object') {
            alert("Object " + index);
            Iterate(value);
        }
        else {
            alert(index + "   :   " + value);
        }
    });
}

Iterate(jsonData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Convert string in base64 to image and save on filesystem in Python

You could probably use the PyPNG package's png.Reader object to do this - decode the base64 string into a regular string (via the base64 standard library), and pass it to the constructor.

Possible to change where Android Virtual Devices are saved?

Variable name: ANDROID_SDK_HOME
Variable value: C:\Users>User Name

worked for me.

How to find if a native DLL file is compiled as x64 or x86?

For an unmanaged DLL file, you need to first check if it is a 16-bit DLL file (hopefully not). Then check the IMAGE\_FILE_HEADER.Machine field.

Someone else took the time to work this out already, so I will just repeat here:

To distinguish between a 32-bit and 64-bit PE file, you should check IMAGE_FILE_HEADER.Machine field. Based on the Microsoft PE and COFF specification below, I have listed out all the possible values for this field: http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v8.doc

IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type

IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33

IMAGE_FILE_MACHINE_AMD64 0x8664 x64

IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian

IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code

IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors

IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family

IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian

IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16

IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU

IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU

IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian

IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support

IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian

IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3

IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP

IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4

IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5

IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb

IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little-endian WCE v2

Yes, you may check IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_IA64 for 64bit and IMAGE_FILE_MACHINE_I386 for 32bit.

Why does this CSS margin-top style not work?

Just for a quick fix, try wrapping your child elements into a div element like this -

<div id="outer">
   <div class="divadjust" style="padding-top: 1px">
      <div id="inner">
         Hello world!
      </div>
   </div>
</div>

Margin of inner div won't collapse due to the padding of 1px in-between outer and inner div. So logically you will have 1px extra space along with existing margin of inner div.

Express.js Response Timeout

An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with

npm install connect-timeout

and in the code it has to be (Edited as per comment, how to include it in the code)

 var timeout = require('connect-timeout');
 app.use(timeout('100s'));

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Simple and fast method to compare images for similarity

Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:

  • Simple euclidean distance as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).
  • (Normalized) Cross Correlation - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.
  • Histogram comparison - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.
  • Detectors of salient points/areas - such as MSER (Maximally Stable Extremal Regions), SURF or SIFT. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: Local invariant feature detectors: a survey.

Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html. The salient point/area detectors are also available - see OpenCV Feature Detection.

How to run (not only install) an android application using .apk file?

When you start the app from the GUI, adb logcat might show you the corresponding action/category/component:

$ adb logcat
[...]
I/ActivityManager( 1607): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.browser/.BrowserActivity} from pid 1792
[...]

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.

...

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Best way to use sql brackets use callback function in laravel eloquent.

YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere('b', 1);
})->where(function ($q) {
    $q->where('c', 1)->orWhere('d', 1);
});

You don't have to use = symbol, it's come as the default

Lest say if you have a query that contain brackets inside a brackets

WHERE (a = 1 OR (b = 1 and c = 5))


YourModal::where(function ($q) {
    $q->where('a', 1)->orWhere(function($q2){
      $q2->where('b', 1)->where('c', 5);
    });
});

lest say you want to make values dynamics

YourModal::where(function ($q) use($val1, $val2) {
    $q->where('a', $val1)->orWhere(function($q2) use($val2){
      $q2->where('b', $val2)->where('c', $val2);
    });
});

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

One way to solve this problem is by turning the warnings off.

SET ANSI_WARNINGS OFF;
GO

Java String split removed empty values

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

String[] split = data.split("\\|", -1);

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Exception:

It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array.
It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Check your JNI/native code. One of my references was null, but it was intermittent, so it wasn't very obvious.

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

Xcode - ld: library not found for -lPods

Delete all the corresponding files/folders of imported cocoapods source except podfile.

install cocoapod again.This should clear any redundant pull from the original source.

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line.

File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}

NOTE:

To convert an active record database to csv would be something like this I think

CSV.open(fn, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values
  end
end

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0
CSV.open(fn, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
    else
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

Base64 length calculation?

Each character is used to represent 6 bits (log2(64) = 6).

Therefore 4 chars are used to represent 4 * 6 = 24 bits = 3 bytes.

So you need 4*(n/3) chars to represent n bytes, and this needs to be rounded up to a multiple of 4.

The number of unused padding chars resulting from the rounding up to a multiple of 4 will obviously be 0, 1, 2 or 3.

Cygwin Make bash command not found

Follow these steps:

  1. Go to the installer again
  2. Do the initial setup.
  3. Under library - go to devel.
  4. under devel scroll and find make.
  5. install all of library with name make.
  6. click next, will take some time to install.
  7. this will solve the problem.

How can I change the thickness of my <hr> tag

Here's a solution for a 1 pixel black line with no border or margin

hr {background-color:black; border:none; height:1px; margin:0px;}
  • Tested in Google Chrome

I thought I would add this because the other answers didn't include: margin:0px;.

  • Demo

_x000D_
_x000D_
hr {background-color:black; border:none; height:1px; margin:0px;}
_x000D_
<div style="border: 1px solid black; text-align:center;">_x000D_
<div style="background-color:lightblue;"> ? container ? <br> <br> <br> ? hr ? </div>_x000D_
<hr>_x000D_
<div style="background-color:lightgreen;"> ? hr ? <br> <br> <br> ? container ? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mysql - delete from multiple tables with one query

usually, i would expect this as a 'cascading delete' enforced in a trigger, you would only need to delete the main record, then all the depepndent records would be deleted by the trigger logic.

this logic would be similar to what you have written.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had same issue reported here. I solved the issue moving the mainTest.cpp from a subfolder src/mainTest/ to the main folder src/ I guess this was your problem too.

X close button only using css

You can use svg.

_x000D_
_x000D_
<svg viewPort="0 0 12 12" version="1.1"_x000D_
     xmlns="http://www.w3.org/2000/svg">_x000D_
    <line x1="1" y1="11" _x000D_
          x2="11" y2="1" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
    <line x1="1" y1="1" _x000D_
          x2="11" y2="11" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

How to insert 1000 rows at a time

DECLARE @X INT = 1
WHILE @X <=1000
BEGIN
    INSERT INTO dbo.YourTable (ID, Age)
    VALUES(@X,LEFT(RAND()*100,2) 
    SET @X+=1
END;

    enter code here
DECLARE @X INT = 1
WHILE @X <=1000
BEGIN
    INSERT INTO dbo.YourTable (ID, Age)
    VALUES(@X,LEFT(RAND()*100,2) 
    SET @X+=1
END;

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

Calculate date/time difference in java

Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.

By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.

Best method to download image from url in Android

you can use below function to download image from url.

private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight)
    {   
           private Bitmap image = null;
           int inSampleSize = 0;


            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inJustDecodeBounds = true;

            options.inSampleSize = inSampleSize;

            try
            {
                URL url = new URL(imageUrl);

                HttpURLConnection connection = (HttpURLConnection)url.openConnection();

                InputStream stream = connection.getInputStream();

                image = BitmapFactory.decodeStream(stream, null, options);

                int imageWidth = options.outWidth;

                int imageHeight = options.outHeight;

                if(imageWidth > desiredWidth || imageHeight > desiredHeight)
                {   
                    System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight);

                    inSampleSize = inSampleSize + 2;

                    getImage(imageUrl);
                }
                else
                {   
                    options.inJustDecodeBounds = false;

                    connection = (HttpURLConnection)url.openConnection();

                    stream = connection.getInputStream();

                    image = BitmapFactory.decodeStream(stream, null, options);

                    return image;
                }
            }

            catch(Exception e)
            {
                Log.e("getImage", e.toString());
            }

        return image;
    }

See complete explanation here

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • GoogleMaps API KEY for testing

    There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

    <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
    

    How to run console application from Windows Service?

    Windows Services do not have UIs. You can redirect the output from a console app to your service with the code shown in this question.

    how to create a cookie and add to http response from inside my service layer?

    Following @Aravind's answer with more details

    @RequestMapping("/myPath.htm")
    public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
        myServiceMethodSettingCookie(request, response);        //Do service call passing the response
        return new ModelAndView("CustomerAddView");
    }
    
    // service method
    void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
        final String cookieName = "my_cool_cookie";
        final String cookieValue = "my cool value here !";  // you could assign it some encoded value
        final Boolean useSecureCookie = false;
        final int expiryTime = 60 * 60 * 24;  // 24h in seconds
        final String cookiePath = "/";
    
        Cookie cookie = new Cookie(cookieName, cookieValue);
    
        cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
    
        cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
    
        cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
    
        response.addCookie(cookie);
    }
    

    Related docs:

    http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

    http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

    Array.push() if does not exist?

    My choice was to use .includes() extending the Array.prototype as @Darrin Dimitrov suggested:

    Array.prototype.pushIfNotIncluded = function (element) {
        if (!this.includes(element)) {
          array.push(element);
        }
    }
    

    Just remembering that includes comes from es6 and does not work on IE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

    How to echo (or print) to the js console with php

    <?php
       echo '<script>console.log("Your stuff here")</script>';
    ?>
    

    Is there a decorator to simply cache function return values?

    Ah, just needed to find the right name for this: "Lazy property evaluation".

    I do this a lot too; maybe I'll use that recipe in my code sometime.

    Failed to find 'ANDROID_HOME' environment variable

    For those having a portable SDK edition on windows, simply add the 2 following path to your system.

    F:\ADT_SDK\sdk\platforms
    F:\ADT_SDK\sdk\platform-tools
    

    This worked for me.

    How to load a UIView using a nib file created with Interface Builder

    I made a category that I like:

    UIView+NibInitializer.h

    #import <UIKit/UIKit.h>
    
    @interface UIView (NibInitializer)
    - (instancetype)initWithNibNamed:(NSString *)nibNameOrNil;
    @end
    

    UIView+NibInitializer.m

    #import "UIView+NibInitializer.h"
    
    @implementation UIView (NibInitializer)
    
    - (instancetype)initWithNibNamed:(NSString *)nibNameOrNil
    {
        if (!nibNameOrNil) {
            nibNameOrNil = NSStringFromClass([self class]);
        }
        NSArray *viewsInNib = [[NSBundle mainBundle] loadNibNamed:nibNameOrNil
                                                            owner:self
                                                          options:nil];
        for (id view in viewsInNib) {
            if ([view isKindOfClass:[self class]]) {
                self = view;
                break;
            }
        }
        return self;
    }
    
    @end
    

    Then, call like this:

    MyCustomView *myCustomView = [[MyCustomView alloc] initWithNibNamed:nil];
    

    Use a nib name if your nib is named something other than the name of your class.

    To override it in your subclasses for additional behavior, it could look like this:

    - (instancetype)initWithNibNamed:(NSString *)nibNameOrNil
    {
        self = [super initWithNibNamed:nibNameOrNil];
        if (self) {
            self.layer.cornerRadius = CGRectGetHeight(self.bounds) / 2.0;
        }
        return self;
    }
    

    How to control the line spacing in UILabel

    SWIFT 3 useful extension for set space between lines more easily :)

    extension UILabel
    {
        func setLineHeight(lineHeight: CGFloat)
        {
            let text = self.text
            if let text = text 
            {
    
                let attributeString = NSMutableAttributedString(string: text)
                let style = NSMutableParagraphStyle()
    
               style.lineSpacing = lineHeight
               attributeString.addAttribute(NSParagraphStyleAttributeName,
                                            value: style,
                                            range: NSMakeRange(0, text.characters.count))
    
               self.attributedText = attributeString
            }
        }
    }
    

    How to get unique values in an array

    One Liner, Pure JavaScript

    With ES6 syntax

    list = list.filter((x, i, a) => a.indexOf(x) === i)

    x --> item in array
    i --> index of item
    a --> array reference, (in this case "list")
    

    enter image description here

    With ES5 syntax

    list = list.filter(function (x, i, a) { 
        return a.indexOf(x) === i; 
    });
    

    Browser Compatibility: IE9+

    JQuery DatePicker ReadOnly

    I came up with another solution that is different than what had been proposed. When the date picker is used, it creates a div similar to a pop-up that is positioned when the input field is clicked on. To remove it, I just set the visibility property of the CSS so that it doesn't show up.

    if ($('.yourDatepickerSelector').prop('readonly')) {
        $('#ui-datepicker-div').css({ 'visibility': 'hidden' })
    } else { $('#ui-datepicker-div').css({ 'visibility': 'visible' }) }
    

    This also seems to post correctly to the server, and should not effect any of the settings associated with it.

    Examples of good gotos in C or C++

    I don't use goto's myself, however I did work with a person once that would use them in specific cases. If I remember correctly, his rationale was around performance issues - he also had specific rules for how. Always in the same function, and the label was always BELOW the goto statement.

    Deprecated meaning?

    If there are true answers to those questions, it would be different per software vendor and would be defined by the vendor. I don't know of any true industry standards that are followed with regards to this matter.

    Historically with Microsoft, they'll mark something as deprecated and state they'll remove it in a future version. That can be several versions before they actually get rid of it though.

    Removing trailing newline character from fgets() input

    Perhaps the simplest solution uses one of my favorite little-known functions, strcspn():

    buffer[strcspn(buffer, "\n")] = 0;
    

    If you want it to also handle '\r' (say, if the stream is binary):

    buffer[strcspn(buffer, "\r\n")] = 0; // works for LF, CR, CRLF, LFCR, ...
    

    The function counts the number of characters until it hits a '\r' or a '\n' (in other words, it finds the first '\r' or '\n'). If it doesn't hit anything, it stops at the '\0' (returning the length of the string).

    Note that this works fine even if there is no newline, because strcspn stops at a '\0'. In that case, the entire line is simply replacing '\0' with '\0'.

    How to validate a form with multiple checkboxes to have atleast one checked

    This script below should put you on the right track perhaps?

    You can keep this html the same (though I changed the method to POST):

    <form method="POST" id="subscribeForm">
        <fieldset id="cbgroup">
            <div><input name="list" id="list0" type="checkbox"  value="newsletter0" >zero</div>
            <div><input name="list" id="list1" type="checkbox"  value="newsletter1" >one</div>
            <div><input name="list" id="list2" type="checkbox"  value="newsletter2" >two</div>
        </fieldset>
        <input name="submit" type="submit"  value="submit">
    </form>
    

    and this javascript validates

    function onSubmit() 
    { 
        var fields = $("input[name='list']").serializeArray(); 
        if (fields.length === 0) 
        { 
            alert('nothing selected'); 
            // cancel submit
            return false;
        } 
        else 
        { 
            alert(fields.length + " items selected"); 
        }
    }
    
    // register event on form, not submit button
    $('#subscribeForm').submit(onSubmit)
    

    and you can find a working example of it here

    UPDATE (Oct 2012)
    Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

    UPDATE (May 2013)
    Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

    UPDATE (June 2016)
    Changes == to ===

    The container 'Maven Dependencies' references non existing library - STS

    I'm a little late to the party but I'll give my two cents. I just resolved this issue after spending longer than I'd like on it. The above solutions didn't work for me and here's why:

    there was a network issue when maven was downloading the required repositories so I actually didn't have the right jars. adding a -U to a maven clean install went and got them for me. So if the above solutions aren't working try this:

    1. Right click on your project -> Choose Run as -> 5 Maven build...
    2. In the Goals field type "clean install -U" and select Run
    3. After that completes right click on your project again and choose Maven -> Update Project and click ok.

    Hope it works for you.

    How to get a list of installed android applications and pick one to run

    To get al installed apps you can use Package Manager..

        List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
    

    To run you can use package name

    Intent launchApp = getPackageManager().getLaunchIntentForPackage(“package name”)
    startActivity(launchApp);
    

    For more detail you can read this blog http://codebucket.co.in/android-get-list-of-all-installed-apps/

    Insert variable values in the middle of a string

    I would use a StringBuilder class for doing string manipulation as it will more efficient (being mutable)

    string flights = "Flight A, B,C,D";
    StringBuilder message = new StringBuilder();
    message.Append("Hi We have these flights for you: ");
    message.Append(flights);
    message.Append(" . Which one do you want?");
    

    How to call a PHP function on the click of a button

    Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.

    <?php
        if(array_key_exists('button1', $_POST)) { 
            button1(); 
        } 
        else if(array_key_exists('button2', $_POST)) { 
            button2(); 
        } 
        function button1() { 
            echo "This is Button1 that is selected"; 
        } 
        function button2() { 
            echo "This is Button2 that is selected"; 
        } 
    ?> 
    
    <form method="post"> 
        <input type="submit" name="button1" class="button" value="Button1" /> 
        <input type="submit" name="button2" class="button" value="Button2" /> 
    </form> 
    

    source: geeksforgeeks.org

    python variable NameError

    This should do it:

    #!/usr/local/cpython-2.7/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print "\nHow much space should the random song list occupy?\n" print "1. 100Mb" print "2. 250Mb\n"  tSizeAns = int(raw_input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print "\nYou  want to create a random song list that is {}.".format(tSize) 

    BTW, in case you're open to moving to Python 3.x, the differences are slight:

    #!/usr/local/cpython-3.3/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print("\nHow much space should the random song list occupy?\n") print("1. 100Mb") print("2. 250Mb\n")  tSizeAns = int(input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print("\nYou want to create a random song list that is {}.".format(tSize)) 

    HTH

    How to get Enum Value from index in Java?

    Try this

    Months.values()[index]
    

    How to exit an application properly

    The following code is used in Visual Basic when prompting a user to exit the application:

    Dim D As String
    
    D = MsgBox("Are you sure you want to exit?", vbYesNo+vbQuestion,"Thanking You")
    
    If D =  vbYes Then 
    Unload Me
    Else
    Exit Sub
    End If
    End
    End Sub
    

    Convert pyQt UI to python

    For Ubuntu it works for following commands; If you want individual files to contain main method to run the files individually, may be for testing purpose,

    pyuic5 filename.ui -o filename.py -x
    

    No main method in file, cannot run individually... try

    pyuic5 filename.ui -o filename.py
    

    Consider, I'm using PyQT5.

    Importing variables from another file?

    Marc response is correct. Actually, you can print the memory address for the variables print(hex(id(libvar)) and you can see the addresses are different.

    # mylib.py
    libvar = None
    def lib_method():
        global libvar
        print(hex(id(libvar)))
    
    # myapp.py
    from mylib import libvar, lib_method
    import mylib
    
    lib_method()
    print(hex(id(libvar)))
    print(hex(id(mylib.libvar)))
    

    Stacking DIVs on top of each other?

    To add to Dave's answer:

    div { position: relative; }
    div div { position: absolute; top: 0; left: 0; }
    

    Is using 'var' to declare variables optional?

    They are not the same.

    Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)

    Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)

    Update: ECMAScript 2015

    let was introduced in ECMAScript 2015 to have block scope.

    Can I safely delete contents of Xcode Derived data folder?

    XCODE 7.2 UPDATE

    (Also works for 7.1.1)

    1. Click Window then Projects and then delete Derived Data.

    Like this:

    enter image description here

    And then delete it here:

    enter image description here


    Hope that helps!

    Return Bit Value as 1/0 and NOT True/False in SQL Server

    Try with this script, maybe will be useful:

    SELECT CAST('TRUE' as bit) -- RETURN 1
    SELECT CAST('FALSE' as bit) --RETURN 0
    

    Anyway I always would use a value of 1 or 0 (not TRUE or FALSE). Following your example, the update script would be:

    Update Table Set BitField=CAST('TRUE' as bit) Where ID=1
    

    Read Post Data submitted to ASP.Net Form

    NameValueCollection nvclc = Request.Form;
    string   uName= nvclc ["txtUserName"];
    string   pswod= nvclc ["txtPassword"];
    //try login
    CheckLogin(uName, pswod);
    

    My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

    Cocoapods (0.39.0.beta.4) was the issue for me so I moved to Carthage.

    Left align and right align within div in Bootstrap

    We can achieve by Bootstrap 4 Flexbox:

    <div class="d-flex justify-content-between w-100">
    <p>TotalCost</p> <p>$42</p>
    </div>
    
    d-flex // Display Flex
    justify-content-between // justify-content:space-between
    w-100 // width:100%
    

    Example: JSFiddle

    How to call python script on excel vba?

    I just came across this old post. Nothing listed above actually worked for me. I tested the script below, and it worked fine on my system. Sharing here, for the benefit of others who come here after me.

    Sub RunPython()
    
    Dim objShell As Object
    Dim PythonExe, PythonScript As String
    
        Set objShell = VBA.CreateObject("Wscript.Shell")
    
        PythonExe = """C:\your_path\Python\Python38\python.exe"""
        PythonScript = "C:\your_path\from_vba.py"
    
        objShell.Run PythonExe & PythonScript
    
    End Sub
    

    How to center buttons in Twitter Bootstrap 3?

    I had this problem. I used

    <div class = "col-xs-8 text-center">
    

    On my div containing a few h3 lines, a couple h4 lines and a Bootstrap button. Everything besides the button jumped to the center after I used text-center so I went into my CSS sheet overriding Bootstrap and gave the button a

    margin: auto;
    

    which seems to have solved the problem.

    How to use subprocess popen Python

    It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can do the correct tokenization for args (I'm using Blender's example of the call):

    import shlex
    from subprocess import Popen, PIPE
    command = shlex.split('swfdump /tmp/filename.swf/ -d')
    process = Popen(command, stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate()
    

    https://docs.python.org/3/library/subprocess.html

    Remove HTML tags from a String

    Remove HTML tags from string. Somewhere we need to parse some string which is received by some responses like Httpresponse from the server.

    So we need to parse it.

    Here I will show how to remove html tags from string.

        // sample text with tags
    
        string str = "<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>";
    
    
    
        // regex which match tags
    
        System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");
    
    
    
        // replace all matches with empty strin
    
        str = rx.Replace(str, "");
    
    
    
        //now str contains string without html tags
    

    Apache Spark: The number of cores vs. the number of executors

    I think one of the major reasons is locality. Your input file size is 165G, the file's related blocks certainly distributed over multiple DataNodes, more executors can avoid network copy.

    Try to set executor num equal blocks count, i think can be faster.

    How to use setprecision in C++

    #include <iostream>
    #include <iomanip>
    using namespace std;
    

    You can enter the line using namespace std; for your convenience. Otherwise, you'll have to explicitly add std:: every time you wish to use cout, fixed, showpoint, setprecision(2) and endl

    int main()
    {
        double num1 = 3.12345678;
        cout << fixed << showpoint;
        cout << setprecision(2);
        cout << num1 << endl;
    return 0;
    }
    

    How to set the "Content-Type ... charset" in the request header using a HTML link

    This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

    To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


    Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

    alt text

    SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

    SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.

    create table test (
      id integer not null,
      ts datetime not null
      );
    
    insert into test values (1, '2012-01-01 08:00');
    insert into test values (1, '2012-01-01 09:00');
    insert into test values (1, '2012-01-01 08:30');
    insert into test values (2, '2012-01-01 08:30');
    insert into test values (2, '2012-01-01 10:30');
    insert into test values (2, '2012-01-01 09:00');
    insert into test values (3, '2012-01-01 09:00');
    insert into test values (3, '2012-01-02 12:00');
    

    Values were chosen in such a way that for

    • id = 1, elapsed time is 1 hour
    • id = 2, elapsed time is 2 hours, and
    • id = 3, elapsed time is 3 hours.

    This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.

    select t.id,
           min(ts) start_time,
           max(ts) end_time,
           datediff(second, min(ts),max(ts)) elapsed_sec,
           convert(varchar, max(ts) - min(ts), 108) do_not_use
    from test t
    group by t.id;
    
    ID  START_TIME                 END_TIME                   ELAPSED_SEC  DO_NOT_USE
    1   January, 01 2012 08:00:00  January, 01 2012 09:00:00  3600         01:00:00
    2   January, 01 2012 08:30:00  January, 01 2012 10:30:00  7200         02:00:00
    3   January, 01 2012 09:00:00  January, 02 2012 12:00:00  97200        03:00:00
    

    Note the misleading "03:00:00" for the 27-hour difference on id number 3.

    Function to format elapsed time in SQL Server

    Why does CSS not support negative padding?

    I recently answered a different question where I discussed why the box model is the way it is.

    There are specific reasons for each part of the box model. Padding is meant to extend the background beyond its contents. If you need to shrink the background of the container, you should make the parent container the correct size and give the child element some negative margins. In this case the content is not being padded, it's overflowing.

    Excel 2010 VBA Referencing Specific Cells in other worksheets

    Private Sub Click_Click()
    
     Dim vaFiles As Variant
     Dim i As Long
    
    For j = 1 To 2
    vaFiles = Application.GetOpenFilename _
         (FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
         Title:="Open File(s)", MultiSelect:=True)
    
    If Not IsArray(vaFiles) Then Exit Sub
    
     With Application
      .ScreenUpdating = False
      For i = 1 To UBound(vaFiles)
         Workbooks.Open vaFiles(i)
         wrkbk_name = vaFiles(i)
        Next i
      .ScreenUpdating = True
    End With
    
    If j = 1 Then
    work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
    Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
    End If
    
    
    
    Next j
    
    'Filling the values of the group name
    
    'check = Application.WorksheetFunction.Search(Name, work1)
    check = InStr(UCase("Qoute Request"), work1)
    
    If check = 1 Then
    Application.Workbooks(work1).Activate
    Else
    Application.Workbooks(work2).Activate
    End If
    
    ActiveWorkbook.Sheets("GI Quote Request").Select
    ActiveSheet.Range("B4:C12").Copy
    Application.Workbooks("Model").Activate
    ActiveWorkbook.Sheets("Request").Range("K3").Select
    ActiveSheet.Paste
    
    
    Application.Workbooks("Model").Activate
    ActiveWorkbook.Sheets("Request").Select
    
    Range("D3").Value = Range("L3").Value
    Range("D7").Value = Range("L9").Value
    Range("D11").Value = Range("L7").Value
    
    For i = 4 To 5
    
    If i = 5 Then
    GoTo NextIteration
    End If
    
    If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
        ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
     End If
    
    NextIteration:
    Next i
    
    'eligibles part
    Count = Range("D11").Value
    For i = 27 To Count + 24
    Range("C" & i).EntireRow.Offset(1, 0).Insert
    Next i
    
    check = Left(work1, InStrRev(work1, ".") - 1)
    
    'check = InStr("Census", work1)
    If check = "Census" Then
    workbk = work1
    Application.Workbooks(work1).Activate
    Else
    Application.Workbooks(work2).Activate
    workbk = work2
    End If
    
    'DOB
    ActiveWorkbook.Sheets("Sheet1").Select
    ActiveSheet.Range("D2").Select
    ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    
    Application.Workbooks("Model").Activate
    ActiveWorkbook.Sheets("Request").Select
    ActiveSheet.Range("C27").Select
    ActiveSheet.Paste
    
    'Gender
    Application.Workbooks(workbk).Activate
    ActiveWorkbook.Sheets("Sheet1").Select
    ActiveSheet.Range("C2").Select
    ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    
    Application.Workbooks("Model").Activate
    ActiveWorkbook.Sheets("Request").Select
    'Application.CutCopyMode = False
    
    ActiveSheet.Range("k27").Select
    ActiveSheet.Paste
    
    For i = 27 To Count + 27
    ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
    Next i
    
    'Salary
    Application.Workbooks(workbk).Activate
    ActiveWorkbook.Sheets("Sheet1").Select
    ActiveSheet.Range("N2").Select
    ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    
    Application.Workbooks("Model").Activate
    ActiveWorkbook.Sheets("Request").Select
    'Application.CutCopyMode = False
    
    ActiveSheet.Range("F27").Select
    ActiveSheet.Paste
    
    
    ActiveSheet.Range("K3:L" & Count).Select
    selction.ClearContents
    End Sub
    

    How to trap on UIViewAlertForUnsatisfiableConstraints?

    Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.

    How do you detect where two line segments intersect?

    Python version of iMalc's answer:

    def find_intersection( p0, p1, p2, p3 ) :
    
        s10_x = p1[0] - p0[0]
        s10_y = p1[1] - p0[1]
        s32_x = p3[0] - p2[0]
        s32_y = p3[1] - p2[1]
    
        denom = s10_x * s32_y - s32_x * s10_y
    
        if denom == 0 : return None # collinear
    
        denom_is_positive = denom > 0
    
        s02_x = p0[0] - p2[0]
        s02_y = p0[1] - p2[1]
    
        s_numer = s10_x * s02_y - s10_y * s02_x
    
        if (s_numer < 0) == denom_is_positive : return None # no collision
    
        t_numer = s32_x * s02_y - s32_y * s02_x
    
        if (t_numer < 0) == denom_is_positive : return None # no collision
    
        if (s_numer > denom) == denom_is_positive or (t_numer > denom) == denom_is_positive : return None # no collision
    
    
        # collision detected
    
        t = t_numer / denom
    
        intersection_point = [ p0[0] + (t * s10_x), p0[1] + (t * s10_y) ]
    
    
        return intersection_point
    

    What does 'public static void' mean in Java?

    It means three things.

    First public means that any other object can access it.

    static means that the class in which it resides doesn't have to be instantiated first before the function can be called.

    void means that the function does not return a value.

    Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).

    Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away. Get a broad overview of the fundamentals, then go back and worry about the details. The reason is that you have to use some things (like public static void) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first. So, for the moment, just accept that that's the way it's done, and move on. You will understand them shortly.

    Is there an upside down caret character?

    Could you just draw an svg path inside of a span using document.write? The span isn't required for the svg to work, it just ensures that the svg remains inline with whatever text the carat is next to. I used margin-bottom to vertically center it with the text, there might be another way to do that though. This is what I did on my blog's side nav (minus the js). If you don't have text next to it you wouldn't need the span or the margin-bottom offset.

    <div id="ID"></div>
    
    <script type="text/javascript">
    var x = document.getElementById('ID');
    
    // your "margin-bottom" is the negative of 1/2 of the font size (in this example the font size is 16px)
    // change the "stroke=" to whatever color your font is too
    x.innerHTML = document.write = '<span><svg style="margin-bottom: -8px; height: 30px; width: 25px;" viewBox="0,0,100,50"><path fill="transparent" stroke-width="4" stroke="black" d="M20 10 L50 40 L80 10"/></svg></span>';
    </script>
    

    JavaScript: Get image dimensions

    if you have image file from your input form. you can use like this

    let images = new Image();
    images.onload = () => {
     console.log("Image Size", images.width, images.height)
    }
    images.onerror = () => result(true);
    
    let fileReader = new FileReader();
    fileReader.onload = () => images.src = fileReader.result;
    fileReader.onerror = () => result(false);
    if (fileTarget) {
       fileReader.readAsDataURL(fileTarget);
    }
    

    OnclientClick and OnClick is not working at the same time?

    Your JavaScript is fine, unless you have other scripts running on this page which may corrupt everything. You may check this using Firebug.

    I've now tested a bit and it really seems that ASP.net ignores disabled controls. Basically the postback is issued, but probably the framework ignores such events since it "assumes" that a disabled button cannot raise any postback and so it ignores possibly attached handlers. Now this is just my personal reasoning, one could use Reflector to check this in more depth.

    As a solution you could really try to do the disabling at a later point, basically you delay the control.disabled = "disabled" call using a JavaTimer or some other functionality. In this way 1st the postback to the server is issued before the control is being disabled by the JavaScript function. Didn't test this but it could work

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

    Unicode is not equal to UTF-8. The latter is just an encoding for the former.

    You are doing it the wrong way around. You are reading UTF-8-encoded data, so you have to decode the UTF-8-encoded String into a unicode string.

    So just replace .encode with .decode, and it should work (if your .csv is UTF-8-encoded).

    Nothing to be ashamed of, though. I bet 3 in 5 programmers had trouble at first understanding this, if not more ;)

    Update: If your input data is not UTF-8 encoded, then you have to .decode() with the appropriate encoding, of course. If nothing is given, python assumes ASCII, which obviously fails on non-ASCII-characters.

    "Comparison method violates its general contract!"

    Java does not check consistency in a strict sense, only notifies you if it runs into serious trouble. Also it does not give you much information from the error.

    I was puzzled with what's happening in my sorter and made a strict consistencyChecker, maybe this will help you:

    /**
     * @param dailyReports
     * @param comparator
     */
    public static <T> void checkConsitency(final List<T> dailyReports, final Comparator<T> comparator) {
      final Map<T, List<T>> objectMapSmallerOnes = new HashMap<T, List<T>>();
    
      iterateDistinctPairs(dailyReports.iterator(), new IPairIteratorCallback<T>() {
        /**
         * @param o1
         * @param o2
         */
        @Override
        public void pair(T o1, T o2) {
          final int diff = comparator.compare(o1, o2);
          if (diff < Compare.EQUAL) {
            checkConsistency(objectMapSmallerOnes, o1, o2);
            getListSafely(objectMapSmallerOnes, o2).add(o1);
          } else if (Compare.EQUAL < diff) {
            checkConsistency(objectMapSmallerOnes, o2, o1);
            getListSafely(objectMapSmallerOnes, o1).add(o2);
          } else {
            throw new IllegalStateException("Equals not expected?");
          }
        }
      });
    }
    
    /**
     * @param objectMapSmallerOnes
     * @param o1
     * @param o2
     */
    static <T> void checkConsistency(final Map<T, List<T>> objectMapSmallerOnes, T o1, T o2) {
      final List<T> smallerThan = objectMapSmallerOnes.get(o1);
    
      if (smallerThan != null) {
        for (final T o : smallerThan) {
          if (o == o2) {
            throw new IllegalStateException(o2 + "  cannot be smaller than " + o1 + " if it's supposed to be vice versa.");
          }
          checkConsistency(objectMapSmallerOnes, o, o2);
        }
      }
    }
    
    /**
     * @param keyMapValues 
     * @param key 
     * @param <Key> 
     * @param <Value> 
     * @return List<Value>
     */ 
    public static <Key, Value> List<Value> getListSafely(Map<Key, List<Value>> keyMapValues, Key key) {
      List<Value> values = keyMapValues.get(key);
    
      if (values == null) {
        keyMapValues.put(key, values = new LinkedList<Value>());
      }
    
      return values;
    }
    
    /**
     * @author Oku
     *
     * @param <T>
     */
    public interface IPairIteratorCallback<T> {
      /**
       * @param o1
       * @param o2
       */
      void pair(T o1, T o2);
    }
    
    /**
     * 
     * Iterates through each distinct unordered pair formed by the elements of a given iterator
     *
     * @param it
     * @param callback
     */
    public static <T> void iterateDistinctPairs(final Iterator<T> it, IPairIteratorCallback<T> callback) {
      List<T> list = Convert.toMinimumArrayList(new Iterable<T>() {
    
        @Override
        public Iterator<T> iterator() {
          return it;
        }
    
      });
    
      for (int outerIndex = 0; outerIndex < list.size() - 1; outerIndex++) {
        for (int innerIndex = outerIndex + 1; innerIndex < list.size(); innerIndex++) {
          callback.pair(list.get(outerIndex), list.get(innerIndex));
        }
      }
    }
    

    Style disabled button with CSS

    I think you should be able to select a disabled button using the following:

    button[disabled=disabled], button:disabled {
        // your css rules
    }
    

    Using Pip to install packages to Anaconda Environment

    For others who run into this situation, I found this to be the most straightforward solution:

    1. Run conda create -n venv_name and source activate venv_name, where venv_name is the name of your virtual environment.

    2. Run conda install pip. This will install pip to your venv directory.

    3. Find your anaconda directory, and find the actual venv folder. It should be somewhere like /anaconda/envs/venv_name/.

    4. Install new packages by doing /anaconda/envs/venv_name/bin/pip install package_name.

    This should now successfully install packages using that virtual environment's pip!

    Using two CSS classes on one element

    I know this post is getting outdated, but here's what they asked. In your style sheet:

    .social {
        width: 330px;
        height: 75px;
        float: right;
        text-align: left;
        padding: 10px 0;
        border-bottom: dotted 1px #6d6d6d;
    }
    [class~="first"] {
        padding-top:0;
    }
    [class~="last"] {
        border:0;
    }
    

    But it may be a bad way to use selectors. Also, if you need multiple "first" extension, you'll have to be sure to set different name, or to refine your selector.

    [class="social first"] {...}
    

    I hope this will help someone, it can be pretty handy in some situation.

    For exemple, if you have a tiny piece of css that has to be linked to many different components, and you don't want to write a hundred time the same code.

    div.myClass1 {font-weight:bold;}
    div.myClass2 {font-style:italic;}
    ...
    div.myClassN {text-shadow:silver 1px 1px 1px;}
    
    div.myClass1.red {color:red;}
    div.myClass2.red {color:red;}
    ...
    div.myClassN.red {color:red;}
    

    Becomes:

    div.myClass1 {font-weight:bold;}
    div.myClass2 {font-style:italic;}
    ...
    div.myClassN {text-shadow:silver 1px 1px 1px;}
    
    [class~=red] {color:red;}
    

    How to Free Inode Usage?

    eaccelerator could be causing the problem since it compiles PHP into blocks...I've had this problem with an Amazon AWS server on a site with heavy load. Free up Inodes by deleting the eaccelerator cache in /var/cache/eaccelerator if you continue to have issues.

    rm -rf /var/cache/eaccelerator/*
    

    (or whatever your cache dir)

    Draw a curve with css

    @Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

    _x000D_
    _x000D_
    .box {_x000D_
      width: 500px;_x000D_
      height: 100px;_x000D_
      border: solid 5px #000;_x000D_
      border-color: transparent transparent #000 transparent;_x000D_
      border-radius: 0 0 240px 50%/60px;_x000D_
    }
    _x000D_
    <div class="box"></div>
    _x000D_
    _x000D_
    _x000D_

    In jQuery, what's the best way of formatting a number to 2 decimal places?

    Maybe something like this, where you could select more than one element if you'd like?

    $("#number").each(function(){
        $(this).val(parseFloat($(this).val()).toFixed(2));
    });
    

    What should main() return in C and C++?

    Standard C — Hosted Environment

    For a hosted environment (that's the normal one), the C11 standard (ISO/IEC 9899:2011) says:

    5.1.2.2.1 Program startup

    The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ }
    

    or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
    

    or equivalent;10) or in some other implementation-defined manner.

    If they are declared, the parameters to the main function shall obey the following constraints:

    • The value of argc shall be nonnegative.
    • argv[argc] shall be a null pointer.
    • If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
    • If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
    • The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

    10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and so on.

    Program termination in C99 or C11

    The value returned from main() is transmitted to the 'environment' in an implementation-defined way.

    5.1.2.2.3 Program termination

    1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

    11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main will have ended in the former case, even where they would not have in the latter.

    Note that 0 is mandated as 'success'. You can use EXIT_FAILURE and EXIT_SUCCESS from <stdlib.h> if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.

    In C89 (and hence in Microsoft C), there is no statement about what happens if the main() function returns but does not specify a return value; it therefore leads to undefined behaviour.

    7.22.4.4 The exit function

    ¶5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

    Standard C++ — Hosted Environment

    The C++11 standard (ISO/IEC 14882:2011) says:

    3.6.1 Main function [basic.start.main]

    ¶1 A program shall contain a global function called main, which is the designated start of the program. [...]

    ¶2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ... */ }
    

    and

    int main(int argc, char* argv[]) { /* ... */ }
    

    In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc] shall be 0. [ Note: It is recommended that any further (optional) parameters be added after argv. —end note ]

    ¶3 The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. [...]

    ¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

    return 0;
    

    The C++ standard explicitly says "It [the main function] shall have a return type of type int, but otherwise its type is implementation defined", and requires the same two signatures as the C standard to be supported as options. So a 'void main()' is directly not allowed by the C++ standard, though there's nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling main (but the C standard does not).

    There's a paragraph of §18.5 Start and termination in the C++11 standard that is identical to the paragraph from §7.22.4.4 The exit function in the C11 standard (quoted above), apart from a footnote (which simply documents that EXIT_SUCCESS and EXIT_FAILURE are defined in <cstdlib>).

    Standard C — Common Extension

    Classically, Unix systems support a third variant:

    int main(int argc, char **argv, char **envp) { ... }
    

    The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via 'extern char **environ;'. This global variable is unique among those in POSIX in that it does not have a header that declares it.

    This is recognized by the C standard as a common extension, documented in Annex J:

    J.5.1 Environment arguments

    ¶1 In a hosted environment, the main function receives a third argument, char *envp[], that points to a null-terminated array of pointers to char, each of which points to a string that provides information about the environment for this execution of the program (5.1.2.2.1).

    Microsoft C

    The Microsoft VS 2010 compiler is interesting. The web site says:

    The declaration syntax for main is

     int main();
    

    or, optionally,

    int main(int argc, char *argv[], char *envp[]);
    

    Alternatively, the main and wmain functions can be declared as returning void (no return value). If you declare main or wmain as returning void, you cannot return an exit code to the parent process or operating system by using a return statement. To return an exit code when main or wmain is declared as void, you must use the exit function.

    It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with void main() does exit — and the MS web site is silent too.

    Interestingly, MS does not prescribe the two-argument version of main() that the C and C++ standards require. It only prescribes a three argument form where the third argument is char **envp, a pointer to a list of environment variables.

    The Microsoft page also lists some other alternatives — wmain() which takes wide character strings, and some more.

    The Microsoft Visual Studio 2005 version of this page does not list void main() as an alternative. The versions from Microsoft Visual Studio 2008 onwards do.

    Standard C — Freestanding Environment

    As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called main and there are no constraints on its return type. The standard says:

    5.1.2 Execution environments

    Two execution environments are defined: freestanding and hosted. In both cases, program startup occurs when a designated C function is called by the execution environment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.

    5.1.2.1 Freestanding environment

    In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.

    The effect of program termination in a freestanding environment is implementation-defined.

    The cross-reference to clause 4 Conformance refers to this:

    ¶5 A strictly conforming program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.

    ¶6 The two forms of conforming implementation are hosted and freestanding. A conforming hosted implementation shall accept any strictly conforming program. A conforming freestanding implementation shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers <float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>, and <stdnoreturn.h>. A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any strictly conforming program.4)

    ¶7 A conforming program is one that is acceptable to a conforming implementation.5)

    3) A strictly conforming program can use conditional features (see 6.10.8.3) provided the use is guarded by an appropriate conditional inclusion preprocessing directive using the related macro. For example:

    #ifdef __STDC_IEC_559__ /* FE_UPWARD defined */
        /* ... */
        fesetround(FE_UPWARD);
        /* ... */
    #endif
    

    4) This implies that a conforming implementation reserves no identifiers other than those explicitly reserved in this International Standard.

    5) Strictly conforming programs are intended to be maximally portable among conforming implementations. Conforming programs may depend upon non-portable features of a conforming implementation.

    It is noticeable that the only header required of a freestanding environment that actually defines any functions is <stdarg.h> (and even those may be — and often are — just macros).

    Standard C++ — Freestanding Environment

    Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.)

    1.4 Implementation compliance [intro.compliance]

    ¶7 Two kinds of implementations are defined: a hosted implementation and a freestanding implementation. For a hosted implementation, this International Standard defines the set of available libraries. A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries (17.6.1.3).

    ¶8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.

    ¶9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.3

    3) This documentation also defines implementation-defined behavior; see 1.9.

    17.6.1.3 Freestanding implementations [compliance]

    Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.

    A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.

    The supplied version of the header <cstdlib> shall declare at least the functions abort, atexit, at_quick_exit, exit, and quick_exit (18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.

    Table 16 — C++ headers for freestanding implementations

    Subclause                           Header(s)
                                        <ciso646>
    18.2  Types                         <cstddef>
    18.3  Implementation properties     <cfloat> <limits> <climits>
    18.4  Integer types                 <cstdint>
    18.5  Start and termination         <cstdlib>
    18.6  Dynamic memory management     <new>
    18.7  Type identification           <typeinfo>
    18.8  Exception handling            <exception>
    18.9  Initializer lists             <initializer_list>
    18.10 Other runtime support         <cstdalign> <cstdarg> <cstdbool>
    20.9  Type traits                   <type_traits>
    29    Atomics                       <atomic>
    

    What about using int main() in C?

    The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — int main(void) — but there are also two examples in the standard which show int main(): §6.5.3.4 ¶8 and §6.7.6.3 ¶20. Now, it is important to note that examples are not 'normative'; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes int main() in an example, it suggests that int main() is not forbidden, even if it is not the preferred notation.

    6.5.3.4 The sizeof and _Alignof operators

    …

    ¶8 EXAMPLE 3 In this example, the size of a variable length array is computed and returned from a function:

    #include <stddef.h>
    
    size_t fsize3(int n)
    {
        char b[n+3]; // variable length array
        return sizeof b; // execution time sizeof
    }
    int main()
    {
        size_t size;
        size = fsize3(10); // fsize3 returns 13
        return 0;
    }
    

    Deploying my application at the root in Tomcat

    You have a couple of options:

    1. Remove the out-of-the-box ROOT/ directory from tomcat and rename your war file to ROOT.war before deploying it.

    2. Deploy your war as (from your example) war_name.war and configure the context root in conf/server.xml to use your war file :

      <Context path="" docBase="war_name" debug="0" reloadable="true"></Context>
      

    The first one is easier, but a little more kludgy. The second one is probably the more elegant way to do it.

    How to view the SQL queries issued by JPA?

    If you use hibernate and logback as your logger you could use the following (shows only the bindings and not the results):

    <appender
        name="STDOUT"
        class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -
                %msg%n</pattern>
        </encoder>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>return message.toLowerCase().contains("org.hibernate.type") &amp;&amp;
                    logger.startsWith("returning");</expression>
            </evaluator>
            <OnMismatch>NEUTRAL</OnMismatch>
            <OnMatch>DENY</OnMatch>
        </filter>
    </appender>
    

    org.hibernate.SQL=DEBUG prints the Query

    <logger name="org.hibernate.SQL">
        <level value="DEBUG" />
    </logger>
    

    org.hibernate.type=TRACE prints the bindings and normally the results, which will be suppressed thru the custom filter

    <logger name="org.hibernate.type">
        <level value="TRACE" />
    </logger>
    

    You need the janino dependency (http://logback.qos.ch/manual/filters.html#JaninoEventEvaluator):

    <dependency>
        <groupId>org.codehaus.janino</groupId>
        <artifactId>janino</artifactId>
        <version>2.6.1</version>
    </dependency>
    

    Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

    Your target SDK might be higher than SDK of the device, change that. For example, your device is running API 23 but your target SDK is 25. Change 25 to 23.

    Sending mass email using PHP

    First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers

    I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).

    querySelector, wildcard element match?

    Set the tagName as an explicit attribute:

    for(var i=0,els=document.querySelectorAll('*'); i<els.length;
              els[i].setAttribute('tagName',els[i++].tagName) );
    

    I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.

    document.querySelectorAll('[tagName$="_Sequence"]')
    

    I didn't say it would be pretty :) PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.

    Zero an array in C code

    int arr[20];
    memset(arr, 0, sizeof arr);
    

    See the reference for memset

    How to remove a field completely from a MongoDB document?

    The solution for PyMongo (Python mongo):

    db.example.update({}, {'$unset': {'tags.words':1}}, multi=True);
    

    Java RegEx meta character (.) and ordinary dot?

    Escape special characters with a backslash. \., \*, \+, \\d, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.

    How to display binary data as image - extjs 4

    In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:

    <img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
    

    my-image is a binary image file. This will load just fine.

    Set HTML dropdown selected option using JSTL

    In Servlet do:

    String selectedRole = "rat"; // Or "cat" or whatever you'd like.
    request.setAttribute("selectedRole", selectedRole);
    

    Then in JSP do:

    <select name="roleName">
        <c:forEach items="${roleNames}" var="role">
            <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
        </c:forEach>
    </select>
    

    It will print the selected attribute of the HTML <option> element so that you end up like:

    <select name="roleName">
        <option value="cat">cat</option>
        <option value="rat" selected>rat</option>
        <option value="unicorn">unicorn</option>
    </select>
    

    Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

    $(document).ready shorthand

    The correct shorthand is this:

    $(function() {
        // this behaves as if within document.ready
    });
    

    The code you posted…

    (function($){
    
    //some code
    
    })(jQuery);
    

    …creates an anonymous function and executes it immediately with jQuery being passed in as the arg $. All it effectively does is take the code inside the function and execute it like normal, since $ is already an alias for jQuery. :D

    jquery find closest previous sibling with class

    I think all the answers are lacking something. I prefer using something like this

    $('li.current_sub').prevUntil("li.par_cat").prev();
    

    Saves you not adding :first inside the selector and is easier to read and understand. prevUntil() method has a better performance as well rather than using prevAll()

    phpmyadmin.pma_table_uiprefs doesn't exist

    Steps:

    • Just download create_table.sql from GitHub and save that file in your system.
    • Then go to your phpMyAdmin.
    • And click on Import from upper tab.
    • At last select create_table.sql and upload that.

    After all it works for me and hopefully work for you.

    How can I store the result of a system command in a Perl variable?

    Use backticks for system commands, which helps to store their results into Perl variables.

    my $pid = 5892;
    my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; 
    print "not = $not\n";
    

    How to add title to seaborn boxplot

    Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

    sns.boxplot('Day', 'Count', data= gg).set_title('lalala')
    

    A complete example would be:

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    tips = sns.load_dataset("tips")
    sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")
    
    plt.show()
    

    Of course you could also use the returned axes instance to make it more readable:

    ax = sns.boxplot('Day', 'Count', data= gg)
    ax.set_title('lalala')
    ax.set_ylabel('lololo')
    

    How to POST a FORM from HTML to ASPX page

    You sure can.

    The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.

    Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.

    How do I find all of the symlinks in a directory tree?

    What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

    you could make one lsl ls -lR | grep ^l

    Just chmod them +x and you are good to go.

    Use URI builder in Android or create URL with variables

    Best answer: https://stackoverflow.com/a/19168199/413127

    Example for

     http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
    

    Now with Kotlin

     val myUrl = Uri.Builder().apply {
            scheme("https")
            authority("www.myawesomesite.com")
            appendPath("turtles")
            appendPath("types")
            appendQueryParameter("type", "1")
            appendQueryParameter("sort", "relevance")
            fragment("section-name")
            build()            
        }.toString()
    

    How do I output the difference between two specific revisions in Subversion?

    To compare entire revisions, it's simply:

    svn diff -r 8979:11390


    If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

    svn diff -r PREV:HEAD

    (Note, without anything specified afterwards, all files in the specified revisions are compared.)


    You can compare a specific file if you add the file path afterwards:

    svn diff -r 8979:HEAD /path/to/my/file.php

    Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

    First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

    For example,

    > z <- factor(letters[c(3, 2, 3, 4)])
    
    # human-friendly display, but internal structure is invisible
    > z
    [1] c b c d
    Levels: b c d
    
    # internal structure of factor
    > unclass(z)
    [1] 2 1 2 3
    attr(,"levels")
    [1] "b" "c" "d"
    

    here, z has 4 elements.
    The index is 2, 1, 2, 3 in that order.
    The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

    Then, as.numeric converts simply the index part of factor into numeric.
    as.character handles the index and levels, and generates character vector expressed by its level.

    ?as.numeric says that Factors are handled by the default method.

    Django request.GET

    Here is a good way to do it.

    from django.utils.datastructures import MultiValueDictKeyError
    try:
        message = 'You submitted: %r' % request.GET['q']
    except MultiValueDictKeyError:
        message = 'You submitted nothing!'
    

    You don't need to check again if q is in GET request. The call in the QueryDict.get already does that to you.

    How are POST and GET variables handled in Python?

    I've found nosklo's answer very extensive and useful! For those, like myself, who might find accessing the raw request data directly also useful, I would like to add the way to do that:

    import os, sys
    
    # the query string, which contains the raw GET data
    # (For example, for http://example.com/myscript.py?a=b&c=d&e
    # this is "a=b&c=d&e")
    os.getenv("QUERY_STRING")
    
    # the raw POST data
    sys.stdin.read()
    

    Vertical Tabs with JQuery?

    Try here:

    http://www.sunsean.com/idTabs/

    A look at the Freedom tab might have what you need.

    Let me know if you find something you like. I worked on the exact same problem a few months ago and decided to implement myself. I like what I did, but it might have been nice to use a standard library.

    how to rename an index in a cluster?

    As such there is no direct method to copy or rename index in ES (I did search extensively for my own project)

    However a very easy option is to use a popular migration tool [Elastic-Exporter].

    http://www.retailmenot.com/corp/eng/posts/2014/12/02/elasticsearch-cluster-migration/

    [PS: this is not my blog, just stumbled upon and found it good]

    Thereby you can copy index/type and then delete the old one.

    How to stop docker under Linux

    The output of ps aux looks like you did not start docker through systemd/systemctl.

    It looks like you started it with:

    sudo dockerd -H gridsim1103:2376
    

    When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.

    The correct way to start docker is to use systemd/systemctl:

    systemctl enable docker
    systemctl start docker
    

    After this, docker should start on system start.

    EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.

    In Rails, how do you render JSON using a view?

    This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder

    Finding all objects that have a given property inside a collection

    Sounds a lot like something you would use LINQ for in .NET

    While there's no "real" LINQ implementation for java yet, you might want to have a look at Quaere which could do what you describe easily enough.

    How to create/make rounded corner buttons in WPF?

    <Button x:Name="btnBack" Grid.Row="2" Width="300"
                            Click="btnBack_Click">
                    <Button.Template>
                        <ControlTemplate>
                            <Border CornerRadius="10" Background="#463190">
                                <TextBlock Text="Retry" Foreground="White" 
                                           HorizontalAlignment="Center"                                           
                                           Margin="0,5,0,0"
                                           Height="40"
                                           FontSize="20"></TextBlock>
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
    

    This is working fine for me.

    How to solve error message: "Failed to map the path '/'."

    Just start cmd and run the command iisreset and error will be gone.

    ALTER TABLE, set null in not null column, PostgreSQL 9.1

    ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
    

    More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

    How to return result of a SELECT inside a function in PostgreSQL?

    Hi please check the below link

    https://www.postgresql.org/docs/current/xfunc-sql.html

    EX:

    CREATE FUNCTION sum_n_product_with_tab (x int)
    RETURNS TABLE(sum int, product int) AS $$
        SELECT $1 + tab.y, $1 * tab.y FROM tab;
    $$ LANGUAGE SQL;
    

    Get IP address of an interface on Linux

    In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.

    What is %timeit in python?

    Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

    How do I clear my Jenkins/Hudson build history?

    Go to "Manage Jenkins" > "Script Console"

    Run below:

    def jobName = "build_name"  
    def job = Jenkins.instance.getItem(jobName)  
    job.getBuilds().each { it.delete() }  
    job.save()
    

    Visual Studio 2013 License Product Key

    I solved this, without having to completely reinstall Visual Studio 2013.

    For those who may come across this in the future, the following steps worked for me:

    1. Run the ISO (or vs_professional.exe).
    2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

      • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

      • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

        HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

      • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

      • Exit the registry

    3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

      Visual Studio Repair button

      • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
    4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

    5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


    Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

    License: Product key applied

    Hope this helps somebody in the future!

    Reference blog 'story'

    ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

    Pickle uses different protocols to convert your data to a binary stream.

    You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

    How to upload a file to directory in S3 bucket using boto

    For upload folder example as following code and S3 folder picture enter image description here

    import boto
    import boto.s3
    import boto.s3.connection
    import os.path
    import sys    
    
    # Fill in info on data to upload
    # destination bucket name
    bucket_name = 'willie20181121'
    # source directory
    sourceDir = '/home/willie/Desktop/x/'  #Linux Path
    # destination directory name (on s3)
    destDir = '/test1/'   #S3 Path
    
    #max size in bytes before uploading in parts. between 1 and 5 GB recommended
    MAX_SIZE = 20 * 1000 * 1000
    #size of parts when uploading in parts
    PART_SIZE = 6 * 1000 * 1000
    
    access_key = 'MPBVAQ*******IT****'
    secret_key = '11t63yDV***********HgUcgMOSN*****'
    
    conn = boto.connect_s3(
            aws_access_key_id = access_key,
            aws_secret_access_key = secret_key,
            host = '******.org.tw',
            is_secure=False,               # uncomment if you are not using ssl
            calling_format = boto.s3.connection.OrdinaryCallingFormat(),
            )
    bucket = conn.create_bucket(bucket_name,
            location=boto.s3.connection.Location.DEFAULT)
    
    
    uploadFileNames = []
    for (sourceDir, dirname, filename) in os.walk(sourceDir):
        uploadFileNames.extend(filename)
        break
    
    def percent_cb(complete, total):
        sys.stdout.write('.')
        sys.stdout.flush()
    
    for filename in uploadFileNames:
        sourcepath = os.path.join(sourceDir + filename)
        destpath = os.path.join(destDir, filename)
        print ('Uploading %s to Amazon S3 bucket %s' % \
               (sourcepath, bucket_name))
    
        filesize = os.path.getsize(sourcepath)
        if filesize > MAX_SIZE:
            print ("multipart upload")
            mp = bucket.initiate_multipart_upload(destpath)
            fp = open(sourcepath,'rb')
            fp_num = 0
            while (fp.tell() < filesize):
                fp_num += 1
                print ("uploading part %i" %fp_num)
                mp.upload_part_from_file(fp, fp_num, cb=percent_cb, num_cb=10, size=PART_SIZE)
    
            mp.complete_upload()
    
        else:
            print ("singlepart upload")
            k = boto.s3.key.Key(bucket)
            k.key = destpath
            k.set_contents_from_filename(sourcepath,
                    cb=percent_cb, num_cb=10)
    

    PS: For more reference URL

    python: sys is not defined

    In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.

    Add/remove class with jquery based on vertical scroll?

    Add some transition effect to it if you like:

    http://jsbin.com/boreme/17/edit?html,css,js

    .clearHeader {
      height:50px;
      background:lightblue;
      position:fixed;
      top:0;
      left:0;
      width:100%;
    
      -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
      transition: background 2s;
    }
    
    .clearHeader.darkHeader {
     background:#000;
    }
    

    PHP MySQL Query Where x = $variable

    You have to do this to echo it:

    echo $row['note'];
    

    (The data is coming as an array)

    What does numpy.random.seed(0) do?

    I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.

    Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.

    What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.

    Laravel back button

    Indeed using {{ URL:previous() }} do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.

    In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.

    When I use URL:previous(), Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:

    <a href="javascript:history.back()" class="btn btn-default">Voltar</a>
    

    I'm tested this on Laravel 5.3, just for clarification.

    TCPDF output without saving file

    Print the PDF header (using header() function) like: header("Content-type: application/pdf");

    and then just echo the content of the PDF file you created (instead of writing it to disk).

    c# Best Method to create a log file

    Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.

    Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.

    C# 4.0 optional out/ref arguments

    ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

    p.GetCoordinates(out var x, out _); // I only care about x

    P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

    How to detect the swipe left or Right in Android?

    this should help you maybe...

    private final GestureDetector.SimpleOnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Log.i("gestureDebug333", "doubleTapped:" + e);
            return super.onDoubleTap(e);
        }
    
        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            Log.i("gestureDebug333", "doubleTappedEvent:" + e);
    
            return super.onDoubleTapEvent(e);
        }
    
        @Override
        public boolean onDown(MotionEvent e) {
            Log.i("gestureDebug333", "onDown:" + e);
    
    
            return super.onDown(e);
    
        }
    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    
    
            Log.i("gestureDebug333", "flinged:" + e1 + "---" + e2);
            Log.i("gestureDebug333", "fling velocity:" + velocityX + "---" + velocityY);
            if (e1.getAction() == MotionEvent.ACTION_DOWN && e1.getX() > (e2.getX() + 300)){
               // Toast.makeText(context, "flinged right to left", Toast.LENGTH_SHORT).show();
                goForward();
            }
            if (e1.getAction() == MotionEvent.ACTION_DOWN && e2.getX() > (e1.getX() + 300)){
                //Toast.makeText(context, "flinged left to right", Toast.LENGTH_SHORT).show();
                goBack();
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    
        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }
    
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    
        @Override
        public void onShowPress(MotionEvent e) {
            super.onShowPress(e);
        }
    
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return super.onSingleTapConfirmed(e);
        }
    
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return super.onSingleTapUp(e);
        }
    };
    

    Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

    I can confirm that I have the same bug on Windows 7 using Chrome Version 35 but I share my partial solution who is open a new tab on Chrome and showing a dialog.

    For other browser when the user click on cancel automatically close the new print window.

    //Chrome's versions > 34 is some bug who stop all javascript when is show a prints preview
    //http://stackoverflow.com/questions/23071291/javascript-window-print-in-chrome-closing-new-window-or-tab-instead-of-cancel
    if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var popupWin = window.open();
        popupWin.window.focus();
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>');
        popupWin.onbeforeunload = function (event) {
            return 'Please use the cancel button on the left side of the print preview to close this window.\n';
        };
    }else {
        var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div>' +
            '<script>setTimeout(function(){ window.parent.focus(); window.close() }, 100)</script></html>');
    }
    popupWin.document.close();
    

    Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

    Make sure you're passing a selector to jQuery, not some form of data:

    $( '.my-selector' )
    

    not:

    $( [ 'my-data' ] )
    

    How to get root access on Android emulator?

    I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:

    On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]

    Inside the shell, run these commands:

    mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
    cd /system/bin
    cat sh > su && chmod 4775 su
    

    Then, install SuperSU and install SU binary. This will replace the SU binary we just created. (Optional) Remove SuperSU and install Superuser by CWM. Install the su binary again. Now, root works!

    How to compare two date values with jQuery

    just use the jQuery datepicker UI library and convert both your strings into date format, then you can easily compare. following link might be useful

    https://stackoverflow.com/questions/2974496/jquery-javascript-convert-date-string-to-date

    cheers..!!

    CSS background image alt attribute

    This article from W3C tells you what they think you should do https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage

    and has examples here http://mars.dequecloud.com/demo/ImgRole.htm

    among which

    <a href="http://www.facebook.com">
     <span class="fb_logo" role="img" aria-label="Connect via Facebook">
     </span>
    </a>
    

    Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:

    <a href="http://www.facebook.com"><span class="fb_logo">
      Connect via Facebook
    </span></a>
    
    .fb_logo {
      height: 37px; width: 37px;
      background-image: url('../gfx/logo-facebook.svg');
      color:transparent; overflow:hidden; /* hide the text */
    }
    

    Anaconda Installed but Cannot Launch Navigator

    What finally worked for me was:

    1. Uninstalling Anaconda
    2. Deleting all files that has "conda" in them - most of them should be located in: C:\Users\Admin
    3. Delete especially the "condarc" file.
    4. Reboot
    5. Installed 32-bit installer (even though my system is 64-bit) and reboot

    Finally worked. I have not yet re-tried with 64-bit installer, since I have a time critical project, but will do when again I have spare time.

    P.S. what broke Anaconda for me was a blue screen I got while updating Anaconda. I guess it did not clear all old files and this broke the new installs.

    How do I add a newline to a windows-forms TextBox?

    First you have to set the MultiLine property of the TextBox to true so that it supports multiple lines.

    Then you just use Environment.NewLine to get the newline character combination.

    Integer value comparison

    well i might be late on this but i would like to share something:

    Given the input: System.out.println(isGreaterThanZero(-1));

    public static boolean isGreaterThanZero(Integer value) {
        return value == null?false:value.compareTo(0) > 0;
    }
    

    Returns false

    public static boolean isGreaterThanZero(Integer value) {
        return value == null?false:value.intValue() > 0;
    }
    

    Returns true So i think in yourcase 'compareTo' will be more accurate.

    Switching users inside Docker image to a non-root user

    You should also be able to do:

    apt install sudo

    sudo -i -u tomcat

    Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.

    How do I put text on ProgressBar?

    Alliteratively you can try placing a Label control and placing it on top of the progress bar control. Then you can set whatever the text you want to the label. I haven't done this my self. If it works it should be a simpler solution than overriding onpaint.

    How to copy multiple files in one layer using a Dockerfile?

    It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

    https://docs.docker.com/engine/reference/builder/#dockerignore-file

    Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

    If a folder does not exist, create it

    Use this code if the folder is not presented under the image folder or other folders

    string subPath = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/");
    
    bool exists = System.IO.Directory.Exists(subPath);
    if(!exists)
        System.IO.Directory.CreateDirectory(subPath);
    
    string path = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/" + OrderId + ".png");
    

    Maximize a window programmatically and prevent the user from changing the windows state

    Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

    So the window will be maximized, and the other parts are in the other answers.

    HTTP POST using JSON in Java

    @momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:

    JSONObject json = new JSONObject();
    json.put("someKey", "someValue");    
    
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    
    try {
        HttpPost request = new HttpPost("http://yoururl");
        StringEntity params = new StringEntity(json.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        httpClient.execute(request);
    // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.close();
    }
    

    Closing a file after File.Create

    File.WriteAllText(file,content)
    

    create write close

    File.WriteAllBytes--   type binary
    

    :)

    foreach loop in angularjs

    The angular.forEach() will iterate through your json object.

    First iteration,

    key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

    Second iteration,

    key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

    To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

    The code below will give you what you want:

       angular.forEach(json, function (value, key)
             {
                    //console.log(key);
                    //console.log(value);
                    if (value.password == "thomasTheKing") {
                        console.log("username is thomas");
                    }
             });
    

    Double precision floating values in Python?

    Decimal datatype

    • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.

    If you are pressed by performance issuses, have a look at GMPY

    How to get an object's property's value by property name?

    Here is an alternative way to get an object's property value:

    write-host $(get-something).SomeProp
    

    Javascript Regex: How to put a variable inside a regular expression?

    You can create regular expressions in JS in one of two ways:

    1. Using regular expression literal - /ab{2}/g
    2. Using the regular expression constructor - new RegExp("ab{2}", "g") .

    Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is

    new RegExp(regularExpressionString, modifiersString)
    

    You can embed variables as part of the regularExpressionString. For example,

    var pattern="cd"
    var repeats=3
    new RegExp(`${pattern}{${repeats}}`, "g") 
    

    This will match any appearance of the pattern cdcdcd.

    Return list of items in list greater than some value

    There is another way,

    j3 = j2 > 4; print(j2[j3])
    

    tested in 3.x

    Delete/Reset all entries in Core Data?

    Here is a somewhat simplified version with less calls to AppDelegate self and the last bit of code that was left out of the top rated answer. Also I was getting an error "Object's persistent store is not reachable from this NSManagedObjectContext's coordinator" so just needed to add that back.

    NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
    NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"dataModel"];
    NSError *error;
    
    [storeCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    
    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
    
    if (storeCoordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
    }
    

    How to do one-liner if else statement?

    Like user2680100 said, in Golang you can have the structure:

    if <statement>; <evaluation> {
        [statements ...]
    } else {
        [statements ...]
    }
    

    This is useful to shortcut some expressions that need error checking, or another kind of boolean checking, like:

    
    var number int64
    if v := os.Getenv("NUMBER"); v != "" {
       if number, err = strconv.ParseInt(v, 10, 64); err != nil {
           os.Exit(42)
       }
    } else {
        os.Exit(1)
    }
    

    With this you can achieve something like (in C):

    Sprite *buffer = get_sprite("foo.png");
    Sprite *foo_sprite = (buffer != 0) ? buffer : donut_sprite
    

    But is evident that this sugar in Golang have to be used with moderation, for me, personally, I like to use this sugar with max of one level of nesting, like:

    
    var number int64
    if v := os.Getenv("NUMBER"); v != "" {
        number, err = strconv.ParseInt(v, 10, 64)
        if err != nil {
            os.Exit(42)
        }
    } else {
        os.Exit(1)
    }
    

    You can also implement ternary expressions with functions like func Ternary(b bool, a interface{}, b interface{}) { ... } but i don't like this approach, looks like a creation of a exception case in syntax, and creation of this "features", in my personal opinion, reduce the focus on that matters, that is algorithm and readability, but, the most important thing that makes me don't go for this way is that fact that this can bring a kind of overhead, and bring more cycles to in your program execution.

    Format the date using Ruby on Rails

    Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

    Date.strptime('1100897479', '%s')
    #=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
    Date.strptime('1100897479', '%s').to_s
    #=> "2004-11-19"
    DateTime.strptime('1100897479', '%s')
    #=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
    DateTime.strptime('1100897479', '%s').to_s
    #=> "2004-11-19T20:51:19+00:00"
    

    Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

    Dataframe to Excel sheet

    Or you can do like this:

    your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
                      sheet_name= 'your_sheet_name'
                    )
    

    <embed> vs. <object>

    Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows

    <iframe style="width:100%;height:500px" src="http://www.mysite.co.uk/libs/pdfjs/web/viewer.html?file="http://www.mysite.co.uk/mypdf.pdf"></iframe>
    

    A tutorial on how to use pdf.js can be found at this ejectamenta blog article

    PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

    Go to C:\xamppp\php. Set these values in php.ini:

    upload_max_filesize = 1000M
    post_max_size = 0M
    

    How to use matplotlib tight layout with Figure?

    Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

    There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

    E.g.

    import matplotlib.pyplot as plt
    
    #-- In your case, you'd do something more like:
    # from matplotlib.figure import Figure
    # fig = Figure()
    #-- ...but we want to use it interactive for a quick example, so 
    #--    we'll do it this way
    fig, axes = plt.subplots(nrows=4, ncols=4)
    
    for i, ax in enumerate(axes.flat, start=1):
        ax.set_title('Test Axes {}'.format(i))
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
    
    plt.show()
    

    Before Tight Layout

    enter image description here

    After Tight Layout

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=4, ncols=4)
    
    for i, ax in enumerate(axes.flat, start=1):
        ax.set_title('Test Axes {}'.format(i))
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
    
    fig.tight_layout()
    
    plt.show()
    

    enter image description here

    PHP Email sending BCC

    You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

    Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

    On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

    $headers  = "From: [email protected]\r\n" .
      "X-Mailer: php\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $headers .= "Bcc: $emailList\r\n";
    

    php delete a single file in directory

    If you want to delete a single file, you must, as you found out, use the unlink() function.

    That function will delete what you pass it as a parameter : so, it's up to you to pass it the path to the file that it must delete.


    For example, you'll use something like this :

    unlink('/path/to/dir/filename');
    

    In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

    Method 1 : Using jQuery Ajax Get call (partial page update).

    Suitable for when you need to retrieve jSon data from database.

    Controller's Action Method

    [HttpGet]
    public ActionResult Foo(string id)
    {
        var person = Something.GetPersonByID(id);
        return Json(person, JsonRequestBehavior.AllowGet);
    }
    

    Jquery GET

    function getPerson(id) {
        $.ajax({
            url: '@Url.Action("Foo", "SomeController")',
            type: 'GET',
            dataType: 'json',
            // we set cache: false because GET requests are often cached by browsers
            // IE is particularly aggressive in that respect
            cache: false,
            data: { id: id },
            success: function(person) {
                $('#FirstName').val(person.FirstName);
                $('#LastName').val(person.LastName);
            }
        });
    }
    

    Person class

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    Method 2 : Using jQuery Ajax Post call (partial page update).

    Suitable for when you need to do partial page post data into database.

    Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

    For more information check Posting JSON Data to MVC Controllers Here

    Method 3 : As a Form post scenario (full page update).

    Suitable for when you need to save or update data into database.

    View

    @using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
    {        
        @Html.TextBoxFor(model => m.Text)
        
        <input type="submit" value="Save" />
    }
    

    Action Method

    [HttpPost]
    public ActionResult SaveData(FormCollection form)
        {
            // Get movie to update
            return View();
       }
    

    Method 4 : As a Form Get scenario (full page update).

    Suitable for when you need to Get data from database

    Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

    I hope this will help to you.

    navbar color in Twitter Bootstrap

    You can download a custom version of bootstrap and set @navbarBackground to the color you want.

    http://twitter.github.com/bootstrap/customize.html

    Read text file into string. C++ ifstream

    getline(fin, buffer, '\n')
    where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

    Java serialization - java.io.InvalidClassException local class incompatible

    The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).

    http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html

    The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

    If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.

    The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.

    How to prevent http file caching in Apache httpd (MAMP)

    Based on the example here: http://drupal.org/node/550488

    The following will probably work in .htaccess

     <IfModule mod_expires.c>
       # Enable expirations.
       ExpiresActive On
    
       # Cache all files for 2 weeks after access (A).
       ExpiresDefault A1209600
    
      <FilesMatch (\.js|\.html)$>
         ExpiresActive Off
      </FilesMatch>
     </IfModule>
    

    How do I migrate an SVN repository with history to a new Git repository?

    I've posted an step by step guide (here) to convert svn in to git including converting svn tags in to git tags and svn branches in to git branches.

    Short version:

    1) clone svn from an specific revision number. (the revision number must be the oldest you want to migrate)

    git svn clone --username=yourSvnUsername -T trunk_subdir -t tags_subdir -b branches_subdir -r aRevisionNumber svn_url gitreponame
    

    2) fetch svn data. This step it's the one it takes most time.

    cd gitreponame
    git svn fetch
    

    repeat git svn fetch until finishes without error

    3) get master branch updated

    git svn rebase
    

    4) Create local branches from svn branches by copying references

    cp .git/refs/remotes/origin/* .git/refs/heads/
    

    5) convert svn tags into git tags

    git for-each-ref refs/remotes/origin/tags | sed 's#^.*\([[:xdigit:]]\{40\}\).*refs/remotes/origin/tags/\(.*\)$#\2 \1#g' | while read p; do git tag -m "tag from svn" $p; done
    

    6) Put a repository at a better place like github

    git remotes add newrepo [email protected]:aUser/aProjectName.git
    git push newrepo refs/heads/*
    git push --tags newrepo
    

    If you want more details, read my post or ask me.

    Deep cloning objects

    Create an extension:

    public static T Clone<T>(this T theObject)
    {
        string jsonData = JsonConvert.SerializeObject(theObject);
        return JsonConvert.DeserializeObject<T>(jsonData);
    }
    

    And call it like this:

    NewObject = OldObject.Clone();
    

    JavaScript Extending Class

    Try this:

    Function.prototype.extends = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    Monkey.extends(Monster);
    function Monkey() {
      Monster.apply(this, arguments); // call super
    }
    

    Edit: I put a quick demo here http://jsbin.com/anekew/1/edit. Note that extends is a reserved word in JS and you may get warnings when linting your code, you can simply name it inherits, that's what I usually do.

    With this helper in place and using an object props as only parameter, inheritance in JS becomes a bit simpler:

    Function.prototype.inherits = function(parent) {
      this.prototype = Object.create(parent.prototype);
    };
    
    function Monster(props) {
      this.health = props.health || 100;
    }
    
    Monster.prototype = {
      growl: function() {
        return 'Grrrrr';
      }
    };
    
    Monkey.inherits(Monster);
    function Monkey() {
      Monster.apply(this, arguments);
    }
    
    var monkey = new Monkey({ health: 200 });
    
    console.log(monkey.health); //=> 200
    console.log(monkey.growl()); //=> "Grrrr"
    

    How to convert empty spaces into null values, using SQL Server?

    here's a regex one for ya.

    update table
    set col1=null
    where col1 not like '%[a-z,0-9]%'
    

    essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.

    Having issues with a MySQL Join that needs to meet multiple conditions

    You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

    SELECT u.*
    FROM rooms AS u
    JOIN facilities_r AS fu
    ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
    WHERE vizibility='1'
    GROUP BY id_uc
    ORDER BY u_premium desc, id_uc desc
    

    Number of days in particular month of particular year?

    public class Main {
    
        private static LocalDate local=LocalDate.now();
        public static void main(String[] args) {
    
                int month=local.lengthOfMonth();
                System.out.println(month);
    
        }
    }
    

    Creating an array from a text file in Bash

    You can do this too:

    oldIFS="$IFS"
    IFS=$'\n' arr=($(<file))
    IFS="$oldIFS"
    echo "${arr[1]}" # It will print `A Dog`.
    

    Note:

    Filename expansion still occurs. For example, if there's a line with a literal * it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.

    How can I make a CSS table fit the screen width?

    Put the table in a container element that has

    overflow:scroll; max-width:95vw;

    or make the table fit to the screen and overflow:scroll all table cells.

    What is the most efficient way to store a list in the Django models?

    A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:

    The "list" would be stored in your Django model like so:

    class MyModel(models.Model):
        myList = models.TextField(null=True) # JSON-serialized (text) version of your list
    

    In your view/controller code:

    Storing the list in the database:

    import simplejson as json # this would be just 'import json' in Python 2.7 and later
    ...
    ...
    
    myModel = MyModel()
    listIWantToStore = [1,2,3,4,5,'hello']
    myModel.myList = json.dumps(listIWantToStore)
    myModel.save()
    

    Retrieving the list from the database:

    jsonDec = json.decoder.JSONDecoder()
    myPythonList = jsonDec.decode(myModel.myList)
    

    Conceptually, here's what's going on:

    >>> myList = [1,2,3,4,5,'hello']
    >>> import simplejson as json
    >>> myJsonList = json.dumps(myList)
    >>> myJsonList
    '[1, 2, 3, 4, 5, "hello"]'
    >>> myJsonList.__class__
    <type 'str'>
    >>> jsonDec = json.decoder.JSONDecoder()
    >>> myPythonList = jsonDec.decode(myJsonList)
    >>> myPythonList
    [1, 2, 3, 4, 5, u'hello']
    >>> myPythonList.__class__
    <type 'list'>