Programs & Examples On #Packaged task

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

ASP.NET postback with JavaScript

Here is a complete solution

Entire form tag of the asp.net page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
  • The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
  • __EVENTTARGET receives argument 1 of __doPostBack
  • __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
  • As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

  • If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else") 
End If

Other Notes

  • What if I don't know the ID of the control whose click handler I want to run?
    • If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
    • Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
    • This will inject the unique id of the control into the javascript, should you wish it

Use URI builder in Android or create URL with variables

Excellent answer from above turned into a simple utility method.

private Uri buildURI(String url, Map<String, String> params) {

    // build url with parameters.
    Uri.Builder builder = Uri.parse(url).buildUpon();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.appendQueryParameter(entry.getKey(), entry.getValue());
    }

    return builder.build();
}

How can I insert multiple rows into oracle with a sequence value?

From Oracle Wiki, error 02287 is

An ORA-02287 occurs when you use a sequence where it is not allowed.

Of the places where sequences can't be used, you seem to be trying:

In a sub-query

So it seems you can't do multiples in the same statement.

The solution they offer is:

If you want the sequence value to be inserted into the column for every row created, then create a before insert trigger and fetch the sequence value in the trigger and assign it to the column

How to set an environment variable in a running docker container

There are generaly two options, because docker doesn't support this feature now:

  1. Create your own script, which will act like runner for your command. For example:

    #!/bin/bash
    export VAR1=VAL1
    export VAR2=VAL2
    your_cmd
    
  2. Run your command following way:

    docker exec -i CONTAINER_ID /bin/bash -c "export VAR1=VAL1 && export VAR2=VAL2 && your_cmd"
    

Ignore self-signed ssl cert using Jersey Client

This code will only ever be run against test servers so I don't want to go to the hassle of adding new trusted certs each time we set up a new test server.

This is the kind of code that will eventually find its way in production (if not from you, someone else who's reading this question will copy and paste the insecure trust managers that have been suggested into their applications). It's just so easy to forget to remove this sort of code when you have a deadline, since it doesn't show up as a problem.

If you're worried about having to add new certificates every time you have a test server, create your own little CA, issue all the certificates for the test servers using that CA and import this CA certificate into your client trust store. (Even if you don't deal with things like online certificate revocation in a local environment, this is certainly better than using a trust manager that lets anything through.)

There are tools to help you do this, for example TinyCA or XCA.

When should I use GET or POST method? What's the difference between them?

Use GET method if you want to retrieve the resources from URL. You could always see the last page if you hit the back button of your browser, and it could be bookmarked, so it is not as secure as POST method.

Use POST method if you want to 'submit' something to the URL. For example you want to create a google account and you may need to fill in all the detailed information, then you hit 'submit' button (POST method is called here), once you submit successfully, and try to hit back button of your browser, you will get error or a new blank form, instead of last page with filled form.

get size of json object

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

How to create a data file for gnuplot?

Either as most people answered: the file doesn't exist / you're not specifying the path correctly.

Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).

For gnuplot 4.6.0 on windows 7, terminal type set to windows

Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")

Make sure you use this syntax:

plot 'path\path\desireddatafile.txt'

NOT

plot "< path\path\desireddatafile.txt>"

NOR

plot "path\path\desireddatafile.txt"

also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.

How to understand nil vs. empty vs. blank in Ruby

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

Running .empty? on something that is nil will throw a NoMethodError.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

"  ".blank? == true
"  ".empty? == false

Rails also provides .present?, which returns the negation of .blank?.

Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:

[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true 

Finding the type of an object in C++

Your description is a little confusing.

Generally speaking, though some C++ implementations have mechanisms for it, you're not supposed to ask about the type. Instead, you are supposed to do a dynamic_cast on the pointer to A. What this will do is that at runtime, the actual contents of the pointer to A will be checked. If you have a B, you'll get your pointer to B. Otherwise, you'll get an exception or null.

jQuery .val() vs .attr("value")

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

Ruby value of a hash key?

This question seems to be ambiguous.

I'll try with my interpretation of the request.

def do_something(data)
   puts "Found! #{data}"
end

a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }

This will loop over all the key,value pairs and do something only if the key is 'x'.

How do you plot bar charts in gnuplot?

You can directly use the style histograms provide by gnuplot. This is an example if you have two file in output:

set style data histograms
 set style fill solid
 set boxwidth 0.5
 plot "file1.dat" using 5 title "Total1" lt rgb "#406090",\
      "file2.dat" using 5 title "Total2" lt rgb "#40FF00"

Make first letter of a string upper case (with maximum performance)

string emp="TENDULKAR";
string output;
output=emp.First().ToString().ToUpper() + String.Join("", emp.Skip(1)).ToLower();

How to add "on delete cascade" constraints?

Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)
  ON DELETE CASCADE;

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

Why do we have to normalize the input for an artificial neural network?

When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.

Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.

Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

When is the finalize() method called in Java?

Sometimes when it is destroyed, an object must make an action. For example, if an object has a non-java resource such as a file handle or a font, you can verify that these resources are released before destroying an object. To manage such situations, java offers a mechanism called "finalizing". By finalizing it, you can define specific actions that occur when an object is about to be removed from the garbage collector. To add a finalizer to a class simply define the finalize() method. Java execution time calls this method whenever it is about to delete an object of that class. Within the finalize method() you specify actions to be performed before destroying an object. The garbage collector is periodically searched for objects that no longer refer to any running state or indirectly any other object with reference. Before an asset is released, the Java runtime calls the finalize() method on the object. The finalize() method has the following general form:

protected void finalize(){
    // This is where the finalization code is entered
}

With the protected keyword, access to finalize() by code outside its class is prevented. It is important to understand that finalize() is called just just before the garbage collection. It is not called when an object leaves the scope, for example. It means you can not know when, or if, finalize() will be executed. As a result, the program must provide other means to free system resources or other resources used by the object. You should not rely on finalize() for normal running of the program.

How to start an application without waiting in a batch file?

I used start /b for this instead of just start and it ran without a window for each command, so there was no waiting.

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Generating a PNG with matplotlib when DISPLAY is undefined

One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.

user@debian:~$ xauth list         
debian/unix:10  MIT-MAGIC-COOKIE-1  ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10  MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm

source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su

How to configure Eclipse build path to use Maven dependencies?

Maybe you could look into maven-eclipse-plugin instead of M2Eclipse.

There you basically add maven-eclipse-plugin configuration to your pom.xml and then execute mvn eclipse:eclipse which will generate the required .project and .classpath files for Eclipse. Then you'll have the correct build path in Eclipse.

run program in Python shell

Use execfile for Python 2:

>>> execfile('C:\\test.py')

Use exec for Python 3

>>> exec(open("C:\\test.py").read())

How to use type: "POST" in jsonp ajax call

If you just want to do a form POST to your own site using $.ajax() (for example, to emulate an AJAX experience), then you can use the jQuery Form Plugin. However, if you need to do a form POST to a different domain, or to your own domain but using a different protocol (a non-secure http: page posting to a secure https: page), then you'll come upon cross-domain scripting restrictions that you won't be able to resolve with jQuery alone (more info). In such cases, you'll need to bring out the big guns: YQL. Put plainly, YQL is a web scraping language with a SQL-like syntax that allows you to query the entire internet as one large table. As it stands now, in my humble opinion YQL is the only [easy] way to go if you want to do cross-domain form POSTing using client-side JavaScript.

More specifically, you'll need to use YQL's Open Data Table containing an Execute block to make this happen. For a good summary on how to do this, you can read the article "Scraping HTML documents that require POST data with YQL". Luckily for us, YQL guru Christian Heilmann has already created an Open Data Table that handles POST data. You can play around with Christian's "htmlpost" table on the YQL Console. Here's a breakdown of the YQL syntax:

  • select * - select all columns, similar to SQL, but in this case the columns are XML elements or JSON objects returned by the query. In the context of scraping web pages, these "columns" generally correspond to HTML elements, so if want to retrieve only the page title, then you would use select head.title.
  • from htmlpost - what table to query; in this case, use the "htmlpost" Open Data Table (you can use your own custom table if this one doesn't suit your needs).
  • url="..." - the form's action URI.
  • postdata="..." - the serialized form data.
  • xpath="..." - the XPath of the nodes you want to include in the response. This acts as the filtering mechanism, so if you want to include only <p> tags then you would use xpath="//p"; to include everything you would use xpath="//*".

Click 'Test' to execute the YQL query. Once you are happy with the results, be sure to (1) click 'JSON' to set the response format to JSON, and (2) uncheck "Diagnostics" to minimize the size of the JSON payload by removing extraneous diagnostics information. The most important bit is the URL at the bottom of the page -- this is the URL you would use in a $.ajax() statement.

Here, I'm going to show you the exact steps to do a cross-domain form POST via a YQL query using this sample form:

<form id="form-post" action="https://www.example.com/add/member" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <button type="button" onclick="doSubmit()">Add Member</button>
</form>

Your JavaScript would look like this:

function doSubmit() {
  $.ajax({
    url: '//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlpost%20where%0Aurl%3D%22' +
         encodeURIComponent($('#form-post').attr('action')) + '%22%20%0Aand%20postdata%3D%22' +
         encodeURIComponent($('#form-post').serialize()) +
         '%22%20and%20xpath%3D%22%2F%2F*%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=',
    dataType: 'json', /* Optional - jQuery autodetects this by default */
    success: function(response) {
      console.log(response);
    }
  });
}

The url string is the query URL copied from the YQL Console, except with the form's encoded action URI and serialized input data dynamically inserted.

NOTE: Please be aware of security implications when passing sensitive information over the internet. Ensure the page you are submitting sensitive information from is secure (https:) and using TLS 1.x instead of SSL 3.0.

How to join two JavaScript Objects, without using JQUERY

I've used this function to merge objects in the past, I use it to add or update existing properties on obj1 with values from obj2:

var _mergeRecursive = function(obj1, obj2) {

      //iterate over all the properties in the object which is being consumed
      for (var p in obj2) {
          // Property in destination object set; update its value.
          if ( obj2.hasOwnProperty(p) && typeof obj1[p] !== "undefined" ) {
            _mergeRecursive(obj1[p], obj2[p]);

          } else {
            //We don't have that level in the heirarchy so add it
            obj1[p] = obj2[p];

          }
     }
}

It will handle multiple levels of hierarchy as well as single level objects. I used it as part of a utility library for manipulating JSON objects. You can find it here.

How to pass values between Fragments

This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.

In receiver fragment add a listener:

setFragmentResultListener(
    "data_request_key",
    lifecycleOwner,
    FragmentResultListener { requestKey: String, bundle: Bundle ->
        // unpack the bundle and use data
        val frag1Str = bundle.getString("frag1_data_key")

    })

In sender fragment(frag1):

setFragmentResult(
    "data_request_key",
    bundleOf("frag1_data_key" to value)
)

Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.

Credits and further reading:

A New Way to Pass Data Between Fragments

Android Fragments: Fragment Result

Getting realtime output using subprocess

I tried this, and for some reason while the code

for line in p.stdout:
  ...

buffers aggressively, the variant

while True:
  line = p.stdout.readline()
  if not line: break
  ...

does not. Apparently this is a known bug: http://bugs.python.org/issue3907 (The issue is now "Closed" as of Aug 29, 2018)

commons httpclient - Adding query string parameters to GET/POST request

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Running sites on "localhost" is extremely slow

This suggestion fixed it for me. Clear out the WebSiteCache in C:\Users\username\AppData\Local\Microsoft\WebSiteCache

http://blog.geocortex.com/2007/12/07/slow-visual-studio-performance-solved/

Scroll / Jump to id without jQuery

if you want smooth scrolling add behavior configuration.

document.getElementById('id').scrollIntoView({
  behavior: 'smooth'
});

What's the difference between "static" and "static inline" function?

inline instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.

For small functions that are called frequently that can make a big performance difference.

However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.

for example:

static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};

