Programs & Examples On #Automocking

List files with certain extensions with ls and grep

ls -R | findstr ".mp3"

ls -R => lists subdirectories recursively

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

String MinLength and MaxLength validation don't work (asp.net mvc)

This can replace the MaxLength and the MinLength

[StringLength(40, MinimumLength = 10 , ErrorMessage = "Password cannot be longer than 40 characters and less than 10 characters")]

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

LINQ to read XML

XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1"); 
var lvs = lv1s.SelectMany(l=>
     new string[]{ l.Attribute("name").Value }
     .Union(
         l.Descendants("level2")
         .Select(l2=>"   " + l2.Attribute("name").Value)
      )
    );
foreach (var lv in lvs)
{
   result.AppendLine(lv);
}

Ps. You have to use .Root on any of these versions.

How do I get the last day of a month?

This formula reflects @RHSeeger's thought as a simple solution to get (in this example) the last day of the 3rd month (month of date in cell A1 + 4 with the first day of that month minus 1 day):

=DATE(YEAR(A1);MONTH(A1)+4;1)-1

Very precise, inclusive February's in leap years :)

What is a "thread" (really)?

A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.

Suppose you're reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers.

If you have a roommate, and she's using the same technique, she can take the book while you're not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were.

Threads work in the same way. A CPU is giving you the illusion that it's doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. Just like you can share a book with your friend, many tasks can share a CPU.

On a more technical level, an execution context (therefore a thread) consists of the values of the CPU's registers.

Last: threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads.

Clarification: the resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process).

Create a Date with a set timezone without using a string representation

I believe you need the createDateAsUTC function (please compare with convertDateToUTC)

function createDateAsUTC(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}

function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
}

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

How can I initialise a static Map?

Your second approach (Double Brace initialization) is thought to be an anti pattern, so I would go for the first approach.

Another easy way to initialise a static Map is by using this utility function:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>(keyValues.length / 2);

    for (int index = 0; index < keyValues.length / 2; index++) {
        map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
    }

    return map;
}

Map<Integer, String> map1 = mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = mapOf("key1", "value1", "key2", "value2");

Note: in Java 9 you can use Map.of

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

About list

First a very important point, from which everything will follow (I hope).

In ordinary Python, list is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6] is made, it is for all intents and purposes just an ordinary Python object, like a number 3, set {3,7}, or a function lambda x: x+5.

(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).

About and

and is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and can (and must) do that.

The consequence of that is that and cannot be overloaded, just like for cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and completely. The protocol is:

Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True?) If you are an author of a's class, you can customize this answer. If a answers "no", and (skips b completely, it is not evaluated at all, and) says: a is my result (NOT: False is my result).

If a doesn't answer, and asks it: what is your length? (Again, you can customize this as an author of a's class). If a answers 0, and does the same as above - considers it false (NOT False), skips b, and gives a as result.

If a answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and evaluates b, and says: b is my result. Note that it does NOT ask b any questions.

The other way to say all of this is that a and b is almost the same as b if a else a, except a is evaluated only once.

Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.

Putting those two together

Now I hope you understand your example 1. and doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.

Second example: & on list

On the other hand, & is an operator like any other, like + for example. It can be defined for a type by defining a special method on that class. int defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list just doesn't define it, probably because Guido didn't think of any obvious way of defining it.

numpy

On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and - because numpy.array doesn't know who is asking it the question; it just speaks about truth.)

For &, it's completely different story. numpy.array can define it as it wishes, and it defines & consistently with other operators: pointwise. So you finally get what you want.

HTH,

What are the differences between B trees and B+ trees?

In B+ Tree, since only pointers are stored in the internal nodes, their size becomes significantly smaller than the internal nodes of B tree (which store both data+key). Hence, the indexes of the B+ tree can be fetched from the external storage in a single disk read, processed to find the location of the target. If it has been a B tree, a disk read is required for each and every decision making process. Hope I made my point clear! :)

Set value of textarea in jQuery

We can either use .val() or .text() methods to set values. we need to put value inside val() like val("hello").

  $(document).ready(function () {
    $("#submitbtn").click(function () {
      var inputVal = $("#inputText").val();
      $("#txtMessage").val(inputVal);
    });
  });

Check example here: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

Getting the name / key of a JToken with JSON.net

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}

Output:

MobileSiteContent
PageContent

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

PHP, Get tomorrows date from date

echo date ('Y-m-d',strtotime('+1 day', strtotime($your_date)));

Retrofit 2.0 how to get deserialised error response.body

val error = JSONObject(callApi.errorBody()?.string() as String)
            CustomResult.OnError(CustomNotFoundError(userMessage = error["userMessage"] as String))

open class CustomError (
    val traceId: String? = null,
    val errorCode: String? = null,
    val systemMessage: String? = null,
    val userMessage: String? = null,
    val cause: Throwable? = null
)

open class ErrorThrowable(
    private val traceId: String? = null,
    private val errorCode: String? = null,
    private val systemMessage: String? = null,
    private val userMessage: String? = null,
    override val cause: Throwable? = null
) : Throwable(userMessage, cause) {
    fun toError(): CustomError = CustomError(traceId, errorCode, systemMessage, userMessage, cause)
}


class NetworkError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Usted no tiene conexión a internet, active los datos", cause)

class HttpError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage, cause)

class UnknownError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Unknown error", cause)