This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline will essentially instruct the compiler to convert the code above into an equivalent of:

 int i;
 ....
 for (i=0; i<999999; i = i+1) { /* do something here */};

Skipping the actual function call and return

Obviously this is an example to show the point, not a real piece of code.

static refers to the scope. In C it means that the function/variable can only be used within the same translation unit.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

How to convert a string of bytes into an int?

In python 3 you can easily convert a byte string into a list of integers (0..255) by

>>> list(b'y\xcc\xa6\xbb')
[121, 204, 166, 187]

How to build a query string for a URL in C#?

Here's my late entry. I didn't like any of the others for various reasons, so I wrote my own.

This version features:

  • Use of StringBuilder only. No ToArray() calls or other extension methods. It doesn't look as pretty as some of the other responses, but I consider this a core function so efficiency is more important than having "fluent", "one-liner" code which hide inefficiencies.

  • Handles multiple values per key. (Didn't need it myself but just to silence Mauricio ;)

    public string ToQueryString(NameValueCollection nvc)
    {
        StringBuilder sb = new StringBuilder("?");
    
        bool first = true;
    
        foreach (string key in nvc.AllKeys)
        {
            foreach (string value in nvc.GetValues(key))
            {
                if (!first)
                {
                    sb.Append("&");
                }
    
                sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
    
                first = false;
            }
        }
    
        return sb.ToString();
    }
    

Example Usage

        var queryParams = new NameValueCollection()
        {
            { "x", "1" },
            { "y", "2" },
            { "foo", "bar" },
            { "foo", "baz" },
            { "special chars", "? = &" },
        };

        string url = "http://example.com/stuff" + ToQueryString(queryParams);

        Console.WriteLine(url);

Output

http://example.com/stuff?x=1&y=2&foo=bar&foo=baz&special%20chars=%3F%20%3D%20%26

How to make the HTML link activated by clicking on the <li>?

jqyery this is another version with jquery a little less shorter. assuming that the <a> element is inside de <li> element

$(li).click(function(){
    $(this).children().click();
});

How do I Convert DateTime.now to UTC in Ruby?

In irb:

>>d = DateTime.now
=> #<DateTime: 11783702280454271/4800000000,5/12,2299161>
>> "#{d.hour.to_i - d.zone.to_i}:#{d.min}:#{d.sec}"
=> "11:16:41"

will convert the time to the utc. But as posted if it is just Time you can use:

Time.now.utc

and get it straight away.

Get name of current class?

Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.

I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:

class InputAssigningMetaclass(type):
    def __new__(cls, name, bases, attrs):
        cls.input = get_input(name)
        return super(MyType, cls).__new__(cls, name, bases, newattrs)

class MyBaseFoo(object):
    __metaclass__ = InputAssigningMetaclass

class foo(MyBaseFoo):
    # etc, no need to create 'input'

class foo2(MyBaseFoo):
    # etc, no need to create 'input'

Losing scope when using ng-include

I've figured out how to work around this issue without mixing parent and sub scope data. Set a ng-if on the the ng-include element and set it to a scope variable. For example :

<div ng-include="{{ template }}" ng-if="show"/>

In your controller, when you have set all the data you need in your sub scope, then set show to true. The ng-include will copy at this moment the data set in your scope and set it in your sub scope.

The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.

Max

Permission denied on CopyFile in VBS

for me adding / worked at the end of location of folder. Hence, if you are copying into folder, don't forget to put /

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

SQL UPDATE with sub-query that references the same table in MySQL

Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE user_account student 
INNER JOIN user_account teacher ON
   teacher.user_account_id = student.teacher_id 
   AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id

Regular Expression For Duplicate Words

I believe this regex handles more situations:

/(\b\S+\b)\s+\b\1\b/

A good selection of test strings can be found here: http://callumacrae.github.com/regex-tuesday/challenge1.html

How to store JSON object in SQLite database

There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();

Using Powershell to stop a service remotely without WMI or remoting

You can also do (Get-Service -Name "what ever" - ComputerName RemoteHost).Status = "Stopped"

Query to list number of records in each table in a database

From this question: https://dba.stackexchange.com/questions/114958/list-all-tables-from-all-user-databases/230411#230411

I added record count to the answer provided by @Aaron Bertrand that lists all databases and all tables.

DECLARE @src NVARCHAR(MAX), @sql NVARCHAR(MAX);

SELECT @sql = N'', @src = N' UNION ALL 
SELECT ''$d'' as ''database'', 
    s.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''schema'',
    t.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''table'' ,
    ind.rows as record_count
  FROM [$d].sys.schemas AS s
  INNER JOIN [$d].sys.tables AS t ON s.[schema_id] = t.[schema_id]
  INNER JOIN [$d].sys.sysindexes AS ind ON t.[object_id] = ind.[id]
  where ind.indid < 2';

SELECT @sql = @sql + REPLACE(@src, '$d', name)
  FROM sys.databases
  WHERE database_id > 4
    AND [state] = 0
    AND HAS_DBACCESS(name) = 1;

SET @sql = STUFF(@sql, 1, 10, CHAR(13) + CHAR(10));

PRINT @sql;
--EXEC sys.sp_executesql @sql;

What is cardinality in Databases?

Cardinality refers to the uniqueness of data contained in a column. If a column has a lot of duplicate data (e.g. a column that stores either "true" or "false"), it has low cardinality, but if the values are highly unique (e.g. Social Security numbers), it has high cardinality.

Gets last digit of a number

Although the best way to do this is to use % if you insist on using strings this will work

public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}

but I just wrote this for completeness. Do not use this code. it is just awful.

How to add a touch event to a UIView?

I think you can simply use

UIControl *headerView = ...
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

i mean headerView extends from UIControl.

Position a CSS background image x pixels from the right?

If you want to specify only the x-axis, you can do the following:

background-position-x: right 100px;

MVC [HttpPost/HttpGet] for Action

You cant combine this to attributes.

But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

The ActionName Attribute allows to have 2 ActionMethods with the same name.

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}

Data truncation: Data too long for column 'logo' at row 1

Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:

jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false

If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.

EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

What does SQL clause "GROUP BY 1" mean?

It will group by first field in the select clause

Loop through all nested dictionary values?

Your question already has been answered well, but I recommend using isinstance(d, collections.Mapping) instead of isinstance(d, dict). It works for dict(), collections.OrderedDict(), and collections.UserDict().

The generally correct version is:

def myprint(d):
    for k, v in d.items():
        if isinstance(v, collections.Mapping):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))

How to align LinearLayout at the center of its parent?

@jksschneider explation is almost right. Make sure that you haven't set any gravity to parent layout, and then set layout_gravity="center" to your view or layout.

What does Html.HiddenFor do?

And to consume the hidden ID input back on your Edit action method:

[HttpPost]
public ActionResult Edit(FormCollection collection)
{
    ViewModel.ID = Convert.ToInt32(collection["ID"]);
}

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Avoid dropdown menu close on click inside

You can also use form tag. Example:

<div class="dropdown-menu">
    <form>
        Anything inside this wont close the dropdown!
        <button class="btn btn-primary" type="button" value="Click me!"/>
    </form>
    <div class="dropdown-divider"></div>
    <a class="dropdown-item" href="#">Clik this and the dropdown will be closed</a>
    <a class="dropdown-item" href="#">This too</a>
</div>

Source: https://getbootstrap.com/docs/5.0/components/dropdowns/#forms

How to get distinct values from an array of objects in JavaScript?

Answering this old question is pretty pointless, but there is a simple answer that speaks to the nature of Javascript. Objects in Javascript are inherently hash tables. We can use this to get a hash of unique keys:

var o = {}; array.map(function(v){ o[v.age] = 1; });

Then we can reduce the hash to an array of unique values:

var a2 = []; for (k in o){ a2.push(k); }

That is all you need. The array a2 contains just the unique ages.

How to handle a lost KeyStore password in Android?

SOLUTION 2018: Sign app with new keystore file if you missing password or jks file.

1) Create new keystore.jks file with comand line (not android studio build menu)

keytool -genkeypair -alias upload -keyalg RSA -keysize 2048 -validity 9125 -keystore keystore.jks

Windows example: "C:\Program Files\Android\Android Studio\jre\bin\keytool.exe" -genkeypair -alias upload -keyalg RSA -keysize 2048 -validity 9125 -keystore "C:\keystore_new.jks"

2) Generate a .pem file from new keystore

keytool -export -rfc -alias upload -file upload_certificate.pem -keystore keystore.jks

Windows example: "C:\Program Files\Android\Android Studio\jre\bin\keytool.exe" -export -rfc -alias upload -file "C:\upload_cert.pem" -keystore "C:\keystore_new.jks"

3) Use this support form, set "keystore problem" and with attachment add .pem file: https://support.google.com/googleplay/android-developer/contact/otherbugs

4) 12-48h you new keystore is enabled. Update your app on playstore with new apk signed with new keystore :D

Global variables in AngularJS

Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope will be around. My conjecture is based on the fact that $scope is being removed as well. Obviously controllers, will still exist, just not in the ng-controller fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.

What represents a double in sql server?

For SQL Sever:

Decimal Type is 128 bit signed number Float is a 64 bit signed number.

The real answer is Float, I was incorrect about decimal.

The reason is if you use a decimal you will never fill 64 bit of the decimal type.

Although decimal won't give you an error if you try to use a int type.

Here is a nice reference chart of the types.

Turning off hibernate logging console output

To get rid of logger output in console try this.

ch.qos.logback.classic.LoggerContext.LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.LoggerFactory.getILoggerFactory();

loggerContext.stop();

These statements disabled all the console outputs from logger.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Load image from url

public class MainActivity extends Activity {

    Bitmap b;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView1);
        information info = new information();
        info.execute("");
    }

    public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... arg0) {

            try
            {
                URL url = new URL("http://10.119.120.10:80/img.jpg");
                InputStream is = new BufferedInputStream(url.openStream());
                b = BitmapFactory.decodeStream(is);

            } catch(Exception e){}
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            img.setImageBitmap(b);
        }
    }
}

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

read word by word from file in C++

If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:

#include "iostream"

#include "windows.h"

#include "string"

#include "fstream"

using namespace std;

int main() {

string saveload;


cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document    |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
    getline(cin, saveload);

    if (saveload == "open file"){
        string filenamet;
        cout << "file name? " << endl;
        getline(cin, filenamet, '*');
        ifstream loadFile;

        loadFile.open(filenamet, ifstream::in);

        cout << "the text you entered was: ";

        while (loadFile.good()){

            cout << (char)loadFile.get();

            Sleep(100);
        }

        cout << "" << endl;

        loadFile.close();

    }

    if (saveload == "text") {
        string filename;
        cout << "file name: " << endl;
        getline(cin, filename,'*');
        string textToSave;
        cout << "Enter your text: " << endl;
        getline(cin, textToSave,'*');

        ofstream saveFile(filename);

        saveFile << textToSave;

        saveFile.close();

    }
}
return 0;
}

Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG

how to fix java.lang.IndexOutOfBoundsException

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

How can I run PowerShell with the .NET 4 runtime?

Actually, you can get PowerShell to run using .NET 4 without affecting other .NET applications. I needed to do so to use the new HttpWebRequest "Host" property, however changing the "OnlyUseLatestCLR" broke Fiddler as that could not be used under .NET 4.

The developers of PowerShell obviously foresaw this happening, and they added a registry key to specify what version of the Framework it should use. One slight issue is that you need to take ownership of the registry key before changing it, as even administrators do not have access.

  • HKLM:\Software\Microsoft\Powershell\1\PowerShellEngine\RuntimeVersion (64 bit and 32 bit)
  • HKLM:\Software\Wow6432Node\Microsoft\Powershell\1\PowerShellEngine\RuntimeVersion (32 bit on 64 bit machine)

Change the value of that key to the required version. Keep in mind though that some snapins may no longer load unless they are .NET 4 compatible (WASP is the only one I have had trouble with, but I don't really use it anyway). VMWare, SQL Server 2008, PSCX, Active Directory (Microsoft and Quest Software) and SCOM all work fine.

"Application tried to present modally an active controller"?

Instead of using:

self.present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)

you can use:

self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)

How do you remove duplicates from a list whilst preserving order?

Relatively effective approach with _sorted_ a numpy arrays:

b = np.array([1,3,3, 8, 12, 12,12])    
numpy.hstack([b[0], [x[0] for x in zip(b[1:], b[:-1]) if x[0]!=x[1]]])

Outputs:

array([ 1,  3,  8, 12])

Custom events in jQuery?

I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:

$('#myInput').keydown(function(ev) {
    if (ev.which == 13) {
        ev.preventDefault();
        // Do some stuff that handles the enter key
    }
});

I want to abbreviate it to this:

$('#myInput').enterKey(function() {
    // Do some stuff that handles the enter key
});

trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring

The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:

(function($){
    $('body').on('keydown', 'input', function(ev) {
        if (ev.which == 13) {
            var enterEv = $.extend({}, ev, { type: 'enterKey' });
            return $(ev.target).trigger(enterEv);
        }
    });

    $.fn.enterKey = function(selector, data, fn) {
        return this.on('enterKey', selector, data, fn);
    };
})(jQuery);

http://jsfiddle.net/b9chris/CkvuJ/4/

A nicety of the above is you can handle keyboard input gracefully on link listeners like:

$('a.button').on('click enterKey', function(ev) {
    ev.preventDefault();
    ...
});

Edits: Updated to properly pass the right this context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.

Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Installing MySQL Python on Mac OS X

To install PyMySQL

install pip => sudo easy_install pip

install PyMySQL=> sudo easy_install-3.7 pymysql

terminal command to check whether installed or not => pip3 list

or

install PyMySQL=> sudo pip install PyMySQL

terminal command to check whether installed or not => pip3 list

MySQL

The macOS Sierra Public Beta’s didn’t play well with MySQL 5.7.x, but these issues are now resolved by using MySQL 5.7.16

MySQL doesn’t come pre-loaded with macOS Sierra and needs to be dowloaded from the MySQL site.