class CustomNotFoundError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
    CustomError(traceId, errorCode, systemMessage, userMessage?: "Data not found", cause)`

Send multipart/form-data files with angular using $http

In Angular 6, you can do this:

In your service file:

 function_name(data) {
    const url = `the_URL`;
    let input = new FormData();
    input.append('url', data);   // "url" as the key and "data" as value
    return this.http.post(url, input).pipe(map((resp: any) => resp));
  }

In component.ts file: in any function say xyz,

xyz(){
this.Your_service_alias.function_name(data).subscribe(d => {   // "data" can be your file or image in base64 or other encoding
      console.log(d);
    });
}

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.

I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.

Here are essential parts of related functions in Start class look like:

ConfigureServices method:

    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder
                                  .WithOrigins("http://localhost:4200")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  //.AllowCredentials()
                                  ;
                          });
    });

Configure method:

        app.UseCors(MyAllowSpecificOrigins);

Found this from:

How can I setup & run PhantomJS on Ubuntu?

PhantomJS is on npm. You can run this command to install it globally:

npm install -g phantomjs-prebuilt  

phantomjs -v should return 2.1.1

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

jquery how to empty input field

Since you are using jQuery, how about using a trigger-reset:

$(document).ready(function(){
  $('#shares').trigger(':reset');
});

HTML span align center not working?

Please use the following style. margin:auto normally used to center align the content. display:table is needed for span element

<span style="margin:auto; display:table; border:1px solid red;">
    This is some text in a div element!
</span>

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

Displaying all table names in php from MySQL database

The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.

It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.

What is the difference between single-quoted and double-quoted strings in PHP?

' Single quoted

The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.

Example:

echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;

" Double quoted

Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces {} to include variables if you do not want to use concatenation (.) operator) in string.

Example:

echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";

Is there a performance benefit single quote vs double quote in PHP?

Yes. It is slightly faster to use single quotes.

PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there are any variables within the string.

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

What is the purpose of nameof?

What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged event. There are numerous cases where you would want to have the name of the property.

Take this example:

switch (e.PropertyName)
{
    case nameof(SomeProperty):
    { break; }

    // opposed to
    case "SomeOtherProperty":
    { break; }
}

In the first case, renaming SomeProperty will change the name of the property too, or it will break compilation. The last case doesn't.

This is a very useful way to keep your code compiling and bug free (sort-of).

(A very nice article from Eric Lippert why infoof didn't make it, while nameof did)

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

Add Facebook Share button to static HTML page

 <div class="fb_share">
     <a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
       href="http://www.facebook.com/sharer.php">Partilhar</a>
     <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php }  }

 add_action('thesis_hook_byline_item','fb_share');

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

three condition may cause this issue.

  1. differ module have differ jar
  2. in libs had contain jar,but in src alse add relevant source
  3. gradle repeat contain,eg:

    compile fileTree(include: [‘*.jar’], dir: ‘libs’)

    compile files(‘libs/xxx.jar’)

if you can read chinese ,read hereError:Execution failed for task ':app:dexDebug'.> com.android.ide.common.process.ProcessException: o

Should composer.lock be committed to version control?

You then commit the composer.json to your project and everyone else on your team can run composer install to install your project dependencies.

The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.

This means that if anything has been committed since the last time a composer install was done, then, without a lock file, you will get new third-party code being pulled down.

Again, this is a problem if you’re concerned about your code breaking. And it’s one of the reasons why it’s important to think about Composer as being centered around the composer.lock file.

Source: Composer: It’s All About the Lock File.


Commit your application's composer.lock (along with composer.json) into version control. This is important because the install command checks if a lock file is present, and if it is, it downloads the versions specified there (regardless of what composer.json says). This means that anyone who sets up the project will download the exact same version of the dependencies. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then.

Source: Composer - Basic Usage.

Aliases in Windows command prompt

Expanding on roryhewitt answer.

An advantage to using .cmd files over DOSKEY is that these "aliases" are then available in other shells such as PowerShell or WSL (Windows subsystem for Linux).

The only gotcha with using these commands in bash is that it may take a bit more setup since you might need to do some path manipulation before calling your "alias".

eg I have vs.cmd which is my "alias" for editing a file in Visual Studio

@echo off
if [%1]==[] goto nofiles
start "" "c:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" /edit %1
goto end
:nofiles
start "" "C:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" "[PATH TO MY NORMAL SLN]"
:end

Which fires up VS (in this case VS2012 - but adjust to taste) using my "normal" project with no file given but when given a file will attempt to attach to a running VS opening that file "within that project" rather than starting a new instance of VS.

For using this from bash I then add an extra level of indirection since "vs Myfile" wouldn't always work

alias vs='/usr/bin/run_visual_studio.sh'

Which adjusts the paths before calling the vs.cmd

#!/bin/bash
cmd.exe /C 'c:\Windows\System32\vs.cmd' "`wslpath.sh -w -r $1`"

So this way I can just do

vs SomeFile.txt

In either a command prompt, Power Shell or bash and it opens in my running Visual Studio for editing (which just saves my poor brain from having to deal with VI commands or some such when I've just been editing in VS for hours).

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

How to use GROUP BY to concatenate strings in MySQL?

Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:

SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') 
FROM table 
GROUP BY id;

Hope this helps someone else

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

What is so bad about singletons?

Because they are basically object oriented global variables, you can usually design your classes in such a way so that you don't need them.

Can you remove elements from a std::list while iterating through it?

do while loop, it's flexable and fast and easy to read and write.

auto textRegion = m_pdfTextRegions.begin();
    while(textRegion != m_pdfTextRegions.end())
    {
        if ((*textRegion)->glyphs.empty())
        {
            m_pdfTextRegions.erase(textRegion);
            textRegion = m_pdfTextRegions.begin();
        }
        else
            textRegion++;
    } 

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

First, you have to learn to think like a Language Lawyer.

The C++ specification does not make reference to any particular compiler, operating system, or CPU. It makes reference to an abstract machine that is a generalization of actual systems. In the Language Lawyer world, the job of the programmer is to write code for the abstract machine; the job of the compiler is to actualize that code on a concrete machine. By coding rigidly to the spec, you can be certain that your code will compile and run without modification on any system with a compliant C++ compiler, whether today or 50 years from now.

The abstract machine in the C++98/C++03 specification is fundamentally single-threaded. So it is not possible to write multi-threaded C++ code that is "fully portable" with respect to the spec. The spec does not even say anything about the atomicity of memory loads and stores or the order in which loads and stores might happen, never mind things like mutexes.

Of course, you can write multi-threaded code in practice for particular concrete systems – like pthreads or Windows. But there is no standard way to write multi-threaded code for C++98/C++03.

The abstract machine in C++11 is multi-threaded by design. It also has a well-defined memory model; that is, it says what the compiler may and may not do when it comes to accessing memory.

Consider the following example, where a pair of global variables are accessed concurrently by two threads:

           Global
           int x, y;

Thread 1            Thread 2
x = 17;             cout << y << " ";
y = 37;             cout << x << endl;

What might Thread 2 output?

Under C++98/C++03, this is not even Undefined Behavior; the question itself is meaningless because the standard does not contemplate anything called a "thread".

Under C++11, the result is Undefined Behavior, because loads and stores need not be atomic in general. Which may not seem like much of an improvement... And by itself, it's not.

But with C++11, you can write this:

           Global
           atomic<int> x, y;

Thread 1                 Thread 2
x.store(17);             cout << y.load() << " ";
y.store(37);             cout << x.load() << endl;

Now things get much more interesting. First of all, the behavior here is defined. Thread 2 could now print 0 0 (if it runs before Thread 1), 37 17 (if it runs after Thread 1), or 0 17 (if it runs after Thread 1 assigns to x but before it assigns to y).

What it cannot print is 37 0, because the default mode for atomic loads/stores in C++11 is to enforce sequential consistency. This just means all loads and stores must be "as if" they happened in the order you wrote them within each thread, while operations among threads can be interleaved however the system likes. So the default behavior of atomics provides both atomicity and ordering for loads and stores.

Now, on a modern CPU, ensuring sequential consistency can be expensive. In particular, the compiler is likely to emit full-blown memory barriers between every access here. But if your algorithm can tolerate out-of-order loads and stores; i.e., if it requires atomicity but not ordering; i.e., if it can tolerate 37 0 as output from this program, then you can write this:

           Global
           atomic<int> x, y;

Thread 1                            Thread 2
x.store(17,memory_order_relaxed);   cout << y.load(memory_order_relaxed) << " ";
y.store(37,memory_order_relaxed);   cout << x.load(memory_order_relaxed) << endl;

The more modern the CPU, the more likely this is to be faster than the previous example.

Finally, if you just need to keep particular loads and stores in order, you can write:

           Global
           atomic<int> x, y;

Thread 1                            Thread 2
x.store(17,memory_order_release);   cout << y.load(memory_order_acquire) << " ";
y.store(37,memory_order_release);   cout << x.load(memory_order_acquire) << endl;

This takes us back to the ordered loads and stores – so 37 0 is no longer a possible output – but it does so with minimal overhead. (In this trivial example, the result is the same as full-blown sequential consistency; in a larger program, it would not be.)

Of course, if the only outputs you want to see are 0 0 or 37 17, you can just wrap a mutex around the original code. But if you have read this far, I bet you already know how that works, and this answer is already longer than I intended :-).

So, bottom line. Mutexes are great, and C++11 standardizes them. But sometimes for performance reasons you want lower-level primitives (e.g., the classic double-checked locking pattern). The new standard provides high-level gadgets like mutexes and condition variables, and it also provides low-level gadgets like atomic types and the various flavors of memory barrier. So now you can write sophisticated, high-performance concurrent routines entirely within the language specified by the standard, and you can be certain your code will compile and run unchanged on both today's systems and tomorrow's.

Although to be frank, unless you are an expert and working on some serious low-level code, you should probably stick to mutexes and condition variables. That's what I intend to do.

For more on this stuff, see this blog post.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Try this (on Windows, i don't know how in others), if you have changed password a now don't work.

1) kill mysql 2) back up /mysql/data folder 3) go to folder /mysql/backup 4) copy files from /mysql/backup/mysql folder to /mysql/data/mysql (rewrite) 5) run mysql

In my XAMPP on Win7 it works.

How to run only one task in ansible playbook?

See my answer here: Run only one task and handler from ansible playbook

It is possible to run separate role (from roles/ dir):

ansible -i stage.yml -m include_role -a name=create-os-user localhost

and separate task file:

ansible -i stage.yml -m include_tasks -a file=tasks/create-os-user.yml localhost

If you externalize tasks from role to root tasks/ directory (reuse is achieved by import_tasks: ../../../tasks/create-os-user.yml) you can run it independently from playbook/role.

Measuring text height to be drawn on Canvas ( Android )

You must use Rect.width() and Rect.Height() which returned from getTextBounds() instead. That works for me.

Add an image in a WPF button

In the case of a 'missing' image there are several things to consider:

  1. When XAML can't locate a resource it might ignore it (when it won't throw a XamlParseException)

  2. The resource must be properly added and defined:

    • Make sure it exists in your project where expected.

    • Make sure it is built with your project as a resource.

      (Right click ? Properties ? BuildAction='Resource')

Snippet

Another thing to try in similar cases, which is also useful for reusing of the image (or any other resource):

Define your image as a resource in your XAML:

<UserControl.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>

And later use it in your desired control(s):

<Button Content="{StaticResource MyImage}" />

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

CSS set li indent

to indent a ul dropdown menu, use

/* Main Level */
ul{
  margin-left:10px;
}

/* Second Level */
ul ul{
  margin-left:15px;
}

/* Third Level */
ul ul ul{
  margin-left:20px;
}

/* and so on... */

You can indent the lis and (if applicable) the as (or whatever content elements you have) as well , each with differing effects. You could also use padding-left instead of margin-left, again depending on the effect you want.

Update

By default, many browsers use padding-left to set the initial indentation. If you want to get rid of that, set padding-left: 0px;

Still, both margin-left and padding-left settings impact the indentation of lists in different ways. Specifically: margin-left impacts the indentation on the outside of the element's border, whereas padding-left affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)

Setting padding-left: 0; leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.

Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/

Extract month and year from a zoo::yearmon object

Having had a similar problem with data from 1800 to now, this worked for me:

data2$date=as.character(data2$date) 
lct <- Sys.getlocale("LC_TIME"); 
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

static linking only some libraries

The problem as I understand it is as follows. You have several libraries, some static, some dynamic and some both static and dynamic. gcc's default behavior is to link "mostly dynamic". That is, gcc links to dynamic libraries when possible but otherwise falls back to static libraries. When you use the -static option to gcc the behavior is to only link static libraries and exit with an error if no static library can be found, even if there is an appropriate dynamic library.

Another option, which I have on several occasions wished gcc had, is what I call -mostly-static and is essentially the opposite of -dynamic (the default). -mostly-static would, if it existed, prefer to link against static libraries but would fall back to dynamic libraries.

This option does not exist but it can be emulated with the following algorithm:

  1. Constructing the link command line with out including -static.

  2. Iterate over the dynamic link options.

  3. Accumulate library paths, i.e. those options of the form -L<lib_dir> in a variable <lib_path>

  4. For each dynamic link option, i.e. those of the form -l<lib_name>, run the command gcc <lib_path> -print-file-name=lib<lib_name>.a and capture the output.

  5. If the command prints something other than what you passed, it will be the full path to the static library. Replace the dynamic library option with the full path to the static library.

Rinse and repeat until you've processed the entire link command line. Optionally the script can also take a list of library names to exclude from static linking.

The following bash script seems to do the trick:

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 [--exclude <lib_name>]. . . <link_command>"
fi

exclude=()
lib_path=()

while [ $# -ne 0 ]; do
    case "$1" in
        -L*)
            if [ "$1" == -L ]; then
                shift
                LPATH="-L$1"
            else
                LPATH="$1"
            fi

            lib_path+=("$LPATH")
            echo -n "\"$LPATH\" "
            ;;

        -l*)
            NAME="$(echo $1 | sed 's/-l\(.*\)/\1/')"

            if echo "${exclude[@]}" | grep " $NAME " >/dev/null; then
                echo -n "$1 "
            else
                LIB="$(gcc $lib_path -print-file-name=lib"$NAME".a)"
                if [ "$LIB" == lib"$NAME".a ]; then
                    echo -n "$1 "
                else
                    echo -n "\"$LIB\" "
                fi
            fi
            ;;

        --exclude)
            shift
            exclude+=(" $1 ")
            ;;

        *) echo -n "$1 "
    esac

    shift
done

echo

For example:

mostlyStatic gcc -o test test.c -ldl -lpthread

on my system returns:

gcc -o test test.c "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libdl.a" "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"

or with an exclusion:

mostlyStatic --exclude dl gcc -o test test.c -ldl -lpthread

I then get:

gcc -o test test.c -ldl "/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/libpthread.a"

How to get the first word of a sentence in PHP?

You question could be reformulated as "replace in the string the first space and everything following by nothing" . So this can be achieved with a simple regular expression:

$firstWord = preg_replace("/\s.*/", '', ltrim($myvalue));

I have added an optional call to ltrim() to be safe: this function remove spaces at the begin of string.

When and why to 'return false' in JavaScript?

When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.

For more take a look at the MDN docs page for return.

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

Example for boost shared_mutex (multiple reads/one write)?

1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.

boost::shared_mutex _access;
void reader()
{
  boost::shared_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access
}

void conditional_writer()
{
  boost::upgrade_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access

  if (something) {
    boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
    // do work here, but now you have exclusive access
  }

  // do more work here, without anyone having exclusive access
}

void unconditional_writer()
{
  boost::unique_lock< boost::shared_mutex > lock(_access);
  // do work here, with exclusive access
}

Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.

Is there a .NET/C# wrapper for SQLite?

For those like me who don't need or don't want ADO.NET, those who need to run code closer to SQLite, but still compatible with netstandard (.net framework, .net core, etc.), I've built a 100% free open source project called SQLNado (for "Not ADO") available on github here:

https://github.com/smourier/SQLNado

It's available as a nuget here https://www.nuget.org/packages/SqlNado but also available as a single .cs file, so it's quite practical to use in any C# project type.

It supports all of SQLite features when using SQL commands, and also supports most of SQLite features through .NET:

  • Automatic class-to-table mapping (Save, Delete, Load, LoadAll, LoadByPrimaryKey, LoadByForeignKey, etc.)
  • Automatic synchronization of schema (tables, columns) between classes and existing table
  • Designed for thread-safe operations
  • Where and OrderBy LINQ/IQueryable .NET expressions are supported (work is still in progress in this area), also with collation support
  • SQLite database schema (tables, columns, etc.) exposed to .NET
  • SQLite custom functions can be written in .NET
  • SQLite incremental BLOB I/O is exposed as a .NET Stream to avoid high memory consumption
  • SQLite collation support, including the possibility to add custom collations using .NET code
  • SQLite Full Text Search engine (FTS3) support, including the possibility to add custom FTS3 tokenizers using .NET code (like localized stop words for example). I don't believe any other .NET wrappers do that.
  • Automatic support for Windows 'winsqlite3.dll' (only on recent Windows versions) to avoid shipping any binary dependency file. This works in Azure Web apps too!.

Array Size (Length) in C#

it goes like this: 1D:

 type[] name=new type[size]  //or =new type[]{.....elements...}

2D:

 type[][]name=new type[size][] //second brackets are emtpy

then as you use this array :

 name[i]=new type[size_of_sec.Dim]

or You can declare something like a matrix

type[ , ] name=new type [size1,size2]

Work on a remote project with Eclipse via SSH

I had the same problem 2 years ago and I solved it in the following way:

1) I build my projects with makefiles, not managed by eclipse 2) I use a SAMBA connection to edit the files inside Eclipse 3) Building the project: Eclipse calles a "local" make with a makefile which opens a SSH connection to the Linux Host. On the SSH command line you can give parameters which are executed on the Linux host. I use for that parameter a makeit.sh shell script which call the "real" make on the linux host. The different targets for building you can give also by parameters from the local makefile --> makeit.sh --> makefile on linux host.

virtualenvwrapper and Python 3

I find that running

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3

and

export VIRTUALENVWRAPPER_VIRTUALENV=/usr/bin/virtualenv-3.4

in the command line on Ubuntu forces mkvirtualenv to use python3 and virtualenv-3.4. One still has to do

mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

to create the environment. This is assuming that you have python3 in /usr/bin/python3 and virtualenv-3.4 in /usr/local/bin/virtualenv-3.4.

Insert PHP code In WordPress Page and Post

Description:

there are 3 steps to run PHP code inside post or page.

  1. In functions.php file (in your theme) add new function

  2. In functions.php file (in your theme) register new shortcode which call your function:

add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
  1. use your new shortcode

Example #1: just display text.

In functions:

function simple_function_1() {
    return "Hello World!";
}

add_shortcode( 'own_shortcode1', 'simple_function_1' );

In post/page:

[own_shortcode1]

Effect:

Hello World!

Example #2: use for loop.

In functions:

function simple_function_2() {
    $output = "";
    
    for ($number = 1; $number < 10; $number++) {    
        // Append numbers to the string
        $output .= "$number<br>";
    } 
    
    return "$output";
}

add_shortcode( 'own_shortcode2', 'simple_function_2' );

In post/page:

[own_shortcode2]

Effect:

1
2
3
4
5
6
7
8
9

Example #3: use shortcode with arguments

In functions:

function simple_function_3($name) {
    return "Hello $name";
}

add_shortcode( 'own_shortcode3', 'simple_function_3' );

In post/page:

[own_shortcode3 name="John"]

Effect:

Hello John

Example #3 - without passing arguments

In post/page:

[own_shortcode3]

Effect:

Hello 

Hiding and Showing TabPages in tabControl

    Public Shared HiddenTabs As New List(Of TabPage)()
Public Shared Visibletabs As New List(Of TabPage)()
Public Shared Function ShowTab(tab_ As TabPage, show_tab As Boolean)
    Select Case show_tab
        Case True
            If Visibletabs.Contains(tab_) = False Then Visibletabs.Add(tab_)
            If HiddenTabs.Contains(tab_) = True Then HiddenTabs.Remove(tab_)
        Case False
            If HiddenTabs.Contains(tab_) = False Then HiddenTabs.Add(tab_)
            If Visibletabs.Contains(tab_) = True Then Visibletabs.Remove(tab_)
    End Select
    For Each r In HiddenTabs
        Try
            Dim TC As TabControl = r.Parent
            If TC.Contains(r) = True Then TC.TabPages.Remove(r)
        Catch ex As Exception

        End Try
    Next
    For Each a In Visibletabs
        Try
            Dim TC As TabControl = a.Parent
            If TC.Contains(a) = False Then TC.TabPages.Add(a)
        Catch ex As Exception

        End Try
    Next
End Function

500.21 Bad module "ManagedPipelineHandler" in its module list

if it is IIS 8 go to control panel, turn windows features on/off and enable Bad "Named pipe activation" then restart IIS. Hope the same works with IIS 7

How do you make an array of structs in C?

So to put it all together by using malloc():

int main(int argc, char** argv) {
    typedef struct{
        char* firstName;
        char* lastName;
        int day;
        int month;
        int year;

    }STUDENT;

    int numStudents=3;
    int x;
    STUDENT* students = malloc(numStudents * sizeof *students);
    for (x = 0; x < numStudents; x++){
        students[x].firstName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].firstName);
        students[x].lastName=(char*)malloc(sizeof(char*));
        scanf("%s",students[x].lastName);
        scanf("%d",&students[x].day);
        scanf("%d",&students[x].month);
        scanf("%d",&students[x].year);
    }

    for (x = 0; x < numStudents; x++)
        printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);

    return (EXIT_SUCCESS);
}

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

There is probably another table with a foreign key referencing the primary key you are trying to change.

To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section

Use SHOW CREATE TABLE categories to show the name of constraint.

Most probably it will be categories_ibfk_1

Use the name to drop the foreign key first and the column then:

ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;

Difference between Eclipse Europa, Helios, Galileo

They are successive, improved versions of the same product. Anyone noticed how the names of the last three and the next release are in alphabetical order (Galileo, Helios, Indigo, Juno)? This is probably how they will go in the future, in the same way that Ubuntu release codenames increase alphabetically (note Indigo is not a moon of Jupiter!).

django templates: include and extends

From Django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

So Django doesn't grab any blocks from your commondata.html and it doesn't know what to do with rendered html outside blocks.

How can I save a base64-encoded image to disk?

Converting from file with base64 string to png image.

4 variants which works.

var {promisify} = require('util');
var fs = require("fs");

var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)

async function run () {

  // variant 1
  var d = await readFile('./1.txt', 'utf8')
  await writeFile("./1.png", d, 'base64')

  // variant 2
  var d = await readFile('./2.txt', 'utf8')
  var dd = new Buffer(d, 'base64')
  await writeFile("./2.png", dd)

  // variant 3
  var d = await readFile('./3.txt')
  await writeFile("./3.png", d.toString('utf8'), 'base64')

  // variant 4
  var d = await readFile('./4.txt')
  var dd = new Buffer(d.toString('utf8'), 'base64')
  await writeFile("./4.png", dd)

}

run();

Redirect within component Angular 2

first configure routing

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

and

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])

then in your component import and then inject Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

the last thing you have to do is to call

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

or

this.router.navigate(['<aliasInRouteConfig>']);

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

tsc is not recognized as internal or external command

If you want to run the tsc command from the integrated terminal with the TypeScript module installed locally, you can add the following to your .vscode\settings.json file.

{
  "terminal.integrated.env.windows": { "PATH": "${workspaceFolder}\\node_modules\\.bin;${env:PATH}" }
}

This will prepend the locally installed node module's binary/executable directory (where tsc.cmd is located) to the $env.PATH variable.

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

How to install a gem or update RubyGems if it fails with a permissions error

Check to see if your Ruby version is right. If not, change it.

This works for me:

$ rbenv global 1.9.3-p547
$ gem update --system

How to make <input type="file"/> accept only these types?

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif, or a notation like image/* that refers to all image types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

How to get visitor's location (i.e. country) using geolocation?

You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

$.get("https://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.

Java synchronized block vs. Collections.synchronizedMap

Check out Google Collections' Multimap, e.g. page 28 of this presentation.

If you can't use that library for some reason, consider using ConcurrentHashMap instead of SynchronizedHashMap; it has a nifty putIfAbsent(K,V) method with which you can atomically add the element list if it's not already there. Also, consider using CopyOnWriteArrayList for the map values if your usage patterns warrant doing so.

How can I check if a string is null or empty in PowerShell?

PowerShell 2.0 replacement for [string]::IsNullOrWhiteSpace() is string -notmatch "\S"

("\S" = any non-whitespace character)

> $null  -notmatch "\S"
True
> "   "  -notmatch "\S"
True
> " x "  -notmatch "\S"
False

Performance is very close:

> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace("   ")}}
TotalMilliseconds : 3641.2089

> Measure-Command {1..1000000 |% {"   " -notmatch "\S"}}
TotalMilliseconds : 4040.8453

Getting the class of the element that fired an event using JQuery

This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":

event.target.className

You can use jQuery to check for classes by name:

$(event.target).hasClass('konbo');

and to add or remove them with addClass and removeClass.

What is the Simplest Way to Reverse an ArrayList?

The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.

The simplest way, intuitively speaking, is Collections.reverse:

Collections.reverse(myList);

This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.


If not, one could create a copy in reverse order:

static <T> List<T> reverse(final List<T> list) {
    final List<T> result = new ArrayList<>(list);
    Collections.reverse(result);
    return result;
}

This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:

static <T> List<T> reverse(final List<T> list) {
    final int size = list.size();
    final int last = size - 1;

    // create a new list, with exactly enough initial capacity to hold the (reversed) list
    final List<T> result = new ArrayList<>(size);

    // iterate through the list in reverse order and append to the result
    for (int i = last; i >= 0; --i) {
        final T element = list.get(i);
        result.add(element);
    }

    // result now holds a reversed copy of the original list
    return result;
}

This is more efficient, but also more verbose.

Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:

static <T> List<T> reverse(final List<T> list) {
    final int last = list.size() - 1;
    return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
        .map(i -> (last - i))             // reverse order
        .mapToObj(list::get)              // map each index to a list element
        .collect(Collectors.toList());    // wrap them up in a list
}

nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.


The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.

Choosing a "simplest" implementation is left as an exercise for the reader.

Why are empty catch blocks a bad idea?

If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.

        try
        {
            string a = "125";
            int b = int.Parse(a);
        }
        catch (Exception ex)
        {
            Log.LogError(ex);
        }

How to change DataTable columns order

We Can use this method for changing the column index but should be applied to all the columns if there are more than two number of columns otherwise it will show all the Improper values from data table....................

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Date / Timestamp to record when a record was added to the table?

You can use a datetime field and set it's default value to GetDate().

CREATE TABLE [dbo].[Test](
    [TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
    [Foo] [varchar](50) NOT NULL
) ON [PRIMARY]

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

MongoDB: Combine data from multiple collections into one..how?

Starting Mongo 4.4, we can achieve this join within an aggregation pipeline by coupling the new $unionWith aggregation stage with $group's new $accumulator operator:

// > db.users.find()
//   [{ user: 1, name: "x" }, { user: 2, name: "y" }]
// > db.books.find()
//   [{ user: 1, book: "a" }, { user: 1, book: "b" }, { user: 2, book: "c" }]
// > db.movies.find()
//   [{ user: 1, movie: "g" }, { user: 2, movie: "h" }, { user: 2, movie: "i" }]
db.users.aggregate([
  { $unionWith: "books"  },
  { $unionWith: "movies" },
  { $group: {
    _id: "$user",
    user: {
      $accumulator: {
        accumulateArgs: ["$name", "$book", "$movie"],
        init: function() { return { books: [], movies: [] } },
        accumulate: function(user, name, book, movie) {
          if (name) user.name = name;
          if (book) user.books.push(book);
          if (movie) user.movies.push(movie);
          return user;
        },
        merge: function(userV1, userV2) {
          if (userV2.name) userV1.name = userV2.name;
          userV1.books.concat(userV2.books);
          userV1.movies.concat(userV2.movies);
          return userV1;
        },
        lang: "js"
      }
    }
  }}
])
// { _id: 1, user: { books: ["a", "b"], movies: ["g"], name: "x" } }
// { _id: 2, user: { books: ["c"], movies: ["h", "i"], name: "y" } }
  • $unionWith combines records from the given collection within documents already in the aggregation pipeline. After the 2 union stages, we thus have all users, books and movies records within the pipeline.

  • We then $group records by $user and accumulate items using the $accumulator operator allowing custom accumulations of documents as they get grouped:

    • the fields we're interested in accumulating are defined with accumulateArgs.
    • init defines the state that will be accumulated as we group elements.
    • the accumulate function allows performing a custom action with a record being grouped in order to build the accumulated state. For instance, if the item being grouped has the book field defined, then we update the books part of the state.
    • merge is used to merge two internal states. It's only used for aggregations running on sharded clusters or when the operation exceeds memory limits.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Why do this() and super() have to be the first statement in a constructor?

The main goal of adding the super() in the sub-class constructors is that the main job of the compiler is to make a direct or indirect connection of all the classes with the Object class that's why the compiler checks if we have provided the super(parameterized) then compiler doesn't take any responsibility. so that all the instance member gets initialized from Object to the sub - classes.

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

How to implode array with key and value without foreach in PHP

You could use http_build_query, like this:

<?php
  $a=array("item1"=>"object1", "item2"=>"object2");
  echo http_build_query($a,'',', ');
?>

Output:

item1=object1, item2=object2 

Demo

SQL Server SELECT into existing table

There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable

Ref 1 2

Replacing .NET WebBrowser control with a better browser, like Chrome?

You can use registry to set IE version for webbrowser control. Go to: HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add "yourApplicationName.exe" with value of browser_emulation To see value of browser_emulation, refer link: http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

What is the difference between java and core java?

"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.

Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.

Font awesome is not showing icon

You needed to close your `<link />` 
As you can see in your <head></head> tag. This will solve your problem

<head>
    <link rel="stylesheet" href="../css/font-awesome.css" />
    <link rel="stylesheet" href="../css/font-awesome.min.css" />
</head>

pip install: Please check the permissions and owner of that directory

I also saw this change on my Mac when I went from running pip to sudo pip. Adding -H to sudo causes the message to go away for me. E.g.

sudo -H pip install foo

man sudo tells me that -H causes sudo to set $HOME to the target users (root in this case).

So it appears pip is looking into $HOME/Library/Log and sudo by default isn't setting $HOME to /root/. Not surprisingly ~/Library/Log is owned by you as a user rather than root.

I suspect this is some recent change in pip. I'll run it with sudo -H for now to work around.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:

Correct:

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

Incorrect:

<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />

Incorrect:

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

Though this may seem trivial, its easy to overlook.

If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!

No Application Encryption Key Has Been Specified

In my case, while cloning the project from git there was no .env

file. So I copy the .env file from the source project and paste in my current project and change its configuration of database and it run successfully.

Edittext change border color with shape.xml

Use root tag as shape instead of selector in your shape.xml file, and it will resolve your problem!

DateTime2 vs DateTime in SQL Server

Almost all the Answers and Comments have been heavy on the Pros and light on the Cons. Here's a recap of all Pros and Cons so far plus some crucial Cons (in #2 below) I've only seen mentioned once or not at all.

  1. PROS:

1.1. More ISO compliant (ISO 8601) (although I don’t know how this comes into play in practice).

1.2. More range (1/1/0001 to 12/31/9999 vs. 1/1/1753-12/31/9999) (although the extra range, all prior to year 1753, will likely not be used except for ex., in historical, astronomical, geologic, etc. apps).

1.3. Exactly matches the range of .NET’s DateTime Type’s range (although both convert back and forth with no special coding if values are within the target type’s range and precision except for Con # 2.1 below else error / rounding will occur).

1.4. More precision (100 nanosecond aka 0.000,000,1 sec. vs. 3.33 millisecond aka 0.003,33 sec.) (although the extra precision will likely not be used except for ex., in engineering / scientific apps).

1.5. When configured for similar (as in 1 millisec not "same" (as in 3.33 millisec) as Iman Abidi has claimed) precision as DateTime, uses less space (7 vs. 8 bytes), but then of course, you’d be losing the precision benefit which is likely one of the two (the other being range) most touted albeit likely unneeded benefits).

  1. CONS:

2.1. When passing a Parameter to a .NET SqlCommand, you must specify System.Data.SqlDbType.DateTime2 if you may be passing a value outside the SQL Server DateTime’s range and/or precision, because it defaults to System.Data.SqlDbType.DateTime.

2.2. Cannot be implicitly / easily converted to a floating-point numeric (# of days since min date-time) value to do the following to / with it in SQL Server expressions using numeric values and operators:

2.2.1. add or subtract # of days or partial days. Note: Using DateAdd Function as a workaround is not trivial when you're needing to consider multiple if not all parts of the date-time.

2.2.2. take the difference between two date-times for purposes of “age” calculation. Note: You cannot simply use SQL Server’s DateDiff Function instead, because it does not compute age as most people would expect in that if the two date-times happens to cross a calendar / clock date-time boundary of the units specified if even for a tiny fraction of that unit, it’ll return the difference as 1 of that unit vs. 0. For example, the DateDiff in Day’s of two date-times only 1 millisecond apart will return 1 vs. 0 (days) if those date-times are on different calendar days (i.e. “1999-12-31 23:59:59.9999999” and “2000-01-01 00:00:00.0000000”). The same 1 millisecond difference date-times if moved so that they don’t cross a calendar day, will return a “DateDiff” in Day’s of 0 (days).

2.2.3. take the Avg of date-times (in an Aggregate Query) by simply converting to “Float” first and then back again to DateTime.

NOTE: To convert DateTime2 to a numeric, you have to do something like the following formula which still assumes your values are not less than the year 1970 (which means you’re losing all of the extra range plus another 217 years. Note: You may not be able to simply adjust the formula to allow for extra range because you may run into numeric overflow issues.

25567 + (DATEDIFF(SECOND, {d '1970-01-01'}, @Time) + DATEPART(nanosecond, @Time) / 1.0E + 9) / 86400.0 – Source: “ https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html

Of course, you could also Cast to DateTime first (and if necessary back again to DateTime2), but you'd lose the precision and range (all prior to year 1753) benefits of DateTime2 vs. DateTime which are prolly the 2 biggest and also at the same time prolly the 2 least likely needed which begs the question why use it when you lose the implicit / easy conversions to floating-point numeric (# of days) for addition / subtraction / "age" (vs. DateDiff) / Avg calcs benefit which is a big one in my experience.

Btw, the Avg of date-times is (or at least should be) an important use case. a) Besides use in getting average duration when date-times (since a common base date-time) are used to represent duration (a common practice), b) it’s also useful to get a dashboard-type statistic on what the average date-time is in the date-time column of a range / group of Rows. c) A standard (or at least should be standard) ad-hoc Query to monitor / troubleshoot values in a Column that may not be valid ever / any longer and / or may need to be deprecated is to list for each value the occurrence count and (if available) the Min, Avg and Max date-time stamps associated with that value.

How to download all files (but not HTML) from a website using wget?

I was trying to download zip files linked from Omeka's themes page - pretty similar task. This worked for me:

wget -A zip -r -l 1 -nd http://omeka.org/add-ons/themes/
  • -A: only accept zip files
  • -r: recurse
  • -l 1: one level deep (ie, only files directly linked from this page)
  • -nd: don't create a directory structure, just download all the files into this directory.

All the answers with -k, -K, -E etc options probably haven't really understood the question, as those as for rewriting HTML pages to make a local structure, renaming .php files and so on. Not relevant.

To literally get all files except .html etc:

wget -R html,htm,php,asp,jsp,js,py,css -r -l 1 -nd http://yoursite.com

Push items into mongo array via mongoose

First I tried this code

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  function (error, success) {
    if (error) {
      console.log(error);
    } else {
      console.log(success);
    }
  }
);

But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  { upsert: true }
);

Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.

if it doesn't work use below snippet

People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
).exec();

Laravel assets url

You have to do two steps:

  1. Put all your files (css,js,html code, etc.) into the public folder.
  2. Use url({{ URL::asset('images/slides/2.jpg') }}) where images/slides/2.jpg is path of your content.

Similarly you can call js, css etc.

How do I reference a local image in React?

put your images in the public folder or make a subfolder in your public folder and put your images there. for example:

  1. you put "completative-reptile.jpg" in the public folder, then you can access it as
src={'/completative-reptile.jpg'}
  1. you put completative-reptile.jpg at public/static/images, then you can access it as
src={'/static/images/completative-reptile.jpg'}

How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the Client API and get the InputStream from the response

Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);

There are two flavors to get the InputStream. You can also use

Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();

Which one is the more efficient? I'm not sure, but the returned InputStreams are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput. An example implementation might be something like

final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) throws IOException, WebApplicationException {  
        int length;
        byte[] buffer = new byte[1024];
        while((length = responseStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        responseStream.close();
    }   
};
return Response.ok(output).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the InputStream as the Response

final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out), which simply does what we did above in the StreamingOutput implementation

 public static void writeTo(InputStream in, OutputStream out) throws IOException {
    int read;
    final byte[] data = new byte[BUFFER_SIZE];
    while ((read = in.read(data)) != -1) {
        out.write(data, 0, read);
    }
}

Asides:

  • Client objects are expensive resources. You may want to reuse the same Client for request. You can extract a WebTarget from the client for each request.

    WebTarget target = client.target(url);
    InputStream is = target.request().get(InputStream.class);
    

    I think the WebTarget can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client and WebResource (which is equivalent to WebTarget in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

  • You don't have to make use of the Client API. A download can be easily achieved with the java.net package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

  • The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)


UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream to an InputStream, I missed the simplest solution, which is simply to write a MessageBodyWriter for the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return ByteArrayOutputStream.class == type;
    }

    @Override
    public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        t.writeTo(entityStream);
    }
}

Then we can simply return the ByteArrayOutputStream in the response

return Response.ok(baos).build();

D'OH!

UPDATE 2

Here are the tests I used (

Resource class

@Path("test")
public class TestResource {

    final String path = "some_150_mb_file";

    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response doTest() throws Exception {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[4096];
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println("Server size: " + baos.size());
        return Response.ok(baos).build();
    }
}

Client test

public class Main {
    public static void main(String[] args) throws Exception {
        Client client = ClientBuilder.newClient();
        String url = "http://localhost:8080/api/test";
        Response response = client.target(url).request().get();
        String location = "some_location";
        FileOutputStream out = new FileOutputStream(location);
        InputStream is = (InputStream)response.getEntity();
        int len = 0;
        byte[] buffer = new byte[4096];
        while((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
}

UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the OutputStream from the StreamingOutput's write method. Seems the third-party API, required a OutputStream as an argument.

StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) {
        thirdPartyApi.downloadFile(.., .., .., out);
    }
}
return Response.ok(output).build();

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the downloadFile method accepting an OutputStream is so that it can write the result directly to the OutputStream provided. For instance a FileOutputStream, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the OutputStream, as you were trying to do with the baos, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method write doesn't actually get called until the writeTo method (in the MessageBodyWriter), where the OutputStream is passed to it.

You can get a better picture looking at the MessageBodyWriter I wrote. Basically in the writeTo method, replace the ByteArrayOutputStream with StreamingOutput, then inside the method, call streamingOutput.write(entityStream). You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider. This is exactly what happens

What's the main difference between Java SE and Java EE?

The biggest difference are the enterprise services (hence the ee) such as an application server supporting EJBs etc.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

The old fashion emacs bindings can still work in iterm2 and os x terminal:

Preferences -> Profiles -> Keys (sub tab in profiles)

  • Set Left/Right option <kbd>?</kbd> key acts as +Esc (similar in os x terminal)

This should enable alt-f and alt-b for moving words by words. (Still ctrl-a and ctrl-e always work as usual)

If set as meta those old bindings will work while some iterm2 bindings unavailable.

Scheduled run of stored procedure on SQL server

Yes, if you use the SQL Server Agent.

Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.

Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:

exec MyStoredProcedure

That's the overview, post back here if you need any further advice.

[I actually thought I might get in first on this one, boy was I wrong :)]

Unbound classpath container in Eclipse

I got the Similar issue while importing the project.

The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.

There are two ways to resolve this issue:

1.While first time importing the project:

in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".

2.Delete the Project from your work space and import again. This time:

select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"

Get width in pixels from element with style set with %?

You can use offsetWidth. Refer to this post and question for more.

_x000D_
_x000D_
console.log("width:" + document.getElementsByTagName("div")[0].offsetWidth + "px");
_x000D_
div {border: 1px solid #F00;}
_x000D_
<div style="width: 100%; height: 10px;"></div>
_x000D_
_x000D_
_x000D_

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

How to use an environment variable inside a quoted string in Bash

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

echo "$VARIABLE"
echo "${VARIABLE}"

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).

Validating with an XML schema in Python

lxml provides etree.DTD

from the tests on http://lxml.de/api/lxml.tests.test_dtd-pysrc.html

...
root = etree.XML(_bytes("<b/>")) 
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>")) 
self.assert_(dtd.validate(root)) 

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

compression and decompression of string data in java

Another example of correct compression and decompression:

@Slf4j
public class GZIPCompression {
    public static byte[] compress(final String stringToCompress) {
        if (isNull(stringToCompress) || stringToCompress.length() == 0) {
            return null;
        }

        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOutput = new GZIPOutputStream(baos)) {
            gzipOutput.write(stringToCompress.getBytes(UTF_8));
            gzipOutput.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while compression!", e);
        }
    }

    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }
}

How to handle invalid SSL certificates with Apache HttpClient?

From http://hc.apache.org/httpclient-3.x/sslguide.html:

Protocol.registerProtocol("https", 
new Protocol("https", new MySSLSocketFactory(), 443));
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.whatever.com/");
try {
  httpclient.executeMethod(httpget);
      System.out.println(httpget.getStatusLine());
} finally {
      httpget.releaseConnection();
}

Where MySSLSocketFactory example can be found here. It references a TrustManager, which you can modify to trust everything (although you must consider this!)

How to change the height of a div dynamically based on another div using css?

I don't believe you can accomplish that with css. Originally javascript was designed for this. Try this:

<div class="div1" id="div1">
  <div class="div2">
    Div2 starts <br /><br /><br /><br /><br /><br /><br />
    Div2 ends
  </div>
  <div class="div3" id="div3">
    Div3
  </div>
</div>

and javascript function:

function adjustHeight() {
    document.getElementById('div3').style.height = document.defaultView.getComputedStyle(document.getElementById('div1'), "").getPropertyValue("height");
}

call the javascript after the div1 (or whole page) is loaded.

You can also replace document.getElementById('div3').style.height with code manipulating class div3 since my code only add / change style attribute of an element.

Hope this helps.

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

Arduino COM port doesn't work

I restarted my computer and then opened the IDE again and it worked while none of the above did.

Maybe you have to do the things above as well, but make sure to restart the computer too.

How to get SLF4J "Hello World" working with log4j?

you need to add 3 dependency ( API+ API implementation + log4j dependency) 
Add also this 
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
</dependency>

# And to see log in command line , set log4j.properties 

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#And to see log in file  , set log4j.properties 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

how to convert an RGB image to numpy array?

You can also use matplotlib for this.

from matplotlib.image import imread

img = imread('abc.tiff')
print(type(img))

output: <class 'numpy.ndarray'>

Setting the Vim background colors

supplement of windows

gvim version: 8.2

location of .gvimrc: %userprofile%/.gvimrc

" .gvimrc
colorscheme darkblue

Which color is allows me to choose?

Find your install directory and go to the directory of colors. in my case is: %PROGRAMFILES(X86)%\Vim\vim82\colors

blue.vim
darkblue.vim
slate.vim
...
README.txt

How to reset settings in Visual Studio Code?

On Linux environment delete the folder "~/.config/Code" to reset Visual Studio Code Settings.

How to use the pass statement?

If you want to import a module, if it exists, and ignore importing it, if that module does not exists, you can use the below code:

try:
    import a_module
except ImportError:
    pass
#rest of your code

If you avoid writing the pass statement and continue writing the rest of your code, a IndentationError would be raised, since the lines after opening the except block are not indented

Detect the Internet connection is offline?

Just use navigator.onLine if this is true then you're online else offline

Getting reference to child component in parent component

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(Child) child:Child;

  (...)

  someOtherMethod() {
    this.searchBar.someMethod();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(Child) children:QueryList<Child>) {
    this.childcmp = children.first();
  }

  (...)
}

Archive the artifacts in Jenkins

In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.

The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.

Discard old builds options

script to map network drive

Here a JScript variant of JohnB's answer

// Below the MSDN page for MapNetworkDrive Method with link and in case if Microsoft breaks it like every now and then the path to the documentation of now.
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
// MSDN Library -> Web Development -> Scripting -> JScript and VBScript -> Windows Scripting -> Windows Script Host -> Reference (Windows Script Host) -> Methods (Windows Script Host) -> MapNetworkDrive Method

var WshNetwork = WScript.CreateObject('WScript.Network');
function localNameInUse(localName) {
    var driveIterator = WshNetwork.EnumNetworkDrives();
    for (var i=0, l=driveIterator.length; i < l; i += 2) {
        if (driveIterator.Item(i) == localName) {
            return true;
        }
    }
    return false;
}

function mount(localName, remoteName) {
    if (localNameInUse(localName)) {
        WScript.Echo('"' + localName + '" drive letter already in use.');
    } else {
        WshNetwork.MapNetworkDrive(localName, remoteName);
    }
}

function unmount(localName) {
    if (localNameInUse(localName)) {
        WshNetwork.RemoveNetworkDrive(localName);
    }
}

Force flushing of output to a file while bash script is still running

I found a solution to this here. Using the OP's example you basically run

stdbuf -oL /homedir/MyScript &> some_log.log

and then the buffer gets flushed after each line of output. I often combine this with nohup to run long jobs on a remote machine.

stdbuf -oL nohup /homedir/MyScript &> some_log.log

This way your process doesn't get cancelled when you log out.

Stacked Tabs in Bootstrap 3

You should not need to add this back in. This was removed purposefully. The documentation has changed somewhat and the CSS class that is necessary ("nav-stacked") is only mentioned under the pills component, but should work for tabs as well.

This tutorial shows how to use the Bootstrap 3 setup properly to do vertical tabs:
tutsme-webdesign.info/bootstrap-3-toggable-tabs-and-pills

how to convert String into Date time format in JAVA?

Using this,

        String s = "03/24/2013 21:54";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try
        {
            Date date = simpleDateFormat.parse(s);

            System.out.println("date : "+simpleDateFormat.format(date));
        }
        catch (ParseException ex)
        {
            System.out.println("Exception "+ex);
        }

How to upload files on server folder using jsp

You can only use absolute path http://grand-shopping.com/<"some folder"> is not an absolute path.

Either you can use a path inside the application which is vurneable or you can use server specific path like in

windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

Convert hex string to int

you can easily do it with parseInt with format parameter.

Integer.parseInt("-FF", 16) ; // returns -255

javadoc Integer

Large WCF web service request failing with (400) HTTP Bad Request

You can also turn on WCF logging for more information about the original error. This helped me solve this problem.

Add the following to your web.config, it saves the log to C:\log\Traces.svclog

<system.diagnostics>
    <sources>
        <source name="System.ServiceModel"
                  switchValue="Information, ActivityTracing"
                  propagateActivity="true">
            <listeners>
                <add name="traceListener"
                     type="System.Diagnostics.XmlWriterTraceListener"
                     initializeData= "c:\log\Traces.svclog" />
            </listeners>
        </source>
    </sources>
</system.diagnostics>

Rails: Check output of path helper from console

You can show them with rake routes directly.

In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.

Python equivalent of a given wget command

import urllib2
import time

max_attempts = 80
attempts = 0
sleeptime = 10 #in seconds, no reason to continuously try if network is down

#while true: #Possibly Dangerous
while attempts < max_attempts:
    time.sleep(sleeptime)
    try:
        response = urllib2.urlopen("http://example.com", timeout = 5)
        content = response.read()
        f = open( "local/index.html", 'w' )
        f.write( content )
        f.close()
        break
    except urllib2.URLError as e:
        attempts += 1
        print type(e)

Find and replace Android studio

The shortcuts are

On Windows : Ctrl+Shift+R

On Mac : Cmd+Shift+R

Open window in JavaScript with HTML inserted

Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:

https://codepen.io/trusktr/pen/mdeQbKG?editors=0010

This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):

_x000D_
_x000D_
const winHtml = `<!DOCTYPE html>_x000D_
    <html>_x000D_
        <head>_x000D_
            <title>Window with Blob</title>_x000D_
        </head>_x000D_
        <body>_x000D_
            <h1>Hello from the new window!</h1>_x000D_
        </body>_x000D_
    </html>`;_x000D_
_x000D_
const winUrl = URL.createObjectURL(_x000D_
    new Blob([winHtml], { type: "text/html" })_x000D_
);_x000D_
_x000D_
const win = window.open(_x000D_
    winUrl,_x000D_
    "win",_x000D_
    `width=800,height=400,screenX=200,screenY=200`_x000D_
);
_x000D_
_x000D_
_x000D_

How to copy text from a div to clipboard

<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

How to trigger HTML button when you press Enter in textbox?

Do not use Javascript for this!

Modern HTML pages automatically allow a form's submit button to submit the page with the ENTER/RETURN key when any form field control in the web page has focus by the user, autofocus attribute is set on a form field or button, or user tab's into any of the form fields.

So instead of Javascripting this, an easier solution is to add tabindex=0 on your form fields and button inside a form element then autofocus on the first input control. The user can then press "ENTER" to submit the form at any point as they enter data:

<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
  <label for="username1">Username</label>
  <input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
  <label for="password1">Password</label>
  <input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
  <button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

Django Server Error: port is already in use

netstat -ntlp

It will show something like this.

   Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State           PID/Program name    
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      6599/python         
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      -                   
tcp        0      0 192.168.124.1:53        0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::3306                 :::*                    LISTEN     

So now just close the port in which Django/python running already by killing the process associated with it.

kill -9 PID

in my case

kill -9 6599

Now run your Django app.

Casting an int to a string in Python

Either:

"ME" + str(i)

Or:

"ME%d" % i

The second one is usually preferred, especially if you want to build a string from several tokens.

SSIS Convert Between Unicode and Non-Unicode Error

The missing piece here is Data Conversion object. It should be in between OLE DB Source and Destination object.

enter image description here

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

What's the purpose of git-mv?

As @Charles says, git mv is a shorthand.

The real question here is "Other version control systems (eg. Subversion and Perforce) treat file renames specially. Why doesn't Git?"

Linus explains at http://permalink.gmane.org/gmane.comp.version-control.git/217 with characteristic tact:

Please stop this "track files" crap. Git tracks exactly what matters, namely "collections of files". Nothing else is relevant, and even thinking that it is relevant only limits your world-view. Notice how the notion of CVS "annotate" always inevitably ends up limiting how people use it. I think it's a totally useless piece of crap, and I've described something that I think is a million times more useful, and it all fell out exactly because I'm not limiting my thinking to the wrong model of the world.

How to get Last record from Sqlite?

To get last record from your table..

 String selectQuery = "SELECT  * FROM " + "sqlite_sequence";
 Cursor cursor = db.rawQuery(selectQuery, null);
  cursor.moveToLast();

MySQL query to get column names?

Not sure if this is what you were looking for, but this worked for me:

$query = query("DESC YourTable");  
$col_names = array_column($query, 'Field');

That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!

To check result: print_r($col_names);

Warning: comparison with string literals results in unspecified behaviour

There is a distinction between 'a' and "a":

  • 'a' means the value of the character a.
  • "a" means the address of the memory location where the string "a" is stored (which will generally be in the data section of your program's memory space). At that memory location, you will have two bytes -- the character 'a' and the null terminator for the string.

Detecting touch screen devices with Javascript

This works for me:

function isTouchDevice(){
    return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}

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

Actually it is the issue related to the app store. I have upload many build some time it takes time depend upon the size of the ipa and at which time you are uploading it to the App Store. Please use Application Loader 3.0 or higher to upload the build.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

I know you already accepted the other answer, but if you want to do this as a DataFrame, just use groupBy and agg. Assuming you had a DF already created (with columns named "col1", "col2", etc) you could do:

myDF.groupBy($"col1", $"col3", $"col4").agg($"col1", max($"col2"), $"col3", $"col4")

Note that in this case, I chose the Max of col2, but you could do avg, min, etc.

Iterate over model instance field names and values in template

I just tested something like this in shell and seems to do it's job:

my_object_mapped = {attr.name: str(getattr(my_object, attr.name)) for attr in MyModel._meta.fields}

Note that if you want str() representation for foreign objects you should define it in their str method. From that you have dict of values for object. Then you can render some kind of template or whatever.

TypeError: ObjectId('') is not JSON serializable

from bson import json_util
import json

@app.route('/')
def index():
    for _ in "collection_name".find():
        return json.dumps(i, indent=4, default=json_util.default)

This is the sample example for converting BSON into JSON object. You can try this.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Apple uses "NSObjectProtocol" instead of "class".

public protocol UIScrollViewDelegate : NSObjectProtocol {
   ...
}

This also works for me and removed the errors I was seeing when trying to implement my own delegate pattern.

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

Check if textbox has empty value

if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

CSS/HTML: Create a glowing border around an Input Field

Use a normal blue border, a medium border-radius, and a blue box-shadow with position 0 0.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

Did you implement the main() function?

int main(int argc, char **argv) {
    ... code ...
    return 0;
}

[edit]

You have your main() in another source file so you've probably forgotten to add it to your project.

To add an existing source file: In Solution Explorer, right-click the Source Files folder, point to Add, and then click Existing Item. Now select the source file containing the main()

deleted object would be re-saved by cascade (remove deleted object from associations)

I encountered this exception message as well. For me the problem was different. I wanted to delete a parent.

In one transaction:

  • First I called up the parent from the database.
  • Then I called a child element from a collection in the parent.
  • Then I referenced one field in the child (id)
  • Then I deleted the parent.
  • Then I called commit.
  • I got the "deleted object would be resaved" error.

It turns out that I had to do two separate transactions. I committed after referencing the field in the child. Then started a new commit for the delete.

There was no need to delete the child elements or empty the collections in the parent (assuming orphanRemoval = true.). In fact, this didn't work.

In sum, this error appears if you have a reference to a field in a child object when that object is being deleted.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

Unfortunately you can't reference your alias in the GROUP BY statement, you'll have to write the logic again, amazing as that seems.

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY     LastName + ', ' + FirstName

Alternately you could put the select into a subselect or common table expression, after which you could group on the column name (no longer an alias.)

How to minify php page html output?

I've tried several minifiers and they either remove too little or too much.

This code removes redundant empty spaces and optional HTML (ending) tags. Also it plays it safe and does not remove anything that could potentially break HTML, JS or CSS.

Also the code shows how to do that in Zend Framework:

class Application_Plugin_Minify extends Zend_Controller_Plugin_Abstract {

  public function dispatchLoopShutdown() {
    $response = $this->getResponse();
    $body = $response->getBody(); //actually returns both HEAD and BODY

    //remove redundant (white-space) characters
    $replace = array(
        //remove tabs before and after HTML tags
        '/\>[^\S ]+/s'   => '>',
        '/[^\S ]+\</s'   => '<',
        //shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!!
        '/([\t ])+/s'  => ' ',
        //remove leading and trailing spaces
        '/^([\t ])+/m' => '',
        '/([\t ])+$/m' => '',
        // remove JS line comments (simple only); do NOT remove lines containing URL (e.g. 'src="http://server.com/"')!!!
        '~//[a-zA-Z0-9 ]+$~m' => '',
        //remove empty lines (sequence of line-end and white-space characters)
        '/[\r\n]+([\t ]?[\r\n]+)+/s'  => "\n",
        //remove empty lines (between HTML tags); cannot remove just any line-end characters because in inline JS they can matter!
        '/\>[\r\n\t ]+\</s'    => '><',
        //remove "empty" lines containing only JS's block end character; join with next line (e.g. "}\n}\n</script>" --> "}}</script>"
        '/}[\r\n\t ]+/s'  => '}',
        '/}[\r\n\t ]+,[\r\n\t ]+/s'  => '},',
        //remove new-line after JS's function or condition start; join with next line
        '/\)[\r\n\t ]?{[\r\n\t ]+/s'  => '){',
        '/,[\r\n\t ]?{[\r\n\t ]+/s'  => ',{',
        //remove new-line after JS's line end (only most obvious and safe cases)
        '/\),[\r\n\t ]+/s'  => '),',
        //remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs!
        '~([\r\n\t ])?([a-zA-Z0-9]+)="([a-zA-Z0-9_/\\-]+)"([\r\n\t ])?~s' => '$1$2=$3$4', //$1 and $4 insert first white-space character found before/after attribute
    );
    $body = preg_replace(array_keys($replace), array_values($replace), $body);

    //remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission )
    $remove = array(
        '</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>'
    );
    $body = str_ireplace($remove, '', $body);

    $response->setBody($body);
  }
}

But note that when using gZip compression your code gets compressed a lot more that any minification can do so combining minification and gZip is pointless, because time saved by downloading is lost by minification and also saves minimum.

Here are my results (download via 3G network):

 Original HTML:        150kB       180ms download
 gZipped HTML:          24kB        40ms
 minified HTML:        120kB       150ms download + 150ms minification
 min+gzip HTML:         22kB        30ms download + 150ms minification

OS detecting makefile

Note that Makefiles are extremely sensitive to spacing. Here's an example of a Makefile that runs an extra command on OS X and which works on OS X and Linux. Overall, though, autoconf/automake is the way to go for anything at all non-trivial.

UNAME := $(shell uname -s)
CPP = g++
CPPFLAGS = -pthread -ansi -Wall -Werror -pedantic -O0 -g3 -I /nexopia/include
LDFLAGS = -pthread -L/nexopia/lib -lboost_system

HEADERS = data_structures.h http_client.h load.h lock.h search.h server.h thread.h utility.h
OBJECTS = http_client.o load.o lock.o search.o server.o thread.o utility.o vor.o

all: vor

clean:
    rm -f $(OBJECTS) vor

vor: $(OBJECTS)
    $(CPP) $(LDFLAGS) -o vor $(OBJECTS)
ifeq ($(UNAME),Darwin)
    # Set the Boost library location
    install_name_tool -change libboost_system.dylib /nexopia/lib/libboost_system.dylib vor
endif

%.o: %.cpp $(HEADERS) Makefile
    $(CPP) $(CPPFLAGS) -c $

Javascript - Regex to validate date format

@mplungjan, @eduard-luca

function isDate(str) {    
    var parms = str.split(/[\.\-\/]/);
    var yyyy = parseInt(parms[2],10);
    var mm   = parseInt(parms[1],10);
    var dd   = parseInt(parms[0],10);
    var date = new Date(yyyy,mm-1,dd,12,0,0,0);
    return mm === (date.getMonth()+1) && 
        dd === date.getDate() && 
        yyyy === date.getFullYear();
}

new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.

Example:

new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)

Another alternative is to use getUTCDate().

window.location.href and window.open () methods in JavaScript

window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.

Why can't overriding methods throw exceptions broader than the overridden method?

In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).

Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.

Create a basic matrix in C (input by user !)

This is my answer

#include<stdio.h>
int main()
{int mat[100][100];
int row,column,i,j;
printf("enter how many row and colmn you want:\n \n");
scanf("%d",&row);
scanf("%d",&column);
printf("enter the matrix:");

for(i=0;i<row;i++){
    for(j=0;j<column;j++){
        scanf("%d",&mat[i][j]);
    }

printf("\n");
}

for(i=0;i<row;i++){
    for(j=0;j<column;j++){
        printf("%d \t",mat[i][j]);}

printf("\n");}
}

I just choose an approximate value for the row and column. My selected row or column will not cross the value.and then I scan the matrix element then make it in matrix size.

How do I set the colour of a label (coloured text) in Java?

For single color foreground color

label.setForeground(Color.RED)

For multiple foreground colors in the same label:

(I would probably put two labels next to each other using a GridLayout or something, but here goes...)

You could use html in your label text as follows:

frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));

which produces:

enter image description here

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

Go to the task manager, kill the java processes and turn the server back on. should work fine.

iterating and filtering two lists using java 8

this can be achieved using below...

 List<String> unavailable = list1.stream()
                            .filter(e -> !list2.contains(e))
                            .collect(Collectors.toList());

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

How can I get a file's size in C++?

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);

How to fix: Error device not found with ADB.exe

For me, I have to Revoke USB debugging authorizations in Developer Options. Here is the steps:

  1. Turn off USB Debugging,
  2. Revoke USB debugging authorizations,
  3. Plug the cable back in,
  4. Turn on USB Debugging

Batch file to delete files older than N days

Delete all Files older than 3 days

forfiles -p "C:\folder" -m *.* -d -3 -c "cmd  /c del /q @path"

Delete Directories older than 3 days

forfiles -p "C:\folder" -d -3 -c "cmd  /c IF @isdir == TRUE rd /S /Q @path"

Get the index of a certain value in an array in PHP

You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

<?php

$given_array = array('Monday' => 'boring',
'Friday' => 'yay',
'boring',
'Sunday' => 'fun',
7 => 'boring',
'Saturday' => 'yay fun',
'Wednesday' => 'boring',
'my life' => 'boring');

$repeating_value = "boring";

function array_value_positions($array, $value){
    $index = 0;
    $value_array = array();
        foreach($array as $v){
            if($value == $v){
                $value_array[$index] = $value;
            }
        $index++;
        }
    return $value_array;
}

$value_array = array_value_positions($given_array, $repeating_value);

$result = "The value '$value_array[0]' was found at these indices in the given array: ";

$key_string = implode(', ',array_keys($value_array));

echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7

How to write a multiline command?

In the Windows Command Prompt the ^ is used to escape the next character on the command line. (Like \ is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that's why it works for the newline.

For reference the characters that need escaping (if specified as command arguments and not within quotes) are: &|()

So the equivalent of your linux example would be (the More? being a prompt):

C:\> dir ^
More? C:\Windows

Extension methods must be defined in a non-generic static class

Try changing it to static class and back. That might resolve visual studio complaining when it's a false positive.

Ignoring upper case and lower case in Java

I have also tried all the posted code until I found out this one

if(math.toLowerCase(Locale.ENGLISH));

Here whatever character the user input will be converted to lower cases.

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

catching stdout in realtime from subprocess

Depending on the use case, you might also want to disable the buffering in the subprocess itself.

If the subprocess will be a Python process, you could do this before the call:

os.environ["PYTHONUNBUFFERED"] = "1"

Or alternatively pass this in the env argument to Popen.

Otherwise, if you are on Linux/Unix, you can use the stdbuf tool. E.g. like:

cmd = ["stdbuf", "-oL"] + cmd

See also here about stdbuf or other options.

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

Use F string if you are using python v3.7

xstr = F"{s}"

jQuery how to bind onclick event to dynamically added HTML element

A little late to the party but I thought I would try to clear up some common misconceptions in jQuery event handlers. As of jQuery 1.7, .on() should be used instead of the deprecated .live(), to delegate event handlers to elements that are dynamically created at any point after the event handler is assigned.

That said, it is not a simple of switching live for on because the syntax is slightly different:

New method (example 1):

$(document).on('click', '#someting', function(){

});

Deprecated method (example 2):

$('#something').live(function(){

});

As shown above, there is a difference. The twist is .on() can actually be called similar to .live(), by passing the selector to the jQuery function itself:

Example 3:

$('#something').on('click', function(){

});

However, without using $(document) as in example 1, example 3 will not work for dynamically created elements. The example 3 is absolutely fine if you don't need the dynamic delegation.

Should $(document).on() be used for everything?

It will work but if you don't need the dynamic delegation, it would be more appropriate to use example 3 because example 1 requires slightly more work from the browser. There won't be any real impact on performance but it makes sense to use the most appropriate method for your use.

Should .on() be used instead of .click() if no dynamic delegation is needed?

Not necessarily. The following is just a shortcut for example 3:

$('#something').click(function(){

});

The above is perfectly valid and so it's really a matter of personal preference as to which method is used when no dynamic delegation is required.

References:

Why does integer division in C# return an integer and not a float?

As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:

int a = 1;
int b = 2;
var result = a/b;

your compiler will tell you that result would be of type int here.

Gitignore not working

In my case whitespaces at the end of the lines of .gitignore was the cause. So watch out for whitespaces in the .gitignore!

TextFX menu is missing in Notepad++

For 32 bit Notepad++ only

Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.

It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

Best practice for storing and protecting private API keys in applications

Adding to @Manohar Reddy solution, firebase Database or firebase RemoteConfig (with Null default value) can be used:

  1. Cipher your keys
  2. Store it in firebase database
  3. Get it during App startup or whenever required
  4. decipher keys and use it

What is different in this solution?

  • no credintials for firebase
  • firebase access is protected so only app with signed certificate have privilege to make API calls
  • ciphering/deciphering to prevent middle man interception. However calls already https to firebase

jQuery: How to capture the TAB keypress within a Textbox

Suppose you have TextBox with Id txtName

$("[id*=txtName]").on('keydown', function(e) { 
  var keyCode = e.keyCode || e.which; 
  if (keyCode == 9) {
     e.preventDefault();
     alert('Tab Pressed');
 }
});