( https://dev.mysql.com/downloads/mysql/) The latest version of MySQL 5.7.16 does work with the public release of macOS.

If you already have MySQL 5.7 and you have upgraded OS from El Capitan to Sierra I expect that to be ok, but will be interested if anyone comments on that.

Use the Mac OS X 10.11 (x86, 64-bit), DMG Archive version (works on macOS Sierra).

If you are upgrading from a previous OSX and have an older MySQL version you do not have to update it. One thing with MySQL upgrades always take a data dump of your database in case things go south and before you upgrade to macOS Sierra make sure your MySQL Server is not running.

When downloading you don’t have to sign up, look for » No thanks, just take me to the downloads! – go straight to the download mirrors and download the software from a mirror which is closest to you.

Once downloaded open the .dmg and run the installer.

When it is finished installing you get a dialog box with a temporary mysql root password – that is a MySQL root password not a macOS admin password, copy and paste it so you can use it. But I have found that the temporary password is pretty much useless so we’ll need to change it straight away.

You are also told: If you lose this password, please consult the section How to Reset the Root Password in the MySQL reference manual.(https://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html)

Change the MySQL root password

Note that this is not the same as the root or admin password of macOS – this is a unique password for the mysql root user, use one and remember/jot down somewhere what it is.

Stop MySQL

sudo /usr/local/mysql/support-files/mysql.server stop

if stop throws permission issue

Check the error file first.

tail -f /usr/local/mysql/data/*.err

Do a complete shut down or kill the process. Confirm that no mysql process is running

mysqladmin -uroot shutdown
sudo killall mysqld 

ps -ef | grep mysql

Give permisiions

sudo chown -RL root:mysql /usr/local/mysql
sudo chown -RL mysql:mysql /usr/local/mysql/data
chmod -R 755 /usr/local/mysql/data
chmod -R 755 /usr/local/mysql/data/accountname.local.pid

or Right click->get info and change the permission for 
/usr/local/mysql/data
/usr/local/mysql/data/Pushparajas-MacBook-Pro.local.pid

Start mysql

sudo mysql.server start

Start it in safe mode:

sudo mysqld_safe --skip-grant-tables

This will be an ongoing command until the process is finished so open another shell/terminal window, and log in with a password which is temporary generated:

mysql -u root -p
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass'

; Change the lowercase ‘MyNewPass’ to what you want – and keep the single quotes.

\q

Start MySQL

sudo /usr/local/mysql/support-files/mysql.server start

Starting MySQL

You can then start the MySQL server from the System Preferences or via the command line.

Command line start MySQL.

sudo /usr/local/mysql/support-files/mysql.server start

To find the MySQL version from the terminal, type at the prompt:

/usr/local/mysql/bin/mysql -v -uroot -p

This also puts you in to a shell interactive dialogue with mySQL, type \q to exit.

After installation, in order to use mysql commands without typing the full path to the commands you need to add the mysql directory to your shell path, (optional step) this is done in your “.bash_profile” file in your home directory, if you don’t have that file just create it using vi or nano:

cd ; nano .bash_profile
export PATH="/usr/local/mysql/bin:$PATH"

The first command brings you to your home directory and opens the .bash_profile file or creates a new one if it doesn’t exist, then add in the line above which adds the mysql binary path to commands that you can run. Exit the file with type “control + x” and when prompted save the change by typing “y”. Last thing to do here is to reload the shell for the above to work straight away.

source ~/.bash_profile
mysql -v

You will get the version number again, just type “q” to exit.

Fix the 2002 MySQL Socket error

Fix the looming 2002 socket error – which is linking where MySQL places the socket and where macOS thinks it should be, MySQL puts it in /tmp and macOS looks for it in /var/mysql the socket is a type of file that allows mysql client/server communication.

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

phpMyAdmin

uncomment below line in httpd.conf file

LoadModule php7_module libexec/apache2/libphp7.so

First fix the 2002 socket error if you haven’t done so from the MySQL section-

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

Download phpMyAdmin, (https://www.phpmyadmin.net/downloads/) the zip English package will suit a lot of users, then unzip it and move the folder with its contents into the document root level(~/Sites/) renaming folder to ‘phpmyadmin’.

Make the config folder

mkdir ~/Sites/phpmyadmin/config

Change the permissions

chmod o+w ~/Sites/phpmyadmin/config

Run the set up in the browser http://localhost/~username/phpmyadmin/setup/ or http://localhost/phpmyadmin/setup/

You need to create a new localhost mysql server connection, click new server.

Switch to the Authentication tab and set the local mysql root user and the password.

Add in the username “root” (maybe already populated, add in the password that you set up earlier for the MySQL root user set up, click on save and you are returned to the previous screen. (This is not the macOS Admin or root password – it is the MySQL root user).

Make sure you click on save, then a config.inc.php is now in the /config directory of phpmyadmin directory, move this file to the root level of /phpmyadmin and then remove the now empty /config directory.

In the latest phpmyadmin, download the config.inc.php and place in phpmyadmin directory.

If you want to setup new server move config.inc.php to some location and try http://localhost/~username/phpmyadmin/setup

Now going to http://localhost/~username/phpmyadmin/ will now allow you to interact with your MySQL databases.

To upgrade phpmyadmin just download the latest version and copy the older ‘config.inc.php‘ from the existing directory into the new folder and replace – backup the older one just in case.

Permissions

To run a website with no permission issues it is best to set the web root and its contents to be writeable by all, since it’s a local development it shouldn’t be a security issue.

Lets say that you have a site in the User Sites folder at the following location ~/Sites/testsite you would set it to be writeable like so:

sudo chmod -R a+w ~/Sites/testsite

If you are concerned about security then instead of making it world writeable you can set the owner to be Apache _www but when working on files you would have to authenticate more as admin you are “not” the owner, you would do this like so:

sudo chown -R _www ~/Sites/testsite

This will set the contents recursively to be owned by the Apache user. If you had the website stored at the System level Document root at say ~/Sites/testsite then it would have to be the latter:

sudo chown -R _www ~/Sites/testsite

Another easier way to do this if you have a one user workstation is to change the Apache web user from _www to your account. That’s it! You now have the native AMP stack running on top of macOS Sierra.

Ref Link - https://coolestguidesontheplanet.com/get-apache-mysql-php-and-phpmyadmin-working-on-macos-sierra/#ssu

sql ORDER BY multiple values in specific order?

For someone who is new to ORDER BY with CASE this may be useful

ORDER BY 
    CASE WHEN GRADE = 'A' THEN 0
         WHEN GRADE = 'B' THEN 1
         ELSE 2 END

No module named setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

What is the best way to iterate over a dictionary?

C# 7.0 introduced Deconstructors and if you are using .NET Core 2.0+ Application, the struct KeyValuePair<> already include a Deconstruct() for you. So you can do:

var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
    Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
    Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
    Console.WriteLine($"Item [{key}] = {value}");
}

enter image description here

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

When I had this issue with tf.train.string_input_producer() and tf.train.batch() initializing the local variables before I started the Coordinator solved the problem. I had been getting the error when I initialized the local variables after starting the Coordinator.

Spring Boot - inject map from application.yml

You can have a map injected using @ConfigurationProperties:

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class MapBindingSample {

    public static void main(String[] args) throws Exception {
        System.out.println(SpringApplication.run(MapBindingSample.class, args)
                .getBean(Test.class).getInfo());
    }

    @Bean
    @ConfigurationProperties
    public Test test() {
        return new Test();
    }

    public static class Test {

        private Map<String, Object> info = new HashMap<String, Object>();

        public Map<String, Object> getInfo() {
            return this.info;
        }
    }
}

Running this with the yaml in the question produces:

{build={artifact=${project.artifactId}, version=${project.version}, name=${project.name}, description=${project.description}}}

There are various options for setting a prefix, controlling how missing properties are handled, etc. See the javadoc for more information.

Understanding __getitem__ method

The magic method __getitem__ is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.

Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__ method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.

import copy

# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1

class Person(object):
    def __init__(self, name, age, dob):
        self.name = name
        self.age = age
        self.dob = dob

    def __getitem__(self, indx):
        print ("Calling __getitem__")
        p = copy.copy(self)

        p.name = p.name.split(" ")[indx]
        p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
        return p

Suppose one user input is as follows:

p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))

With the help of __getitem__ method, the user can access the indexed attributes. e.g.,

print p[0].name # print first (or last) name
print p[Y].dob  # print (Date or Month or ) Year of the 'date of birth'

How do I use LINQ Contains(string[]) instead of Contains(string)

How about:

from xx in table
where stringarray.Contains(xx.uid.ToString())
select xx

Bootstrap 3 Navbar Collapse

these are controlled in variables, no need to muck around in source. with bootstrap, try variables first, then overrides. then go back and try variables again ;)

i used bootstrap-sass with rails, but it's the same with the default LESS.

FILE: main.css.scss
-------------------

// control the screen sizes
$screen-xs-min: 300px;
$screen-sm-min: 400px;
$screen-md-min: 800px;
$screen-lg-min: 1200px;

// this tells which screen size to use to start breaking on
// will tell navbar when to collapse
$grid-float-breakpoint: $screen-md-min;

// then import your bootstrap
@import "bootstrap";

that's it! this variables reference page is super handy: https://github.com/twbs/bootstrap/blob/master/less/variables.less

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

How to trap on UIViewAlertForUnsatisfiableConstraints?

This usually appears when you want to use UIActivityViewController in iPad.

Add below, before you present the controller to mark the arrow.

activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC

I assume you already have below, if not, add together:

activityViewController.popoverPresentationController?.sourceView = self.view

Is it possible to compile a program written in Python?

Avoiding redundancy I don't repeat my answer here again.

Please refer to my answer here. (note that answer only covers compiling to python bytecode.)

What characters do I need to escape in XML documents?

In addition to the commonly known five characters [<, >, &, ", and '], I would also escape the vertical tab character (0x0B). It is valid UTF-8, but not valid XML 1.0, and even many libraries (including the highly portable (ANSI C) library libxml2) miss it and silently output invalid XML.

Can we instantiate an abstract class?

Technical Answer

Abstract classes cannot be instantiated - this is by definition and design.

From the JLS, Chapter 8. Classes:

A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses.

From JSE 6 java doc for Classes.newInstance():

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.

A Different Angle On This - Teamplay & Social Intelligence:

This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.

"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??

Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.

How to extract epoch from LocalDate and LocalDateTime?

Look at this method to see which fields are supported. You will find for LocalDateTime:

•NANO_OF_SECOND 
•NANO_OF_DAY 
•MICRO_OF_SECOND 
•MICRO_OF_DAY 
•MILLI_OF_SECOND 
•MILLI_OF_DAY 
•SECOND_OF_MINUTE 
•SECOND_OF_DAY 
•MINUTE_OF_HOUR 
•MINUTE_OF_DAY 
•HOUR_OF_AMPM 
•CLOCK_HOUR_OF_AMPM 
•HOUR_OF_DAY 
•CLOCK_HOUR_OF_DAY 
•AMPM_OF_DAY 
•DAY_OF_WEEK 
•ALIGNED_DAY_OF_WEEK_IN_MONTH 
•ALIGNED_DAY_OF_WEEK_IN_YEAR 
•DAY_OF_MONTH 
•DAY_OF_YEAR 
•EPOCH_DAY 
•ALIGNED_WEEK_OF_MONTH 
•ALIGNED_WEEK_OF_YEAR 
•MONTH_OF_YEAR 
•PROLEPTIC_MONTH 
•YEAR_OF_ERA 
•YEAR 
•ERA 

The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate (with even less supported fields).

If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.

Coming back to your question and the numbers in your code:

The result 1605 is correct
  => (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1

16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).

UPDATE after given timezone info:

local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861

As JSR-310-code with two equivalent approaches:

long secondsSinceUnixEpoch1 =
  LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();

long secondsSinceUnixEpoch2 =
  LocalDate
    .of(2014, 2, 4)
    .atTime(19, 51, 1)
    .atZone(ZoneId.of("Europe/Oslo"))
    .toEpochSecond();

Using str_replace so that it only acts on the first match?

To expand on zombat's answer (which I believe to be the best answer), I created a recursive version of his function that takes in a $limit parameter to specify how many occurrences you want to replace.

function str_replace_limit($haystack, $needle, $replace, $limit, $start_pos = 0) {
    if ($limit <= 0) {
        return $haystack;
    } else {
        $pos = strpos($haystack,$needle,$start_pos);
        if ($pos !== false) {
            $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
            return str_replace_limit($newstring, $needle, $replace, $limit-1, $pos+strlen($replace));
        } else {
            return $haystack;
        }
    }
}

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

How to avoid "StaleElementReferenceException" in Selenium?

Try this

while (true) { // loops forever until break
    try { // checks code for exceptions
        WebElement ele=
        (WebElement)wait.until(ExpectedConditions.elementToBeClickable((By.xpath(Xpath))));  
        break; // if no exceptions breaks out of loop
    } 
    catch (org.openqa.selenium.StaleElementReferenceException e1) { 
        Thread.sleep(3000); // you can set your value here maybe 2 secs
        continue; // continues to loop if exception is found
    }
}

C# Remove object from list of objects

Simplest solution without using LINQ:

    Chunk toRemove = null;
    foreach (Chunk i in ChunkList)
    {
        if (i.UniqueID == ChunkID)
        {
            toRemove = i;
            break;
        }
    }
    if (toRemove != null) {
        ChunkList.Remove(toRemove);
    }

(If Chunk is a struct, then you can use Nullable<Chunk> to achieve this.)

How do I format currencies in a Vue component?

With vuejs 2, you could use vue2-filters which does have other goodies as well.

npm install vue2-filters


import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

Then use it like so:

{{ amount | currency }} // 12345 => $12,345.00

Ref: https://www.npmjs.com/package/vue2-filters

Filtering DataGridView without changing datasource

I have a clearer proposal on automatic search in a DataGridView

this is an example

private void searchTb_TextChanged(object sender, EventArgs e)
    {
        try
        {
            (lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
                "lename IS NOT NULL" :
                String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
        }
        catch (Exception ex) {
            MessageBox.Show(ex.StackTrace);
        }
    }

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

What is the difference between Class.getResource() and ClassLoader.getResource()?

All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String) and class.getClassLoader().getResourceAsStream(String). This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).

MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!  
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!

Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String) in the past and haven't had any problems.

PS: I also posted this over here

How to add elements of a Java8 stream into an existing List

Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.

Anyway, you can use the following one-liner, if you really need this functionality.

But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...

list.stream().collect(Collectors.toCollection(() -> myExistingList));

Slide right to left?

GreenSock Animation Platform (GSAP) with TweenLite / TweenMax provides much smoother transitions with far greater customization than jQuery or CSS3 transitions. In order to animate CSS properties with TweenLite / TweenMax, you'll also need their plugin called "CSSPlugin". TweenMax includes this automatically.

First, load the TweenMax library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>

Or the lightweight version, TweenLite:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenLite.min.js"></script>

Then, call your animation:

 var myObj= document.getElementById("myDiv");

// Syntax: (target, speed, {distance, ease})
 TweenLite.to(myObj, .7, { x: 500, ease: Power3.easeOut});

You can also call it with an ID selector:

 TweenLite.to("#myID", .7, { x: 500, ease: Power3.easeOut});

If you have jQuery loaded, you can use more advanced broad selectors, like all elements containing a specific class:

 // This will parse the selectors using jQuery's engine.
TweenLite.to(".myClass", .7, { x: 500, ease: Power3.easeOut});

For full details, see: TweenLite Documentation

According to their website: "TweenLite is an extremely fast, lightweight, and flexible animation tool that serves as the foundation of the GreenSock Animation Platform (GSAP)."

Find duplicate records in a table using SQL Server

Select EventID,count() as cnt from dbo.EventInstances group by EventID having count() > 1

Add/Delete table rows dynamically using JavaScript

This code may help some one

    <HTML>
<HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <style type="text/css">
        .democlass{
            color:red;
        }
    </style>
    <SCRIPT language="javascript">
        function addRow(tableID) {

            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var colCount = table.rows[0].cells.length;

            var row = table.insertRow(rowCount);
            for(var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            }

            row = table.insertRow(table.rows.length);
            for(var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            }

            row = table.insertRow(table.rows.length);
            for(var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[2].cells[i].innerHTML;
            }

            row = table.insertRow(table.rows.length);
            for(var i = 0; i < colCount; i++) {

                var newcell = row.insertCell(i);
                if(i == (colCount - 1)) {
                    newcell.innerHTML = "<INPUT type=\"button\" value=\"Delete Row\" onclick=\"removeRow(this)\"/>";
                } else {
                    newcell.innerHTML = table.rows[3].cells[i].innerHTML;
                }
            }
        }

        /**
         * This method deletes the specified section of the table
         * OR deletes the specified rows from the table.
         */
        function removeRow(src) {

            var oRow = src.parentElement.parentElement;
            var rowsCount = 0;
            for(var index = oRow.rowIndex; index >= 0; index--) {

                document.getElementById("dataTable").deleteRow(index);
                if(rowsCount == (4 - 1)) {
                    return;
                }
                rowsCount++;
            }
            //once the row reference is obtained, delete it passing in its rowIndex
            /* document.getElementById("dataTable").deleteRow(oRow.rowIndex); */
        }
    </SCRIPT>
</HEAD>
<BODY>
    <form name="myForm">
        <TABLE id="dataTable" width="350px" border="1">
            <TR>
                <TD>
                    <INPUT type="checkbox" name="chk"/>
                </TD>
                <TD>
                    Code
                </TD>
                <TD>
                    <INPUT type="text" name="txt"/>
                </TD>
                <TD>
                    Select Country
                </TD>
                <TD>
                    <SELECT name="country">
                        <OPTION value="in">India</OPTION>
                        <OPTION value="de">Germany</OPTION>
                        <OPTION value="fr">France</OPTION>
                        <OPTION value="us">United States</OPTION>
                        <OPTION value="ch">Switzerland</OPTION>
                    </SELECT>
                </TD>
            </TR>
            <TR>
                <TD>&nbsp;</TD>
                <TD>
                    First Name
                </TD>
                <TD>
                    <INPUT type="text" name="txt1"/>
                </TD>
                <TD>
                    Last Name
                </TD>
                <TD>
                    <INPUT type="text" name="txt2"/>
                </TD>
            </TR>
            <TR>
                <TD>&nbsp;</TD>
                <TD>Phone</TD>
                <TD>
                    <INPUT type="text" name="txt3"/>
                </TD>
                <TD>Address</TD>
                <TD>
                    <INPUT type="text" name="txt4" class="democlass"/>
                </TD>
            </TR>
            <TR>
                <TD>&nbsp;</TD>
                <TD>&nbsp;</TD>
                <TD>
                    &nbsp;
                </TD>
                <TD>&nbsp;</TD>
                <TD>
                    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
                </TD>
            </TR>
        </TABLE>
</BODY>
</HTML>

How to avoid reverse engineering of an APK file?

Its not possible to completely avoid RE but By making them more complex internally, you put make it more difficult for attackers to see the clear operation of the app, which may reduce the number of attack vectors.

If the application handles highly sensitive data, Various techniques exist which can increase the complexity of reverse engineering your code. One technique is to use C/C++ to limit easy runtime manipulation by the attacker. There are ample C and C++ libraries that are very mature and easy to integrate with Android offers JNI. An attacker must first circumvent the debugging restrictions in order to attack the application on a low level. This adds further complexity to an attack. Android applications should have android:debuggable=”false” set in the application manifest to prevent easy run time manipulation by an attacker or malware.

Trace Checking – An application can determine whether or not it is currently being traced by a debugger or other debugging tool. If being traced, the application can perform any number of possible attack response actions, such as discarding encryption keys to protect user data, notifying a server administrator, or other such type responses in an attempt to defend itself. This can be determined by checking the process status flags or using other techniques like comparing the return value of ptrace attach, checking parent process, blacklist debuggers in the process list or comparing timestamps on different places of the program.

Optimizations - To hide advanced mathematical computations and other types of complex logic, utilizing compiler optimizations can help obfuscate the object code so that it cannot easily be disassembled by an attacker, making it more difficult for an attacker to gain an understanding of the particular code. In Android this can more easily be achieved by utilizing natively compiled libraries with the NDK. In addition, using an LLVM Obfuscator or any protector SDK will provide better machine code obfuscation.

Stripping binaries – Stripping native binaries is an effective way to increase the amount of time and skill level required of an attacker in order to view the makeup of your application’s low level functions. By stripping a binary, the symbol table of the binary is stripped, so that an attacker cannot easily debug or reverse engineer an application.You can refer techniques used on GNU/Linux systems like sstriping or using UPX.

And at last you must be aware about obfuscation and tools like ProGuard.

How to use a variable for the database name in T-SQL?

Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:

SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)

and then run it with

EXECUTE (@SQL_SCRIPT)

It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!

You can't EXEC multiple batches. GO is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC each one after substitution.

I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO; I've done that in ADO.NET code.

And where did I get the word "SERVERNAME" from?

Here's some code that I just tested (and which works):

DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'

DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)

SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'

DECLARE @SQL_SCRIPT VARCHAR(MAX)

SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)

Always show vertical scrollbar in <select>

It will work in IE7. But here you need to fixed the size less than the number of option and not use overflow-y:scroll. In your example you have 2 option but you set size=10, which will not work.

Suppose your select has 10 option, then fixed size=9.

Here, in your code reference you used height:100px with size:2. I remove the height css, because its not necessary and change the size:5 and it works fine.

Here is your modified code from jsfiddle:

<select size="5" style="width:100px;">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
</select>

this will generate a larger select box than size:2 create.In case of small size the select box will not display the scrollbar,you have to check with appropriate size quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2 and size greater than 2(e.g: 3,5).

Here is your desired result. I think this will help you:

CSS

  .wrapper{
    border: 1px dashed red;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 150px;
 }
 .wrapper .selection{
   width:150px;
   border:1px solid #ccc
 }

HTML

<div class="wrapper">
<select size="15" class="selection">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>
</div>

How to clear Flutter's Build cache?

I tried flutter clean and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.

How to rotate the background image in the container?

Very well done and answered here - http://www.sitepoint.com/css3-transform-background-image/

#myelement:before
{
    content: "";
    position: absolute;
    width: 200%;
    height: 200%;
    top: -50%;
    left: -50%;
    z-index: -1;
    background: url(background.png) 0 0 repeat;
    -webkit-transform: rotate(30deg);
    -moz-transform: rotate(30deg);
    -ms-transform: rotate(30deg);
    -o-transform: rotate(30deg);
    transform: rotate(30deg);
}

Disabling Chrome Autofill

Try this. I know the question is somewhat old, but this is a different approach for the problem.

I also noticed the issue comes just above the password field.

I tried both the methods like

<form autocomplete="off"> and <input autocomplete="off"> but none of them worked for me.

So I fixed it using the snippet below - just added another text field just above the password type field and made it display:none.

Something like this:

<input type="text" name="prevent_autofill" id="prevent_autofill" value="" style="display:none;" />
<input type="password" name="password_fake" id="password_fake" value="" style="display:none;" />
<input type="password" name="password" id="password" value="" />

Hope it will help someone.

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

tl;dr set both the soft and hard limits

I'm sure it's working as intended but I'll add it here just in case. For completeness the limit is set here (see below for syntax): /etc/security/limits.conf

some_user       soft    nofile          60000
some_user       hard    nofile          60000

and activated with the following in /etc/pam.d/common-session:

session required pam_limits.so

If you set only the hard limit, ulimit -a will show the default (1024): If you set only the soft the limit ulimit -a will show (4096)

If you set them both ulimit -a will show the soft limit (up to the hard limit of course)

What is the meaning of 'No bundle URL present' in react-native?

Solution --> npm start then open new Terminal and go to your project path and then hit react-native run-ios it works for me

Definitive way to trigger keypress events with jQuery

I made it work with keyup.

$("#id input").trigger('keyup');

How to trigger an event in input text after I stop typing/writing?

There is some simple plugin I've made that does exacly that. It requires much less code than proposed solutions and it's very light (~0,6kb)

First you create Bid object than can be bumped anytime. Every bump will delay firing Bid callback for next given ammount of time.

var searchBid = new Bid(function(inputValue){
    //your action when user will stop writing for 200ms. 
    yourSpecialAction(inputValue);
}, 200); //we set delay time of every bump to 200ms

When Bid object is ready, we need to bump it somehow. Let's attach bumping to keyup event.

$("input").keyup(function(){
    searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});

What happens here is:

Everytime user presses key, bid is 'delayed' (bumped) for next 200ms. If 200ms will pass without beeing 'bumped' again, callback will be fired.

Also, you've got 2 additional functions for stopping bid (if user pressed esc or clicked outside input for example) and for finishing and firing callback immediately (for example when user press enter key):

searchBid.stop();
searchBid.finish(valueToPass);

Declaring multiple variables in JavaScript

I think the first way (multiple variables) is best, as you can otherwise end up with this (from an application that uses KnockoutJS), which is difficult to read in my opinion:

    var categories = ko.observableArray(),
        keywordFilter = ko.observableArray(),
        omniFilter = ko.observable('').extend({ throttle: 300 }),
        filteredCategories = ko.computed(function () {
            var underlyingArray = categories();
            return ko.utils.arrayFilter(underlyingArray, function (n) {
                return n.FilteredSportCount() > 0;
            });
        }),
        favoriteSports = ko.computed(function () {
            var sports = ko.observableArray();
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        sports.push(a);
                    }
                });
            });
            return sports;
        }),
        toggleFavorite = function (sport, userId) {
            var isFavorite = sport.IsFavorite();

            var url = setfavouritesurl;

            var data = {
                userId: userId,
                sportId: sport.Id(),
                isFavourite: !isFavorite
            };

            var callback = function () {
                sport.IsFavorite(!isFavorite);
            };

            jQuery.support.cors = true;
            jQuery.ajax({
                url: url,
                type: "GET",
                data: data,
                success: callback
            });
        },
        hasfavoriteSports = ko.computed(function () {
            var result = false;
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        result = true;
                    }
                });
            });
            return result;
        });

How to open URL in Microsoft Edge from the command line?

I would like to recommend:
Microsoft Edge Run Wrapper
https://github.com/mihula/RunEdge

You run it this way:

RunEdge.exe [URL]
  • where URL may or may not contains protocol (http://), when not provided, wrapper adds http://
  • if URL not provided at all, it just opens edge

Examples:

RunEdge.exe http://google.com
RunEdge.exe www.stackoverflow.com

It is not exactly new way how to do it, but it is wrapped as exe file, which could be useful in some situations. For me it is way how to start Edge from IBM Notes Basic client.

curl POST format for CURLOPT_POSTFIELDS

According to the PHP manual, data passed to cURL as a string should be URLencoded. See the page for curl_setopt() and search for CURLOPT_POSTFIELDS.

NULL or BLANK fields (ORACLE)

First, you know that "blank" and "null" are two COMPLETELY DIFFERENT THINGS? Correct?

Second: in most programming languages, "" means an "empty string". A zero-length string. No characters in it.

SQL doesn't necessarily work like that. If I define a column "name char(5)", then a "blank" name will be " " (5 spaces).

It sounds like you might want something like this:

select count(*) from my_table where Length(trim(my_column)) = 0;

"Trim()" is one of many Oracle functions you can use in PL/SQL. It's documented here:

http://www.techonthenet.com/oracle/functions/trim.php

'Hope that helps!

How do I run a program with commandline arguments using GDB within a Bash script?

In addition to the answer of Hugo Ideler. When using arguments having themself prefix like -- or -, I was not sure to conflict with gdb one.

It seems gdb takes all after args option as arguments for the program.

At first I wanted to be sure, I ran gdb with quotes around your args, it is removed at launch.

This works too, but optional:

gdb --args executablename "--arg1" "--arg2" "--arg3"

This doesn't work :

gdb --args executablename "--arg1" "--arg2" "--arg3" -tui

In that case, -tui is used as my program parameter not as gdb one.

JavaScript Extending Class

For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.

     function AbstractClass() {
      this.superclass_method = function(message) {
          // do something
        };
     }

     function Child() {
         AbstractClass.apply(this);
         // Now Child will have superclass_method()
     }

Example on angularjs:

http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview

app.service('noisyThing', 
  ['notify',function(notify){
    this._constructor = function() {
      this.scream = function(message) {
          message = message + " by " + this.get_mouth();
          notify(message); 
          console.log(message);
        };

      this.get_mouth = function(){
        return 'abstract mouth';
      }
    }
  }])
  .service('cat',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.meow = function() {
      this.scream('meooooow');
    }
    this.get_mouth = function(){
      return 'fluffy mouth';
    }
  }])
  .service('bird',
  ['noisyThing', function(noisyThing){
    noisyThing._constructor.apply(this)
    this.twit = function() {
      this.scream('fuuuuuuck');
    }
  }])

How to put a jpg or png image into a button in HTML

you can also try something like this as well

<input type="button" value="text" name="text" onClick="{action}; return false" class="fwm_button">

and CSS class

.fwm_button {
   color: white;
   font-weight: bold;
   background-color: #6699cc;
   border: 2px outset;
   border-top-color: #aaccff;
   border-left-color: #aaccff;
   border-right-color: #003366;
   border-bottom-color: #003366;
 }

An example is given here

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

How to change default install location for pip

According to pip documentation at

http://pip.readthedocs.org/en/stable/user_guide/#configuration

You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows

On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf

On Windows, the configuration file is: %HOME%\pip\pip.ini

The %HOME% is located in C:\Users\Bob on windows assuming your name is Bob

On linux the $HOME directory can be located by using cd ~

You may have to create the pip.ini file when you find your pip directory. Within your pip.ini or pip.config you will then need to put (assuming your on windows) something like

[global]
target=C:\Users\Bob\Desktop

Except that you would replace C:\Users\Bob\Desktop with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path

After saving the command would then be

pip install pandas

However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.

How do I change the default port (9000) that Play uses when I execute the "run" command?

Hope this helps someone.

via sbt settings:

...
.settings(PlayKeys.playDefaultPort := 8855)
...

apache and httpd running but I can't see my website

There are several possibilities.

  • firewall, iptables configuration
  • apache listen address / port

More information is needed about your configuration. What distro are you using? Can you connect via 127.0.0.1?

If the issue is with the firewall/iptables, you can add the following lines to /etc/sysconfig/iptables:

-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

(Second line is only needed for https)

Make sure this is above any lines that would globally restrict access, like the following:

-A INPUT -j REJECT --reject-with icmp-host-prohibited

Tested on CentOS 6.3

And finally

service iptables restart

How do I do top 1 in Oracle?

You can do something like

    SELECT *
      FROM (SELECT Fname FROM MyTbl ORDER BY Fname )
 WHERE rownum = 1;

You could also use the analytic functions RANK and/or DENSE_RANK, but ROWNUM is probably the easiest.

Subtract two variables in Bash

You just need a little extra whitespace around the minus sign, and backticks:

COUNT=`expr $FIRSTV - $SECONDV`

Be aware of the exit status:

The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.

Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.

How to convert a byte array to its numeric value (Java)?

Each cell in the array is treated as unsigned int:

private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
    return res;


for (int i=0;i<bytes.length;i++){
    res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}

Spring Security with roles and permissions

ACL was overkill for my requirements also.
I ended up creating a library similar to @Alexander's to inject a GrantedAuthority list for Role->Permissions based on the role membership of a user.

For example, using a DB to hold the relationships -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.

This library provides 2 built-in integration points for Spring Security. When the integration point is reached, the PermissionProvider is called to get the effective permissions for each role the user is a member of.
The distinct list of permissions are added as GrantedAuthority items in the Authentication object.

You can also implement a custom PermissionProvider to store the relationships in config for example.

A more complete explanation here - https://stackoverflow.com/a/60251931/1308685

And the source code is here - https://github.com/savantly-net/spring-role-permissions

1030 Got error 28 from storage engine

Check your /backup to see if you can delete an older not needed backup.

How can I tell jaxb / Maven to generate multiple schema packages?

There is another, a clear one (IMO) solution to this There is a parameter called "staleFile" that uses as a flag to not generate stuff again. Simply alter it in each execution.

Equivalent of explode() to work with strings in MySQL

This is actually a modified version of the selected answer in order to support Unicode characters but I don't have enough reputation to comment there.

CREATE FUNCTION SPLIT_STRING(str VARCHAR(255) CHARSET utf8, delim VARCHAR(12), pos INT) RETURNS varchar(255) CHARSET utf8
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
       CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
       delim, '')

The modifications are the following:

  • The first parameter is set as utf8
  • The function is set to return utf8
  • The code uses CHAR_LENGTH() instead of LENGTH() to calculate the character length and not the byte length.

Return multiple values from a SQL Server function

Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters

Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

http://192.168.180.1:8000

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

Plot correlation matrix using pandas

Along with other methods it is also good to have pairplot which will give scatter plot for all the cases-

import pandas as pd
import numpy as np
import seaborn as sns
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
sns.pairplot(df)

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

You can put the jQuery's Ajax setup in synchronous mode by calling

jQuery.ajaxSetup({async:false});

And then perform your Ajax calls using jQuery.get( ... );

Then just turning it on again once

jQuery.ajaxSetup({async:true});

I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get() or jQuery.post() to the more elaborate jQuery.ajax() syntax.

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

How do I measure execution time of a command on the Windows command line?

I'm using Windows XP and for some reason timeit.exe does not work for me. I found another alternative - PTIME. This works very well.

http://www.pc-tools.net/win32/ptime/

Example -

C:\> ptime

ptime 1.0 for Win32, Freeware - http://www.pc-tools.net/
Copyright(C) 2002, Jem Berkes <[email protected]>

Syntax: ptime command [arguments ...]

ptime will run the specified command and measure the execution time
(run time) in seconds, accurate to 5 millisecond or better. It is an
automatic process timer, or program timer.


C:\> ptime cd

ptime 1.0 for Win32, Freeware - http://www.pc-tools.net/
Copyright(C) 2002, Jem Berkes <[email protected]>

===  cd ===
C:\

Execution time: 0.015 s

CSS for grabbing cursors (drag & drop)

CSS3 grab and grabbing are now allowed values for cursor. In order to provide several fallbacks for cross-browser compatibility3 including custom cursor files, a complete solution would look like this:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Internet Explorer */
    cursor: -webkit-grab; /* Chrome 1-21, Safari 4+ */
    cursor:    -moz-grab; /* Firefox 1.5-26 */
    cursor:         grab; /* W3C standards syntax, should come least */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: -webkit-grabbing;
    cursor:    -moz-grabbing;
    cursor:         grabbing;
}

Update 2019-10-07:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Chrome 1-21, Firefox 1.5-26, Safari 4+, IE, Edge 12-14, Android 2.1-4.4.4 */
    cursor: grab; /* W3C standards syntax, all modern browser */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: grabbing;
}

How to upgrade all Python packages with pip

You can just print the packages that are outdated:

pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:'

How to set an image as a background for Frame in Swing GUI of java?

The Background Panel entry shows a couple of different ways depending on your requirements.

ImportError: No module named 'pygame'

First execute python3 then type the command import pygame,now you can see the output

No provider for Router?

I had a routerLink="." attribute at one of my HTML tags which caused that error

<code> vs <pre> vs <samp> for inline and block code snippets

Consider TextArea

People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea> which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>, I find <textarea readonly> is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea> might appear within).

For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly> your html or etc with any characters including tabs and CrLf's </textarea>.

_x000D_
_x000D_
<textarea rows=5 cols=100 readonly>Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

To compare all...

_x000D_
_x000D_
<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>_x000D_
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>_x000D_
    _x000D_
    _x000D_
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;</textarea>_x000D_
_x000D_
<xmp>XMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>displayed natively</b>._x000D_
    However, note that &amp; (&) will not act as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</xmp>_x000D_
_x000D_
<pre>PRE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</pre>_x000D_
_x000D_
<samp>SAMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</samp>_x000D_
_x000D_
<code>CODE: Example text with Newlines,_x000D_
tabs & space,_x000D_
  html tags etc <b>are interpreted, not displayed</b>._x000D_
    However, note that &amp; still acts as an escape char.._x000D_
      Eg: &lt;u&gt;(text)&lt;/u&gt;_x000D_
</code>
_x000D_
_x000D_
_x000D_

Sequence contains more than one element

As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.

But to the point i wanted to give you a quick overview.

//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();

//success on 0-n, returns first element in the list or default() if 0 
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();

//success on 0-n, returns first element in the list or default() if 0 
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();

for more Linq expressions have a look at System.Linq.Expressions

Why use Gradle instead of Ant or Maven?

This isn't my answer, but it definitely resonates with me. It's from ThoughtWorks' Technology Radar from October 2012:

Two things have caused fatigue with XML-based build tools like Ant and Maven: too many angry pointy braces and the coarseness of plug-in architectures. While syntax issues can be dealt with through generation, plug-in architectures severely limit the ability for build tools to grow gracefully as projects become more complex. We have come to feel that plug-ins are the wrong level of abstraction, and prefer language-based tools like Gradle and Rake instead, because they offer finer-grained abstractions and more flexibility long term.

Return the most recent record from ElasticSearch index

the _timestamp didn't work out for me,

this query does work for me:

(as in mconlin's answer)

{
  "query": {
    "match_all": {}
  },
  "size": "1",
  "sort": [
    {
      "@timestamp": {
        "order": "desc"
      }
    }
  ]
}

Could be trivial but the _timestamp answer didn't gave an error but not a good result either...

Hope to help someone...

(kibana/elastic 5.0.4)

S.

How to decorate a class?

That's not a good practice and there is no mechanism to do that because of that. The right way to accomplish what you want is inheritance.

Take a look into the class documentation.

A little example:

class Employee(object):

    def __init__(self, age, sex, siblings=0):
        self.age = age
        self.sex = sex    
        self.siblings = siblings

    def born_on(self):    
        today = datetime.date.today()

        return today - datetime.timedelta(days=self.age*365)


class Boss(Employee):    
    def __init__(self, age, sex, siblings=0, bonus=0):
        self.bonus = bonus
        Employee.__init__(self, age, sex, siblings)

This way Boss has everything Employee has, with also his own __init__ method and own members.

How to list all functions in a Python module?

r = globals()
sep = '\n'+100*'*'+'\n' # To make it clean to read.
for k in list(r.keys()):
    try:
        if str(type(r[k])).count('function'):
            print(sep+k + ' : \n' + str(r[k].__doc__))
    except Exception as e:
        print(e)

Output :

******************************************************************************************
GetNumberOfWordsInTextFile : 

    Calcule et retourne le nombre de mots d'un fichier texte
    :param path_: le chemin du fichier à analyser
    :return: le nombre de mots du fichier

******************************************************************************************

    write_in : 

        Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,
        :param path_: le path du fichier texte
        :param data_: la liste des données à écrire ou un bloc texte directement
        :return: None


 ******************************************************************************************
    write_in_as_w : 

            Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,
            :param path_: le path du fichier texte
            :param data_: la liste des données à écrire ou un bloc texte directement
            :return: None

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Selecting just one branch: fetch/merge vs. pull

People often advise you to separate "fetching" from "merging". They say instead of this:

    git pull remoteR branchB

do this:

    git fetch remoteR
    git merge remoteR branchB

What they don't mention is that such a fetch command will actually fetch all branches from the remote repo, which is not what that pull command does. If you have thousands of branches in the remote repo, but you do not want to see all of them, you can run this obscure command:

    git fetch remoteR refs/heads/branchB:refs/remotes/remoteR/branchB
    git branch -a  # to verify
    git branch -t branchB remoteR/branchB

Of course, that's ridiculously hard to remember, so if you really want to avoid fetching all branches, it is better to alter your .git/config as described in ProGit.

Huh?

The best explanation of all this is in Chapter 9-5 of ProGit, Git Internals - The Refspec (or via github). That is amazingly hard to find via Google.

First, we need to clear up some terminology. For remote-branch-tracking, there are typically 3 different branches to be aware of:

  1. The branch on the remote repo: refs/heads/branchB inside the other repo
  2. Your remote-tracking branch: refs/remotes/remoteR/branchB in your repo
  3. Your own branch: refs/heads/branchB inside your repo

Remote-tracking branches (in refs/remotes) are read-only. You do not modify those directly. You modify your own branch, and then you push to the corresponding branch at the remote repo. The result is not reflected in your refs/remotes until after an appropriate pull or fetch. That distinction was difficult for me to understand from the git man-pages, mainly because the local branch (refs/heads/branchB) is said to "track" the remote-tracking branch when .git/config defines branch.branchB.remote = remoteR.

Think of 'refs' as C++ pointers. Physically, they are files containing SHA-digests, but basically they are just pointers into the commit tree. git fetch will add many nodes to your commit-tree, but how git decides what pointers to move is a bit complicated.

As mentioned in another answer, neither

    git pull remoteR branchB

nor

    git fetch remoteR branchB

would move refs/remotes/branches/branchB, and the latter certainly cannot move refs/heads/branchB. However, both move FETCH_HEAD. (You can cat any of these files inside .git/ to see when they change.) And git merge will refer to FETCH_HEAD, while setting MERGE_ORIG, etc.

How to center the elements in ConstraintLayout

you can use layout_constraintCircle for center view inside ConstraintLayout.

<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/mparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageButton
            android:id="@+id/btn_settings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/ic_home_black_24dp"
            app:layout_constraintCircle="@id/mparent"
            app:layout_constraintCircleRadius="0dp"
            />
    </android.support.constraint.ConstraintLayout>

with constraintCircle to parent and zero radius you can make your view be center of parent.

What is middleware exactly?

There is a common definition in web application development which is (and I'm making this wording up but it seems to fit): A component which is designed to modify an HTTP request and/or response but does not (usually) serve the response in its entirety, designed to be chained together to form a pipeline of behavioral changes during request processing.

Examples of tasks that are commonly implemented by middleware:

  • Gzip response compression
  • HTTP authentication
  • Request logging

The key point here is that none of these is fully responsible for responding to the client. Instead each changes the behavior in some way as part of the pipeline, leaving the actual response to come from something later in the sequence (pipeline).

Usually, the middlewares are run before some sort of "router", which examines the request (often the path) and calls the appropriate code to generate the response.

Personally, I hate the term "middleware" for its genericity but it is in common use.

Here is an additional explanation specifically applicable to Ruby on Rails.

How do I edit SSIS package files?

You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.

Have a look at this link:

http://www.microsoft.com/downloads/details.aspx?familyid=3C856B93-369F-4C6F-9357-C35384179543&displaylang=en

Converting bool to text in C++

C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.

C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

boost::lexical_cast<std::string>(my_bool)

Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.

How to get the data-id attribute?

This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Use awk to find average of a column

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'

Add the numbers in $2 (second column) in sum (variables are auto-initialized to zero by awk) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.

awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'

If you want to use the shebang notation, you could write:

#!/bin/awk

{ sum += $2 }
END { if (NR > 0) print sum / NR }

You can also control the format of the average with printf() and a suitable format ("%13.6e\n", for example).

You can also generalize the code to average the Nth column (with N=2 in this sample) using:

awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'

Official way to ask jQuery wait for all images to load before executing something

$(window).load() will work only the first time the page is loaded. If you are doing dynamic stuff (example: click button, wait for some new images to load), this won't work. To achieve that, you can use my plugin:

Demo

Download

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @author:  H. Yankov (hristo.yankov at gmail dot com)
 *  @version: 1.0.0 (Feb/22/2010)
 *  http://yankov.us
 */

(function($) {
$.fn.batchImageLoad = function(options) {
    var images = $(this);
    var originalTotalImagesCount = images.size();
    var totalImagesCount = originalTotalImagesCount;
    var elementsLoaded = 0;

    // Init
    $.fn.batchImageLoad.defaults = {
        loadingCompleteCallback: null, 
        imageLoadedCallback: null
    }
    var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);

    // Start
    images.each(function() {
        // The image has already been loaded (cached)
        if ($(this)[0].complete) {
            totalImagesCount--;
            if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
        // The image is loading, so attach the listener
        } else {
            $(this).load(function() {
                elementsLoaded++;

                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // An image has been loaded
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
            $(this).error(function() {
                elementsLoaded++;

                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // The image has errored
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
        }
    });

    // There are no unloaded images
    if (totalImagesCount <= 0)
        if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);

How to upgrade Angular CLI project?

Just use the build-in feature of Angular CLI

ng update

to update to the latest version.

How to inject window into a service?

You can get window from injected document.

import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

export class MyClass {

  constructor(@Inject(DOCUMENT) private document: Document) {
     this.window = this.document.defaultView;
  }

  check() {
    console.log(this.document);
    console.log(this.window);
  }

}

How can I inspect element in chrome when right click is disabled?

Press F12 to Inspect Element and Ctrl+U to View Page Source

CSS hexadecimal RGBA?

Charming Prince:

Only internet explorer allows the 4 byte hex color in the format of ARGB, where A is the Alpha channel. It can be used in gradient filters for example:

filter  : ~"progid:DXImageTransform.Microsoft.Gradient(GradientType=@{dir},startColorstr=@{color1},endColorstr=@{color2})";

Where dir can be: 1(horizontal) or 0(vertical) And the color strings can be hex colors(#FFAAD3) or argb hex colors(#88FFAAD3).

How to remove certain characters from a string in C++?

remove_if() has already been mentioned. But, with C++0x, you can specify the predicate for it with a lambda instead.

Below is an example of that with 3 different ways of doing the filtering. "copy" versions of the functions are included too for cases when you're working with a const or don't want to modify the original.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

string& remove_chars(string& s, const string& chars) {
    s.erase(remove_if(s.begin(), s.end(), [&chars](const char& c) {
        return chars.find(c) != string::npos;
    }), s.end());
    return s;
}
string remove_chars_copy(string s, const string& chars) {
    return remove_chars(s, chars);
}

string& remove_nondigit(string& s) {
    s.erase(remove_if(s.begin(), s.end(), [](const char& c) {
        return !isdigit(c);
    }), s.end());
    return s;
}
string remove_nondigit_copy(string s) {
    return remove_nondigit(s);
}

string& remove_chars_if_not(string& s, const string& allowed) {
    s.erase(remove_if(s.begin(), s.end(), [&allowed](const char& c) {
        return allowed.find(c) == string::npos;
    }), s.end());
    return s;
}
string remove_chars_if_not_copy(string s, const string& allowed) {
    return remove_chars_if_not(s, allowed);
}

int main() {
    const string test1("(555) 555-5555");
    string test2(test1);
    string test3(test1);
    string test4(test1);
    cout << remove_chars_copy(test1, "()- ") << endl;
    cout << remove_chars(test2, "()- ") << endl;
    cout << remove_nondigit_copy(test1) << endl;
    cout << remove_nondigit(test3) << endl;
    cout << remove_chars_if_not_copy(test1, "0123456789") << endl;
    cout << remove_chars_if_not(test4, "0123456789") << endl;
}

When to use "new" and when not to, in C++?

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

How to use code to open a modal in Angular 2?

Easy way to achieve this in angular 2 or 4 (Assuming that you are using bootstrap 4)

Component.html

_x000D_
_x000D_
<button type="button" (click)="openModel()">Open Modal</button>_x000D_
_x000D_
<div #myModel class="modal fade">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
     <div class="modal-header">_x000D_
        <h5 class="modal-title ">Title</h5>_x000D_
        <button type="button" class="close" (click)="closeModel()">_x000D_
            <span aria-hidden="true">&times;</span>_x000D_
        </button>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>Some text in the modal.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Component.ts

import {Component, OnInit, ViewChild} from '@angular/core';

@ViewChild('myModal') myModal;

openModel() {
  this.myModal.nativeElement.className = 'modal fade show';
}
closeModel() {
   this.myModal.nativeElement.className = 'modal hide';
}

How to change default format at created_at and updated_at value laravel

Laravel 4.x and 5.0

To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
    {
        return 'U';
    }

}

Laravel 5.1+

https://laravel.com/docs/5.1/eloquent

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

How to set default Checked in checkbox ReactJS?

this can be done with pure js

              <Form.Group controlId="categoryStatus">
                <Form.Check
                  type="checkbox"
                  label="Category Status Active/In-active"
                  onChange={this.handleChecked}                 
                />
              </Form.Group>

  //Load category to form : to edit
  GetCategoryById(id) {
    this.UpdateId = id
    axios.get('http://localhost:4000/Category/edit/' + id)
      .then(response => {
        this.setState({
          category_name: response.data.category_name,
          category_description: response.data.category_description,
          is_active: response.data.is_active,
        });

        response.data.is_active == 1 ? document.getElementById("categoryStatus").checked = true : document.getElementById("categoryStatus").checked = false;
      })
      .catch(function (error) {
        console.log(error);
      })
  }


How to set locale in DatePipe in Angular 2?

I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';

Near the bottom is this line:

return DateFormatter.format(value, defaultLocale, pattern);

This suggests to me that the date pipe is currently hard-coded to be 'en-US'.

Please enlighten me if I am wrong.

How do I fix twitter-bootstrap on IE?

Please put the pages in localhost and try

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

if nothing from above works, remove the .class from the listener class i.e.

<listener>
<listener-class>

org.springframework.web.context.ContextLoaderListener.class

</listener-class>
</listener>

How to chain scope queries with OR instead of AND?

Rails 4 + Scope + Arel

class Creature < ActiveRecord::Base
    scope :is_good_pet, -> {
        where(
            arel_table[:is_cat].eq(true)
            .or(arel_table[:is_dog].eq(true))
            .or(arel_table[:eats_children].eq(false))
        )
    }
end

I tried chaining named scopes with .or and no luck, but this worked for finding anything with those booleans set. Generates SQL like

SELECT 'CREATURES'.* FROM 'CREATURES' WHERE ((('CREATURES'.'is_cat' = 1 OR 'CREATURES'.'is_dog' = 1) OR 'CREATURES'.'eats_children' = 0))

Why is my JavaScript function sometimes "not defined"?

My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.

Convert Dictionary to JSON in Swift

You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.

Here is example code that will convert a dictionary of strings to JSON:

Swift 3 version:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: dictionary,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    print("JSON string = \(theJSONText!)")
}

To display the above in "pretty printed" format you'd change the options line to:

    options: [.prettyPrinted]

Or in Swift 2 syntax:

import Foundation
 
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)
let theJSONText = NSString(data: theJSONData!,
  encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")

The output of that is

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"

Or in pretty format:

{
  "anotherKey" : "anotherValue",
  "aKey" : "aValue"
}

The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.

EDIT:

In Swift 3/4 syntax, the code above looks like this:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
  }

Finding whether a point lies inside a rectangle or not

Assuming the rectangle is represented by three points A,B,C, with AB and BC perpendicular, you only need to check the projections of the query point M on AB and BC:

0 <= dot(AB,AM) <= dot(AB,AB) &&
0 <= dot(BC,BM) <= dot(BC,BC)

AB is vector AB, with coordinates (Bx-Ax,By-Ay), and dot(U,V) is the dot product of vectors U and V: Ux*Vx+Uy*Vy.

Update. Let's take an example to illustrate this: A(5,0) B(0,2) C(1,5) and D(6,3). From the point coordinates, we get AB=(-5,2), BC=(1,3), dot(AB,AB)=29, dot(BC,BC)=10.

For query point M(4,2), we have AM=(-1,2), BM=(4,0), dot(AB,AM)=9, dot(BC,BM)=4. M is inside the rectangle.

For query point P(6,1), we have AP=(1,1), BP=(6,-1), dot(AB,AP)=-3, dot(BC,BP)=3. P is not inside the rectangle, because its projection on side AB is not inside segment AB.

How to retrieve images from MySQL database and display in an html tag

I have added slashes before inserting into database so on the time of fetching i removed slashes again stripslashes() and it works for me. I am sharing the code which works for me.

How i inserted into mysql db (blob type)

$db = mysqli_connect("localhost","root","","dName"); 
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO student_img (id,image) VALUES('','$image')";  
$query = mysqli_query($db, $query);

Now to access the image

$sqlQuery = "SELECT * FROM student_img WHERE id = $stid";
$rs = $db->query($sqlQuery);
$result=mysqli_fetch_array($rs);
echo '<img src="data:image/jpeg;base64,'.base64_encode( stripslashes($result['image']) ).'"/>';

Hope it will help someone

Thanks.

Vertical divider doesn't work in Bootstrap 3

.divider-vertical {
height: 50px;
margin: 0 9px;
border-left: 1px solid #F2F2F2;
border-right: 1px solid #FFF;
}

and now you can use it

<ul>
    <li class="divider-vertical"></li>
</ul>

How can I check if a background image is loaded?

Something like this:

var $div = $('div'),
  bg = $div.css('background-image');
  if (bg) {
    var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
      $img = $('<img>').attr('src', src).on('load', function() {
        // do something, maybe:
        $div.fadeIn();
      });
  }
});

List all environment variables from the command line

Simply run set from cmd.

Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Pipe output and capture exit status in Bash

Pure shell solution:

% rm -f error.flag; echo hello world \
| (cat || echo "First command failed: $?" >> error.flag) \
| (cat || echo "Second command failed: $?" >> error.flag) \
| (cat || echo "Third command failed: $?" >> error.flag) \
; test -s error.flag  && (echo Some command failed: ; cat error.flag)
hello world

And now with the second cat replaced by false:

% rm -f error.flag; echo hello world \
| (cat || echo "First command failed: $?" >> error.flag) \
| (false || echo "Second command failed: $?" >> error.flag) \
| (cat || echo "Third command failed: $?" >> error.flag) \
; test -s error.flag  && (echo Some command failed: ; cat error.flag)
Some command failed:
Second command failed: 1
First command failed: 141

Please note the first cat fails as well, because it's stdout gets closed on it. The order of the failed commands in the log is correct in this example, but don't rely on it.

This method allows for capturing stdout and stderr for the individual commands so you can then dump that as well into a log file if an error occurs, or just delete it if no error (like the output of dd).

Find if current time falls in a time range

A simple little extension function for this:

public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
    var time = now.TimeOfDay;
    // Scenario 1: If the start time and the end time are in the same day.
    if (start <= end)
        return time >= start && time <= end;
    // Scenario 2: The start time and end time is on different days.
    return time >= start || time <= end;
}