Programs & Examples On #Atoi

atoi() is the C runtime library function for converting the ASCII representation of a number to an integer. This SO tag also applies to atol(), atoll(), and atoq() which perform the same conversion to types "long" and "long long".

How to convert a string to integer in C?

You can always roll your own!

#include <stdio.h>
#include <string.h>
#include <math.h>

int my_atoi(const char* snum)
{
    int idx, strIdx = 0, accum = 0, numIsNeg = 0;
    const unsigned int NUMLEN = (int)strlen(snum);

    /* Check if negative number and flag it. */
    if(snum[0] == 0x2d)
        numIsNeg = 1;

    for(idx = NUMLEN - 1; idx >= 0; idx--)
    {
        /* Only process numbers from 0 through 9. */
        if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
            accum += (snum[strIdx] - 0x30) * pow(10, idx);

        strIdx++;
    }

    /* Check flag to see if originally passed -ve number and convert result if so. */
    if(!numIsNeg)
        return accum;
    else
        return accum * -1;
}

int main()
{
    /* Tests... */
    printf("Returned number is: %d\n", my_atoi("34574"));
    printf("Returned number is: %d\n", my_atoi("-23"));

    return 0;
}

This will do what you want without clutter.

What is the difference between sscanf or atoi to convert a string to an integer?

Combining R.. and PickBoy answers for brevity

long strtol (const char *String, char **EndPointer, int Base)

// examples
strtol(s, NULL, 10);
strtol(s, &s, 10);

Impact of Xcode build options "Enable bitcode" Yes/No

Make sure to select "All" to find the enable bitcode build settings:

Build settings

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

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

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

How to initialize var?

var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

So, no you are not allowed to do this.

When you say "some empty value"...if you mean:

var s = string.Empty;
//
var s = "";

Then yes, you may do that, but not null.

Installation of VB6 on Windows 7 / 8 / 10

I've installed and use VB6 for legacy projects many times on Windows 7.

What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.

Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721

Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm

elasticsearch bool query combine must with OR

If you were using Solr's default or Lucene query parser, you can pretty much always put it into a query string query:

POST test/_search
{
  "query": {
    "query_string": {
      "query": "(( name:(+foo +bar) OR info:(+foo +bar)  )) AND state:(1) AND (has_image:(0) OR has_image:(1)^100)"
    }
  }
}

That said, you may want to use a boolean query, like the one you already posted, or even a combination of the two.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I'm running Windows 10 and had this problem after I changed my SSD, I fixed it by disabling the VT support on Bios. I got a different error after I ran the installer. I rebooted and enabled VT support again and voila, working now.

SQLAlchemy IN clause

Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session is your database session here, while User is the ORM class with __tablename__ equal to "users".

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

What are the differences between Pandas and NumPy+SciPy in Python?

pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation.

    template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y)
    {
        double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0);
        double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0);

        double mx =  sum_x / x.size();
        double my =  sum_y / y.size();

        double accum = 0.0;

        for (auto i = 0; i < x.size(); i++)
        {
            accum += (x.at(i) - mx) * (y.at(i) - my);
        }

        return accum / (x.size() - 1);
    }

Directory Chooser in HTML page

Scripting is inevitable.

This isn't provided because of the security risk. <input type='file' /> is closest, but not what you are looking for.

Checkout this example that uses Javascript to achieve what you want.

If the OS is windows, you can use VB scripts to access the core control files to browse for a folder.

Where to put default parameter value in C++?

One more point I haven't found anyone mentioned:

If you have virtual method, each declaration can have its own default value!

It depends on the interface you are calling which value will be used.

Example on ideone

struct iface
{
    virtual void test(int a = 0) { std::cout << a; }
};

struct impl : public iface
{
    virtual void test(int a = 5) override { std::cout << a; }
};

int main()
{
    impl d;
    d.test();
    iface* a = &d;
    a->test();
}

It prints 50

I strongly discourage you to use it like this

Fastest check if row exists in PostgreSQL

as @MikeM pointed out.

select exists(select 1 from contact where id=12)

with index on contact, it can usually reduce time cost to 1 ms.

CREATE INDEX index_contact on contact(id);

Create sequence of repeated values, in sequence?

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

How to get JSON from webpage into Python script

Late answer, but for python>=3.6 you can use:

import dload
j = dload.json(url)

Install dload with:

pip3 install dload

Add/Delete table rows dynamically using JavaScript

Javascript dynamically adding table data.

SCRIPT

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var colCount = table.rows[0].cells.length;    
    var validate_Noof_columns = (colCount - 1); // •No Of Columns to be Validated on Text.
    for(var j = 0; j < colCount; j++) { 
        var text = window.document.getElementById('input'+j).value;

        if (j == validate_Noof_columns) {
            row = table.insertRow(2); // •location of new row.
            for(var i = 0; i < colCount; i++) {       
            var text = window.document.getElementById('input'+i).value;
            var newcell = row.insertCell(i);
                if(i == (colCount - 1)) {  // Replace last column with delete button
    newcell.innerHTML = "<INPUT type='button' value='X' onclick='removeRow(this)'/>"; break;
                } else  {
                    newcell.innerHTML = text;
                    window.document.getElementById('input'+i).value = '';
                }
            }   
        }else if (text != 'undefined' && text.trim() == ''){ 
            alert('input'+j+' is EMPTY');break;
        }  
    }   
}
function removeRow(onclickTAG) {
    // Iterate till we find TR tag. 
    while ( (onclickTAG = onclickTAG.parentElement)  && onclickTAG.tagName != 'TR' );
            onclickTAG.parentElement.removeChild(onclickTAG);      
}

HTMl

<div align='center'>
<TABLE id='dataTable' border='1' >
<TBODY>
    <TR><th align='center'><b>First Name:</b></th>
        <th align='center' colspan='2'><b>Last  Name:</b></th>
        <th></th>
    </TR>    
    <TR><TD ><INPUT id='input0' type="text"/></TD>              
        <TD ><INPUT id='input1' type='text'/></TD>
        <TD>
<INPUT type='button' id='input2' value='+' onclick="addRow('dataTable')" />
        </TD>
    </TR>
</TBODY> 
</TABLE>
</div>

Example : jsfiddle

Installing Python 2.7 on Windows 8

GUI Option:

  1. Open System Properties

    a. Type it in the Start Menu

    b. Use the keyboard shortcut Win+Pause)

    c. From Windows Explorer address bar go to

    %windir%\System32\SystemPropertiesProtection.exe

    d. Write SystemPropertiesProtection in run window and press Enter

  2. Switch to the Advanced tab

  3. Click Environment Variables
  4. Select PATH in the System variables section
  5. Click Edit
  6. Add python's path to the end of the list (the paths are separated by semicolons).

For example:

C:\Windows;C:\Windows\System32;C:\Python27

Command Line Option:

  1. Run Command Prompt as administrator
  2. Check existing paths under PATH variable (the paths are separated by semicolons). If your python folder already listed then no need to add again. Default python folder is C:\Python27

    C:\Windows\system32>path or C:\Windows\system32>echo %PATH%

  3. Append python path using setx command. The /M option sets the variable at SYSTEM scope.

The default behavior is to set it for the USER.

C:\Windows\system32>setx /M PATH "%PATH%;C:\Python27"

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

Is there a performance difference between i++ and ++i in C?

Executive summary: No.

i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away.

We can demonstrate this by looking at the code for this function, both with ++i and i++.

$ cat i++.c
extern void g(int i);
void f()
{
    int i;

    for (i = 0; i < 100; i++)
        g(i);

}

The files are the same, except for ++i and i++:

$ diff i++.c ++i.c
6c6
<     for (i = 0; i < 100; i++)
---
>     for (i = 0; i < 100; ++i)

We'll compile them, and also get the generated assembler:

$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c

And we can see that both the generated object and assembler files are the same.

$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e

$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22

How to change the font on the TextView?

Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

Check below link to check roboto fonts:

How to use Roboto in xml layout

Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

And don't forget to use 'AppTheme' in your AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

Call break in nested if statements

In the most languages, break does only cancel loops like for, while etc.

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

How to get and set the current web page scroll position?

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

How do you deploy Angular apps?

I use with forever:

  1. Build your Angular application with angular-cli to dist folder ng build --prod --output-path ./dist
  2. Create server.js file in your Angular application path:

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    app.use(express.static(__dirname + '/dist'));
    
    app.get('/*', function(req,res) {
        res.sendFile(path.join(__dirname + '/dist/index.html'));
    });
    app.listen(80);
    
  3. Start forever forever start server.js

That's all! your application should be running!

How, in general, does Node.js handle 10,000 concurrent requests?

Single Threaded Event Loop Model Processing Steps:

  • Clients Send request to Web Server.

  • Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.

  • Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.

  • Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.

  • Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.

  • Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.

  • If yes, then pick up one Client Request from Event Queue

    1. Starts process that Client Request
    2. If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
    3. If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
  • Checks Threads availability from Internal Thread Pool
  • Picks up one Thread and assign this Client Request to that thread.
  • That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop

    very nicely explained by @Rambabu Posa for more explanation go throw this Link

How to fluently build JSON in Java?

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();

Get next / previous element using JavaScript?

This will be easy... its an pure javascript code

    <script>
           alert(document.getElementById("someElement").previousElementSibling.innerHTML);
    </script>

JavaScript: location.href to open in new window/tab?

You can also open a new tab calling to an action method with parameter like this:

   var reportDate = $("#inputDateId").val();
   var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
   window.open(window.location.href = url.replace('findme', reportDate), '_blank');

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :

_x000D_
_x000D_
Chart.Type.extend({_x000D_
      //Passing in a name registers this chart in the Chart namespace_x000D_
      name: "Doughnut",_x000D_
      //Providing a defaults will also register the deafults in the chart namespace_x000D_
      defaults: defaultConfig,_x000D_
      .......
_x000D_
_x000D_
_x000D_

My legendTemplate is changed from

_x000D_
_x000D_
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<datasets.length; i++){%>_x000D_
    <li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
      <%if(datasets[i].label){%>_x000D_
        <%=datasets[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

To

_x000D_
_x000D_
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<segments.length; i++){%>_x000D_
    <li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
      <%if(segments[i].label){%>_x000D_
        <%=s egments[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

How to recompile with -fPIC

Have a look at this page.

you can try globally adding the flag using: export CXXFLAGS="$CXXFLAGS -fPIC"

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

Append column to pandas dataframe

Just a matter of the right google search:

data = dat_1.append(dat_2)
data = data.groupby(data.index).sum()

Remove Project from Android Studio

Or if you don't want to build it just remove it from settings.gradle file

How to pass an object from one activity to another on Android

Start another activity from this activity and pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Retrive data on another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

This is ok for simple kind of data type. But if u want to pass complex data in between activity. U need to serialize it first.

Here we have Employee Model

class Employee{
    private String empId;
    private int age;
    print Double salary;

    getters...
    setters...
}

You can use Gson lib provided by google to serialize the complex data like this

String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            }.getType();
            Employee selectedEmp = gson.fromJson(empStr, type);

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

How to check if a user is logged in (how to properly use user.is_authenticated)?

For Django 2.0+ versions use:

    if request.auth:
       # Only for authenticated users.

For more info visit https://www.django-rest-framework.org/api-guide/requests/#auth

request.user.is_authenticated() has been removed in Django 2.0+ versions.

img src SVG changing the styles with CSS

You will first have to inject the SVG into the HTML DOM.

There is an open source library called SVGInject that does this for you. It uses the onload attribute to trigger the injection.

Here is a minimal example using SVGInject:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

It solves several issues with SVG injection:

  1. SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief "unstyled content flash".

  2. The <img> elements inject themselves automatically. If you add SVGs dynamically, you don't have to worry about calling the injection function again.

  3. A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.

SVGInject is plain Javascript and works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

Using strtok with a std::string

Duplicate the string, tokenize it, then free it.

char *dup = strdup(str.c_str());
token = strtok(dup, " ");
free(dup);

Firebase cloud messaging notification not received by device

private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setColor(getResources().getColor(R.color.colorPrimaryDark))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noBuilder.build());

How do I use Notepad++ (or other) with msysgit?

UPDATE 2015

If you unpack/install Notepad++ into c:\utils\npp\ and rename notepad++.exe to npp.exe for simplicity, then all you have to do is

git config --global core.editor c:/utils/npp/npp.exe

No wrapper scripts or other trickery. No need to have Notepad++ in PATH.

Viewing localhost website from mobile device

Know your host ip address on your lan Open cmd and type ipconfig and the if xampp the default listen port would be 80 Then for instance if 10.0.0.5 is your host ip address Type 10.0.0.5:80 from your mobile's web browser Make sure that both are connected to the same LAN However the default port that webaddress tries is 80.

Alternate output format for psql

One interesting thing is we can view the tables horizontally, without folding. we can use PAGER environment variable. psql makes use of it. you can set

export PAGER='/usr/bin/less -S'

or just less -S if its already availble in command line, if not with the proper location. -S to view unfolded lines. you can pass in any custom viewer or other options with it.

I've written more in Psql Horizontal Display

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I think this problem occurs when you try to access your web driver object after

1) a window has closed and you haven't yet switched to the parent

2) you switched to a window that wasn't quite ready and has been updated since you switched

waiting for the windowhandles.count to be what you're expecting doesn't take into account the page content nor does document.ready. I'm still searching for a solution to this problem

Yes or No confirm box using jQuery

All the example I've seen aren't reusable for different "yes/no" type questions. I was looking for something that would allow me to specify a callback so I could call for any situation.

The following is working well for me:

$.extend({ confirm: function (title, message, yesText, yesCallback) {
    $("<div></div>").dialog( {
        buttons: [{
            text: yesText,
            click: function() {
                yesCallback();
                $( this ).remove();
            }
        },
        {
            text: "Cancel",
            click: function() {
                $( this ).remove();
            }
        }
        ],
        close: function (event, ui) { $(this).remove(); },
        resizable: false,
        title: title,
        modal: true
    }).text(message).parent().addClass("alert");
}
});

I then call it like this:

var deleteOk = function() {
    uploadFile.del(fileid, function() {alert("Deleted")})
};

$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);

php - push array into array - key issue

first convert your array too JSON

while($query->fetch()){
   $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}

then vonvert back it to array

foreach($col as &$array){
   $array = json_decode($array,true);
}

good luck

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

Oracle SQL Developer: Unable to find a JVM

“C:\Users\admin\Downloads\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf” is misleading, it’s not the file which sets the Java Home variable. The actually file used is”%AppData%\sqldeveloper{PRODUCT_VERSION}\product.conf” [in my case it is "%AppData%\sqldeveloper\1.0.0.0.0\product.conf"]

Finding sum of elements in Swift array

this is my approach about this. however I believe that the best solution is the answer from the user username tbd

var i = 0 
var sum = 0
let example = 0
for elements in multiples{
    i = i + 1
    sum = multiples[ (i- 1)]
    example = sum + example
}

Select records from NOW() -1 Day

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)

Uncaught SyntaxError: Invalid or unexpected token

You should pass @item.email in quotes then it will be treated as string argument

<td><a href ="#"  onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a>  </td>

Otherwise, it is treated as variable thus error is generated.

React - changing an uncontrolled input

Simple solution to resolve this problem is to set an empty value by default :

<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />

TypeScript enum to object array

You can do that in this way:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

export class GoalProgressMeasurement {
    constructor(public goalProgressMeasurement: GoalProgressMeasurements, public name: string) {
    }
}

export var goalProgressMeasurements: { [key: number]: GoalProgressMeasurement } = {
    1: new GoalProgressMeasurement(GoalProgressMeasurements.Percentage, "Percentage"),
    2: new GoalProgressMeasurement(GoalProgressMeasurements.Numeric_Target, "Numeric Target"),
    3: new GoalProgressMeasurement(GoalProgressMeasurements.Completed_Tasks, "Completed Tasks"),
    4: new GoalProgressMeasurement(GoalProgressMeasurements.Average_Milestone_Progress, "Average Milestone Progress"),
    5: new GoalProgressMeasurement(GoalProgressMeasurements.Not_Measured, "Not Measured"),
}

And you can use it like this:

var gpm: GoalProgressMeasurement = goalProgressMeasurements[GoalProgressMeasurements.Percentage];
var gpmName: string = gpm.name;

var myProgressId: number = 1; // the value can come out of drop down selected value or from back-end , so you can imagine the way of using
var gpm2: GoalProgressMeasurement = goalProgressMeasurements[myProgressId];
var gpmName: string = gpm.name;

You can extend the GoalProgressMeasurement with additional properties of the object as you need. I'm using this approach for every enumeration that should be an object containing more then a value.

How to count days between two dates in PHP?

You can use date_diff to calculate the difference between two dates:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff =  date_diff($date1 , $date2);
echo  $diff->format("%R%a days");

How to show loading spinner in jQuery?

JavaScript

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS

#loading { background: url(/image/loading.gif) no-repeat center; }

How to remove backslash on json_encode() function?

Yes it's possible. Look!

$str = str_replace('\\', '', $str);

But why would you want to?

Ternary operation in CoffeeScript

Multiline version (e.g. if you need to add comment after each line):

a = if b # a depends on b
then 5   # b is true 
else 10  # b is false

Escaping Double Quotes in Batch Script

Google eventually came up with the answer. The syntax for string replacement in batch is this:

set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%

Which produces "replicate me". My script now looks like this:

@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"

Which replaces all instances of " with \", properly escaped for bash.

Retrieve last 100 lines logs

I know this is very old, but, for whoever it may helps.

less +F my_log_file.log

that's just basic, with less you can do lot more powerful things. once you start seeing logs you can do search, go to line number, search for pattern, much more plus it is faster for large files.

its like vim for logs[totally my opinion]

original less's documentation : https://linux.die.net/man/1/less

less cheatsheet : https://gist.github.com/glnds/8862214

How can I require at least one checkbox be checked before a form can be submitted?

Here's an example using jquery and your html.

<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
    $('#checkBtn').click(function() {
      checked = $("input[type=checkbox]:checked").length;

      if(!checked) {
        alert("You must check at least one checkbox.");
        return false;
      }

    });
});

</script>

<p>Box Set 1</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<p>Box Set 2</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 5" required><label>Box 5</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 6" required><label>Box 6</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 7" required><label>Box 7</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 8" required><label>Box 8</label></li>
</ul>
<p>Box Set 3</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 9" required><label>Box 9</label></li>
</ul>
<p>Box Set 4</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 10" required><label>Box 10</label></li>
</ul>

<input type="button" value="Test Required" id="checkBtn">

</body>
</html>

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

See here for an example from the OpenJPA docs. CascadeType.ALL means it will do all actions.

Quote:

CascadeType.PERSIST: When persisting an entity, also persist the entities held in its fields. We suggest a liberal application of this cascade rule, because if the EntityManager finds a field that references a new entity during the flush, and the field does not use CascadeType.PERSIST, it is an error.

CascadeType.REMOVE: When deleting an entity, it also deletes the entities held in this field.

CascadeType.REFRESH: When refreshing an entity, also refresh the entities held in this field.

CascadeType.MERGE: When merging entity state, also merge the entities held in this field.

Sebastian

Google Chromecast sender error if Chromecast extension is not installed or using incognito

How about filtering these errors ?

With the regex filter bellow, we can dismiss cast_sender.js errors :

^((?!cast_sender).)*$

Do not forget to check Regex box.

enter image description here

Another quick solution is to "Hide network messages".

enter image description here

Passing a method parameter using Task.Factory.StartNew

Construct the first parameter as an instance of Action, e.g.

var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
    () => CheckFiles(inputID, col),
    cancelCheckFile.Token,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

What do the different readystates in XMLHttpRequest mean, and how can I use them?

The full list of readyState values is:

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

(from https://www.w3schools.com/js/js_ajax_http_response.asp)

In practice you almost never use any of them except for 4.

Some XMLHttpRequest implementations may let you see partially received responses in responseText when readyState==3, but this isn't universally supported and shouldn't be relied upon.

Creating a new user and password with Ansible

This is how it worked for me

- hosts: main
  vars:
  # created with:
  #  python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('<password>')"
  # above command requires the PassLib library: sudo pip install passlib
  - password: '$6$rounds=100000$H/83rErWaObIruDw$DEX.DgAuZuuF.wOyCjGHnVqIetVt3qRDnTUvLJHBFKdYr29uVYbfXJeHg.IacaEQ08WaHo9xCsJQgfgZjqGZI0'

tasks:

- user: name=spree password={{password}} groups=sudo,www-data shell=/bin/bash append=yes
  sudo: yes

symfony2 : failed to write cache directory

Maybe you forgot to change the permissions of app/cache app/log

I'm using Ubuntu so

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs

Hope it helps..

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

run from CMD & %path%=set to mysql/bin

mysql_upgrade -u user -ppassword

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:

someString.matches("[A-F]");

For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

get and set in TypeScript

Based on example you show, you want to pass a data object and get a property of that object by get(). for this you need to use generic type, since data object is generic, can be any object.

export class Attributes<T> {
    constructor(private data: T) {}
    get = <K extends keyof T>(key: K): T[K] => {
      return this.data[key];
    };
    set = (update: T): void => {
      //   this is like spread operator. it will take this.data obj and will overwrite with the update obj
      // ins tsconfig.json change target to Es6 to be able to use Object.assign()
      Object.assign(this.data, update);
    };
    getAll(): T {
      return this.data;
    }
  }

< T > refers to generic type. let's initialize an instance

 const myAttributes=new Attributes({name:"something",age:32})

 myAttributes.get("name")="something"

Notice this syntax

<K extends keyof T>

in order to be able to use this we should be aware of 2 things:

1- in typestring strings can be a type.

2- all object properties in javascript essentially are strings.

when we use get(), type of argument that it is receiving is a property of object that passed to constructor and since object properties are strings and strings are allowed to be a type in typescript, we could use this <K extends keyof T>

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

This exception because of when you call session.getEntityById(), the session will be closed. So you need to re-attach the entity to the session. Or Easy solution is just configure default-lazy="false" to your entity.hbm.xml or if you are using annotations just add @Proxy(lazy=false) to your entity class.

Brew install docker does not include docker engine?

Please try running

brew install docker

This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.

If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:

brew install --cask docker 
open /Applications/Docker.app

How to autoplay HTML5 mp4 video on Android?

don't use "mute" alone, use [muted]="true" for example following code:

<video id="videoPlayer" [muted]="true" autoplay playsinline loop style="width:100%; height: 100%;">
<source type="video/mp4" src="assets/Video/Home.mp4">
<source type="video/webm" src="assets/Video/Home.webm">
</video>

I test in more Android and ios

Rest-assured. Is it possible to extract value from request json?

You can also do like this if you're only interested in extracting the "user_id":

String userId = 
given().
        contentType("application/json").
        body(requestBody).
when().
        post("/admin").
then().
        statusCode(200).
extract().
        path("user_id");

In its simplest form it looks like this:

String userId = get("/person").path("person.userId");

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How many files can I put in a directory?

It really depends on the filesystem used, and also some flags.

For example, ext3 can have many thousands of files; but after a couple of thousands, it used to be very slow. Mostly when listing a directory, but also when opening a single file. A few years ago, it gained the 'htree' option, that dramatically shortened the time needed to get an inode given a filename.

Personally, I use subdirectories to keep most levels under a thousand or so items. In your case, I'd create 256 directories, with the two last hex digits of the ID. Use the last and not the first digits, so you get the load balanced.

Moment.js with Vuejs

With your code, the vue.js is trying to access the moment() method from its scope.

Hence you should use a method like this:

methods: {
  moment: function () {
    return moment();
  }
},

If you want to pass a date to the moment.js, I suggest to use filters:

filters: {
  moment: function (date) {
    return moment(date).format('MMMM Do YYYY, h:mm:ss a');
  }
}

<span>{{ date | moment }}</span>

[demo]

What is a monad?

The two things that helped me best when learning about there were:

Chapter 8, "Functional Parsers," from Graham Hutton's book Programming in Haskell. This doesn't mention monads at all, actually, but if you can work through chapter and really understand everything in it, particularly how a sequence of bind operations is evaluated, you'll understand the internals of monads. Expect this to take several tries.

The tutorial All About Monads. This gives several good examples of their use, and I have to say that the analogy in Appendex I worked for me.

If else embedding inside html

 <?php if (date("H") < "12" && date("H")>"6") { ?>
   src="<?php bloginfo('template_url'); ?>/images/img/morning.gif" 
 <?php } elseif (date("H") > "12" && date("H")<"17") { ?>
 src="<?php bloginfo('template_url'); ?>/images/img/noon.gif" 
  <?php } elseif (date("H") > "17" && date("H")<"21") { ?>
   src="<?php bloginfo('template_url'); ?>/images/img/evening.gif" 
  <?php } elseif (date("H") > "21" && date("H")<"24") { ?>
  src="<?php bloginfo('template_url'); ?>/images/img/night.gif" 
  <?php }else { ?>
  src="<?php bloginfo('template_url'); ?>/images/img/mid_night.gif" 
  <?php } ?>

(grep) Regex to match non-ASCII characters?

This will match a single non-ASCII character:

[^\x00-\x7F]

This is a valid PCRE (Perl-Compatible Regular Expression).

You can also use the POSIX shorthands:

  • [[:ascii:]] - matches a single ASCII char
  • [^[:ascii:]] - matches a single non-ASCII char

[^[:print:]] will probably suffice for you.**

method in class cannot be applied to given types

call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

How do I pass a string into subprocess.Popen (using the stdin argument)?

There's a beautiful solution if you're using Python 3.4 or better. Use the input argument instead of the stdin argument, which accepts a bytes argument:

output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

This works for check_output and run, but not call or check_call for some reason.

heroku - how to see all the logs

I prefer to do it this way

heroku logs --tail | tee -a herokuLogs

You can leave the script running in background and you can simply filter the logs from the text file the way you want anytime.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Convert byte to string in Java

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);

How to tag an older commit in Git?

The answer by @Phrogz is great, but doesn't work on Windows. Here's how to tag an old commit with the commit's original date using Powershell:

git checkout 9fceb02
$env:GIT_COMMITTER_DATE = git show --format=%aD | Select -First 1
git tag v1.2
git checkout master

Python SQL query string formatting

To avoid formatting entirely, I think a great solution is to use procedures.

Calling a procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call will just return the last query that was called.

MYSQL

DROP PROCEDURE IF EXISTS example;
 DELIMITER //
 CREATE PROCEDURE example()
   BEGIN
   SELECT 2+222+2222+222+222+2222+2222 AS this_is_a_really_long_string_test;
   END //
 DELIMITER;

#calling the procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call just returns the last query result
 call example;

Python

sql =('call example;')

Fixed position but relative to container

Another weird solution to achieve a relative fixed position is converting your container into an iframe, that way your fixed element can be fixed to it's container's viewport and not the entire page.

How do I read from parameters.yml in a controller in symfony2?

You can use:

public function indexAction()
{
   dump( $this->getParameter('api_user'));
}

For more information I recommend you read the doc :

http://symfony.com/doc/2.8/service_container/parameters.html

Align the form to the center in Bootstrap 4

All above answers perfectly gives the solution to center the form using Bootstrap 4. However, if someone wants to use out of the box Bootstrap 4 css classes without help of any additional styles and also not wanting to use flex, we can do like this.

A sample form

enter image description here

HTML

<div class="container-fluid h-100 bg-light text-dark">
  <div class="row justify-content-center align-items-center">
    <h1>Form</h1>    
  </div>
  <hr/>
  <div class="row justify-content-center align-items-center h-100">
    <div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
      <form action="">
        <div class="form-group">
          <select class="form-control">
                    <option>Option 1</option>
                    <option>Option 2</option>
                  </select>
        </div>
        <div class="form-group">
          <input type="text" class="form-control" />
        </div>
        <div class="form-group text-center">
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 1
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio">Option 2
  </label>
          </div>
          <div class="form-check-inline">
            <label class="form-check-label">
    <input type="radio" class="form-check-input" name="optradio" disabled>Option 3
  </label>
          </div>
        </div>
        <div class="form-group">
          <div class="container">
            <div class="row">
              <div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
              <div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
            </div>
          </div>
        </div>

      </form>
    </div>
  </div>
</div>

Link to CodePen

https://codepen.io/anjanasilva/pen/WgLaGZ

I hope this helps someone. Thank you.

Laravel where on relationship object

    return Deal::with(["redeem" => function($q){
        $q->where('user_id', '=', 1);
    }])->get();

this worked for me

How do I sort a table in Excel if it has cell references in it?

For me this worked like below -

I had sheet name references in formula for the same sheet. When I removed current sheet name from the formula and sorted it worked correctly.

What is bootstrapping?

See on the Wikipedia article on bootstrapping.

There is a section and links explaining what it means in Computing. It has four different uses in the field.

Here are some quotes, but for a more in depth explanation, and alternative meanings, consult the links above.

"...is a technique by which a simple computer program activates a more complicated system of programs."

"A different use of the term bootstrapping is to use a compiler to compile itself, by first writing a small part of a compiler of a new programming language in an existing language to compile more programs of the new compiler written in the new language."

hide/show a image in jquery

If you're trying to hide upload img and show bandwidth img on bandwidth click and viceversa this would work

<script>

    function show_img(id)
    {
        if(id=='bandwidth')
        {
           $("#upload").hide();
           $("#bandwith").show();
        }
        else if(id=='upload')
        {
            $("#upload").show();
            $("#bandwith").hide();
        }
    return false;
     } 
    </script>
    <a href="#" onclick="javascript:show_img('bandwidth');">Bandwidth</a>
    <a href="#" onclick="javascript:show_img('upload');">Upload</a>
    <p align="center"> 
      <img src="/media/img/close.png" style="visibility: hidden;" id="bandwidth"/>
      <img src="/media/img/close.png" style="visibility: hidden;" id="upload"/>
    </p>

Difference between dates in JavaScript

You can also use it

export function diffDateAndToString(small: Date, big: Date) {


    // To calculate the time difference of two dates 
    const Difference_In_Time = big.getTime() - small.getTime()

    // To calculate the no. of days between two dates 
    const Days = Difference_In_Time / (1000 * 3600 * 24)
    const Mins = Difference_In_Time / (60 * 1000)
    const Hours = Mins / 60

    const diffDate = new Date(Difference_In_Time)

    console.log({ date: small, now: big, diffDate, Difference_In_Days: Days, Difference_In_Mins: Mins, Difference_In_Hours: Hours })

    var result = ''

    if (Mins < 60) {
        result = Mins + 'm'
    } else if (Hours < 24) result = diffDate.getMinutes() + 'h'
    else result = Days + 'd'
    return { result, Days, Mins, Hours }
}

results in { result: '30d', Days: 30, Mins: 43200, Hours: 720 }

HTTP authentication logout via PHP

Logout from HTTP Basic Auth in two steps

Let’s say I have a HTTP Basic Auth realm named “Password protected”, and Bob is logged in. To log out I make 2 AJAX requests:

  1. Access script /logout_step1. It adds a random temporary user to .htusers and responds with its login and password.
  2. Access script /logout_step2 authenticated with the temporary user’s login and password. The script deletes the temporary user and adds this header on the response: WWW-Authenticate: Basic realm="Password protected"

At this point browser forgot Bob’s credentials.

Why does SSL handshake give 'Could not generate DH keypair' exception?

I used to get a similar error accessing svn.apache.org with java SVN clients using an IBM JDK. Currently, svn.apache.org users the clients cipher preferences.

After running just once with a packet capture / javax.net.debug=ALL I was able to blacklist just a single DHE cipher and things work for me (ECDHE is negotiated instead).

.../java/jre/lib/security/java.security:
    jdk.tls.disabledAlgorithms=SSL_DHE_RSA_WITH_AES_256_CBC_SHA

A nice quick fix when it is not easy to change the client.

event Action<> vs event EventHandler<>

The main difference will be that if you use Action<> your event will not follow the design pattern of virtually any other event in the system, which I would consider a drawback.

One upside with the dominating design pattern (apart from the power of sameness) is that you can extend the EventArgs object with new properties without altering the signature of the event. This would still be possible if you used Action<SomeClassWithProperties>, but I don't really see the point with not using the regular approach in that case.

WebView and HTML5 <video>

Actually, it seems sufficient to merely attach a stock WebChromeClient to the client view, ala

mWebView.setWebChromeClient(new WebChromeClient());

and you need to have hardware acceleration turned on!

At least, if you don't need to play a full-screen video, there's no need to pull the VideoView out of the WebView and push it into the Activity's view. It will play in the video element's allotted rect.

Any ideas how to intercept the expand video button?

Init method in Spring Controller (annotation version)

You can use

@PostConstruct
public void init() {
   // ...
}

Where is the kibana error log? Is there a kibana error log?

It seems that you need to pass a flag "-l, --log-file"

https://github.com/elastic/kibana/issues/3407

Usage: kibana [options]

Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

Options:

    -h, --help                 output usage information
    -V, --version              output the version number
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file
    -p, --port <port>          The port to bind to
    -q, --quiet                Turns off logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugins <path>           Path to scan for plugins

If you use the init script to run as a service, maybe you will need to customize it.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

solve this issue for angular

"styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

cannot connect to pc-name\SQLEXPRESS

go to services and start the ones related to SQL

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If you want happen to be using LESS it can be achieved like so:

li {
    .glyphicon-ok();

    &:before {            
        .glyphicon();            
        margin-left:-25px;
       float:left;
    }
}

Regular expression to match balanced parentheses

(?<=\().*(?=\))

If you want to select text between two matching parentheses, you are out of luck with regular expressions. This is impossible(*).

This regex just returns the text between the first opening and the last closing parentheses in your string.


(*) Unless your regex engine has features like balancing groups or recursion. The number of engines that support such features is slowly growing, but they are still not a commonly available.

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".

The problem relates to the "shrinkwrap" or package-lock.json which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json.

Adding these options to the npm install command should allow packages to install again.

   --no-optional argument will prevent optional dependencies from being installed.

   --no-shrinkwrap argument, which will ignore an available package lock or
                   shrinkwrap file and use the package.json instead.

   --no-package-lock argument will prevent npm from creating a package-lock.json file.

The complete command looks like this:

    npm install --no-optional --no-shrinkwrap --no-package-lock

nJoy!

AttributeError: 'DataFrame' object has no attribute

To get all the counts for all the columns in a dataframe, it's just df.count()

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

Quotation marks inside a string

You can do this using Escape Sequence.

\"

So you will have to write something like this :

String name = "\"john\"";

You can learn about Escape Sequences from here.

How to check if running as root in a bash script

There is a simple check for a user being root.

The [[ stuff ]] syntax is the standard way of running a check in bash.

error() {
  printf '\E[31m'; echo "$@"; printf '\E[0m'
}

if [[ $EUID -eq 0 ]]; then
    error "Do not run this as the root user"
    exit 1
fi

This also assumes that you want to exit with a 1 if you fail. The error function is some flair that sets output text to red (not needed, but pretty classy if you ask me).

Installing ADB on macOS

  1. You must download Android SDK from this link.

  2. You can really put it anywhere, but the best place at least for me was right in the YOUR USERNAME folder root.

  3. Then you need to set the path by copying the below text, but edit your username into the path, copy the text into Terminal by hitting command+spacebar type terminal. export PATH = ${PATH}:/Users/**YOURUSERNAME**/android-sdk/platform-tools/

  4. Verify ADB works by hitting command+spacebar and type terminal, and type ADB.

There you go. You have ADB setup on MAC OS X. It works on latest MAC OS X 10.10.3.

Android: how to make keyboard enter button say "Search" and handle its click?

In xml file, put imeOptions="actionSearch" and inputType="text", maxLines="1":

<EditText
    android:id="@+id/search_box"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search"
    android:imeOptions="actionSearch"
    android:inputType="text"
    android:maxLines="1" />

Python division

Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.

Try casting one of the operands of "/" to be a float:

float(20-10) / (100-10)

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

How do you format a Date/Time in TypeScript?

Update (2020)

As pointed by @jonhF in the comments, MomentJs recommends to not use MomentJs anymore. Check https://momentjs.com/docs/

Instead, I'm keeping this list with my personal TOP 3 js date libraries for future reference.

Old comment

I suggest you to use MomentJS

With moment you can have lot of outputs, and this one 09/11/2015 16:16 is one of then.

How to expand a list to function arguments in Python

It exists, but it's hard to search for. I think most people call it the "splat" operator.

It's in the documentation as "Unpacking argument lists".

You'd use it like this: foo(*values). There's also one for dictionaries:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

What's the syntax for mod in java

Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainder operator %. For your exact example:

if ((a % 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

This can be simplified to a one-liner:

isEven = (a % 2) == 0;

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

Is it possible to use JavaScript to change the meta-tags of the page?

simple add and div atribute to each meta tag example

<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />

now like normal div change for ex. n click

<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>

function change tags with jQuery

function changeTags(){
   $("#mtlink").attr("content","http://albup.com");
   $("#mtdesc").attr("content","music all the time");
   $("#mtkwrds").attr("content","mp3, download music, ");

}

How do I overload the square-bracket operator in C#?

For CLI C++ (compiled with /clr) see this MSDN link.

In short, a property can be given the name "default":

ref class Class
{
 public:
  property System::String^ default[int i]
  {
    System::String^ get(int i) { return "hello world"; }
  }
};

The import org.apache.commons cannot be resolved in eclipse juno

expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.

if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish

simple Jquery hover enlarge

Well I'm not exactly sure why your code is not working because I usually follow a different approach when trying to accomplish something similar.

But your code is erroring out.. There seems to be an issue with the way you are using scale I got the jQuery to actually execute by changing your code to the following.

$(document).ready(function(){
    $('img').hover(function() {
        $(this).css("cursor", "pointer");
        $(this).toggle({
          effect: "scale",
          percent: "90%"
        },200);
    }, function() {
         $(this).toggle({
           effect: "scale",
           percent: "80%"
         },200);

    });
});  

But I have always done it by using CSS to setup my scaling and transition..

Here is an example, hopefully it helps.

$(document).ready(function(){
    $('#content').hover(function() {
        $("#content").addClass('transition');

    }, function() {
        $("#content").removeClass('transition');
    });
});

http://jsfiddle.net/y4yAP/

How to generate all permutations of a list?

def pzip(c, seq):
    result = []
    for item in seq:
        for i in range(len(item)+1):
            result.append(item[i:]+c+item[:i])
    return result


def perm(line):
    seq = [c for c in line]
    if len(seq) <=1 :
        return seq
    else:
        return pzip(seq[0], perm(seq[1:]))

Array.push() and unique items

so not sure if this answers your question but the indexOf the items you are adding keep returning -1. Not to familiar with js but it appears the items do that because they are not in the array yet. I made a jsfiddle of a little modified code for you.

this.items = [];

add(1);
add(2);
add(3);

document.write("added items to array");
document.write("<br>");
function  add(item) {
        //document.write(this.items.indexOf(item));
    if(this.items.indexOf(item) <= -1) {

      this.items.push(item);
      //document.write("Hello World!");
    }
}

document.write("array is : " + this.items);

https://jsfiddle.net/jmpalmisano/Lnommkbw/2/

Remote Connections Mysql Ubuntu

You are using ubuntu 12 (quite old one)

First, Open the /etc/mysql/mysql.conf.d/mysqld.cnf file (/etc/mysql/my.cnf in Ubuntu 14.04 and earlier versions

Under the [mysqld] Locate the Line, bind-address = 127.0.0.1 And change it to, bind-address = 0.0.0.0 or comment it

Then, Restart the Ubuntu MysQL Server systemctl restart mysql.service

Now Ubuntu Server will allow remote access to the MySQL Server, But still you need to configure MySQL users to allow access from any host.

User must be 'username'@'%' with all the required grants

To make sure that, MySQL server listens on all interfaces, run the netstat command as follows.

netstat -tulnp | grep mysql

Hope this works !

How to detect DIV's dimension changed?

_x000D_
_x000D_
var div = document.getElementById('div');_x000D_
div.addEventListener('resize', (event) => console.log(event.detail));_x000D_
_x000D_
function checkResize (mutations) {_x000D_
    var el = mutations[0].target;_x000D_
    var w = el.clientWidth;_x000D_
    var h = el.clientHeight;_x000D_
    _x000D_
    var isChange = mutations_x000D_
      .map((m) => m.oldValue + '')_x000D_
      .some((prev) => prev.indexOf('width: ' + w + 'px') == -1 || prev.indexOf('height: ' + h + 'px') == -1);_x000D_
_x000D_
    if (!isChange)_x000D_
      return;_x000D_
_x000D_
    var event = new CustomEvent('resize', {detail: {width: w, height: h}});_x000D_
    el.dispatchEvent(event);_x000D_
}_x000D_
_x000D_
var observer = new MutationObserver(checkResize); _x000D_
observer.observe(div, {attributes: true, attributeOldValue: true, attributeFilter: ['style']});
_x000D_
#div {width: 100px; border: 1px solid #bbb; resize: both; overflow: hidden;}
_x000D_
<div id = "div">DIV</div>
_x000D_
_x000D_
_x000D_

How to comment in Vim's config files: ".vimrc"?

You can add comments in Vim's configuration file by either:

" brief descriptiion of command

or:

"" commended command

Taken from here

Get the value of checked checkbox?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    _x000D_
    if (ckbox.is(':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
    });_x000D_
       _x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
_x000D_
_x000D_

Syntax for creating a two-dimensional array in Java

Try this way:

int a[][] = {{1,2}, {3,4}};

int b[] = {1, 2, 3, 4};

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

Right-click the project, select Properties then under 'Configuration properties | Linker | Input | Ignore specific Library and write msvcrtd.lib

How to select a CRAN mirror in R

I had, on macOS, the exact thing that you say: A 'please select' prompt and then nothing more.

After I opened (and updated; don't know if that was relevant) X-Quartz, and then restarted R and tried again, I got an X-window list of mirrors to choose from after a few seconds. It was faster the third time onwards.

Get selected element's outer HTML

To make a FULL jQuery plugin as .outerHTML, add the following script to any js file and include after jQuery in your header:

update New version has better control as well as a more jQuery Selector friendly service! :)

;(function($) {
    $.extend({
        outerHTML: function() {
            var $ele = arguments[0],
                args = Array.prototype.slice.call(arguments, 1)
            if ($ele && !($ele instanceof jQuery) && (typeof $ele == 'string' || $ele instanceof HTMLCollection || $ele instanceof Array)) $ele = $($ele);
            if ($ele.length) {
                if ($ele.length == 1) return $ele[0].outerHTML;
                else return $.map($("div"), function(ele,i) { return ele.outerHTML; });
            }
            throw new Error("Invalid Selector");
        }
    })
    $.fn.extend({
        outerHTML: function() {
            var args = [this];
            if (arguments.length) for (x in arguments) args.push(arguments[x]);
            return $.outerHTML.apply($, args);
        }
    });
})(jQuery);

This will allow you to not only get the outerHTML of one element, but even get an Array return of multiple elements at once! and can be used in both jQuery standard styles as such:

$.outerHTML($("#eleID")); // will return outerHTML of that element and is 
// same as
$("#eleID").outerHTML();
// or
$.outerHTML("#eleID");
// or
$.outerHTML(document.getElementById("eleID"));

For multiple elements

$("#firstEle, .someElesByClassname, tag").outerHTML();

Snippet Examples:

_x000D_
_x000D_
console.log('$.outerHTML($("#eleID"))'+"\t", $.outerHTML($("#eleID"))); _x000D_
console.log('$("#eleID").outerHTML()'+"\t\t", $("#eleID").outerHTML());_x000D_
console.log('$("#firstEle, .someElesByClassname, tag").outerHTML()'+"\t", $("#firstEle, .someElesByClassname, tag").outerHTML());_x000D_
_x000D_
var checkThisOut = $("div").outerHTML();_x000D_
console.log('var checkThisOut = $("div").outerHTML();'+"\t\t", checkThisOut);_x000D_
$.each(checkThisOut, function(i, str){ $("div").eq(i).text("My outerHTML Was: " + str); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://rawgit.com/JDMcKinstry/ce699e82c7e07d02bae82e642fb4275f/raw/deabd0663adf0d12f389ddc03786468af4033ad2/jQuery.outerHTML.js"></script>_x000D_
<div id="eleID">This will</div>_x000D_
<div id="firstEle">be Replaced</div>_x000D_
<div class="someElesByClassname">At RunTime</div>_x000D_
<h3><tag>Open Console to see results</tag></h3>
_x000D_
_x000D_
_x000D_

how do I insert a column at a specific column index in pandas?

df.insert(loc, column_name, value)

This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.

You can pass an optional parameter allow_duplicates with True value to create a new column with already existing column name.

Here is an example:



    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
    >>> df
       b  c
    0  1  3
    1  2  4
    >>> df.insert(0, 'a', -1)
    >>> df
       a  b  c
    0 -1  1  3
    1 -1  2  4
    >>> df.insert(0, 'a', -2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
        self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
      File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
        raise ValueError(f"cannot insert {item}, already exists")
    ValueError: cannot insert a, already exists
    >>> df.insert(0, 'a', -2,  allow_duplicates = True)
    >>> df
       a  a  b  c
    0 -2 -1  1  3
    1 -2 -1  2  4

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00

Echo equivalent in PowerShell for script testing

Powershell has an alias mapping echo to Write-Output, so:

echo "filesizecounter : $filesizecounter"

Running code after Spring Boot starts

The "Spring Boot" way is to use a CommandLineRunner. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean which gets a callback after everything has initialized. And there is SmartLifecycle (from Spring 3).

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

Converting Numpy Array to OpenCV Array

Your code can be fixed as follows:

import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)

Short explanation:

  1. np.uint32 data type is not supported by OpenCV (it supports uint8, int8, uint16, int16, int32, float32, float64)
  2. cv.CvtColor can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray do this conversion.
  3. Both arguments of cv.CvtColor must have the same depth. So I've changed source type to 32bit float to match the ddestination.

Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:

import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

Angular 2.0 router not working on reloading the browser

I think the error you are seeing is because your are requesting http://localhost/route which doesn't exist. You need to make sure that your server will map all requests to your main index.html page.

As Angular 2 uses html5 routing by default rather than using hashes at the end of the url, refreshing the page looks like a request for a different resource.

warning: incompatible implicit declaration of built-in function ‘xyz’

In the case of some programs, these errors are normal and should not be fixed.

I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.

If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Most of the times, the issue is with the paths you have mentioned for 'java home' and 'javac' tags in settings.xml which is present in your .m2 repository and the issue is not with your path variable or Java_Home variable. If you check and correct the same, you should be able to execute your commands successfully. - Jaihind

How to check if click event is already bound - JQuery

JQuery has solution:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
}); 

equivalent:

$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});

Batch file script to zip files

for /d %%a in (*) do (ECHO zip -r -p "%%~na.zip" ".\%%a\*")

should work from within a batch.

Note that I've included an ECHO to simply SHOW the command that is proposed. You'd need to remove the ECHO keywor to EXECUTE the commands.

Sending JWT token in the headers with Postman

I had the same issue in Flask and after trying the first 2 solutions which are the same (Authorization: Bearer <token>), and getting this:

{
    "description": "Unsupported authorization type",
    "error": "Invalid JWT header",
    "status_code": 401
}

I managed to finally solve it by using:

Authorization: jwt <token>

Thought it might save some time to people who encounter the same thing.

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Apache won't run in xampp

logout your account in skype.. then in xampp control panel click start from the line of Apache..

Eclipse Java error: This selection cannot be launched and there are no recent launches

click on the project that you want to run on the left side in package explorer and then click the Run button.

What do *args and **kwargs mean?

Notice the cool thing in S.Lott's comment - you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:

def foo(a, b, c, d):
  print a, b, c, d

l = [0, 1]
d = {"d":3, "c":2}

foo(*l, **d)

Will print: 0 1 2 3

How to find index of STRING array in Java from a given value?

Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!

public static int getIndex(int x, String y, String[]v){
    for(int m = 0; m < v.length; m++){
        if (v[m].equalsIgnoreCase(y)){
            x = m;
        }
    }
    return x;
}

Google Chrome: This setting is enforced by your administrator

Any one on windows 10 Pro , this is for you guys --

  1. Open CMD in administrator mode .
  2. Paste below code-

    RD /S /Q "%WinDir%\System32\GroupPolicyUsers" 
    RD /S /Q "%WinDir%\System32\GroupPolicy" 
    gpupdate /force
    
  3. After few seconds you will see this -

    User Policy update has completed successfully.
    Computer Policy update has completed successfully.
    
  4. Now you can change your search engine to whatever you want.

Thank you

Invoke JSF managed bean action on page load

calling bean action from a will be a good idea,keep attribute autoRun="true" example below

<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />

How to enable multidexing with the new Android Multidex support library

First you should try with Proguard (This clean all code unused)

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

I ran into a problem with this as well as my JUnit assertEquals were failing comparing Dates to Hibernate emitted 'java.util.Date' types (which as described in the question are really Timestamps). It turns out that by changing the mapping to 'date' rather than 'java.util.Date' Hibernate generates java.util.Date members. I am using an XML mapping file with Hibernate version 4.1.12.

This version emits 'java.util.Timestamp':

<property name="date" column="DAY" type="java.util.Date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />

This version emits 'java.util.Date':

<property name="date" column="DAY" type="date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />

Note, however, if Hibernate is used to generate the DDL, then these will generate different SQL types (Date for 'date' and Timestamp for 'java.util.Date').

Regexp Java for password validation

easy one

("^ (?=.* [0-9]) (?=.* [a-z]) (?=.* [A-Z]) (?=.* [\\W_])[\\S]{8,10}$")

  1. (?= anything ) ->means positive looks forward in all input string and make sure for this condition is written .sample(?=.*[0-9])-> means ensure one digit number is written in the all string.if not written return false .

  2. (?! anything ) ->(vise versa) means negative looks forward if condition is written return false.

    close meaning ^(condition)(condition)(condition)(condition)[\S]{8,10}$

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I solved it by doing this:

  1. Copy the file content.
  2. Remove file.
  3. Run command: php artisan make:seeder .
  4. Copy the file content back in this file.

This happened because I made a change in the filename. I don't know why it didn't work after the change.

Command line .cmd/.bat script, how to get directory of running script

for /F "eol= delims=~" %%d in ('CD') do set curdir=%%d

pushd %curdir%

Source

SQL: Alias Column Name for Use in CASE Statement

make it so easy.

select columnnameshow = (CASE tipoventa
when 'CONTADO' then 'contadito'
when 'CREDITO' then 'cred'
else 'no result'
end) from Promocion.Promocion 

Returning a file to View/Download in ASP.NET MVC

Below code worked for me for getting a pdf file from an API service and response it out to the browser - hope it helps;

public async Task<FileResult> PrintPdfStatements(string fileName)
    {
         var fileContent = await GetFileStreamAsync(fileName);
         var fileContentBytes = ((MemoryStream)fileContent).ToArray();
         return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
    }

How to start IIS Express Manually

There is not a program but you can make a batch file and run a command like that :

powershell "start-process 'C:\Program Files (x86)\IIS Express\iisexpress.exe' -workingdirectory 'C:\Program Files (x86)\IIS Express\' -windowstyle Hidden"

Can RDP clients launch remote applications and not desktops

At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

List of enum values in java

This is a more generic solution, that can be use for any Enum object, so be free of used.

static public List<Object> constFromEnumToList(Class enumType) {
    List<Object> nueva = new ArrayList<Object>();
    if (enumType.isEnum()) {
        try {
            Class<?> cls = Class.forName(enumType.getCanonicalName());
            Object[] consts = cls.getEnumConstants();
            nueva.addAll(Arrays.asList(consts));
        } catch (ClassNotFoundException e) {
            System.out.println("No se localizo la clase");
        }
    }
    return nueva;
}

Now you must call this way:

constFromEnumToList(MiEnum.class);

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Sometimes "ARM Translation Installer v1.1" is not working.. Here is the simple solution to install Google Play.

  1. Go to this link: http://www.mediafire.com/download/jdn83v1v3bregyu/Galaxy+S4++HTC+One++Xperia+Z+-+4.2.2+-+with+Google+Apps+-+API+17+-+1080x1920.zip

  2. Download the file from the link and extract to get the Android virtual device with Google Play store. The file will be in the name as “Galaxy S4 HTC One Xperia Z – 4.2.2 – with Google Apps – API 17 – 1080×1920".

  3. Close all your Genymotion store running in the background.

  4. Copy that extracted file in to the following folder. C:\Users\'username'\AppData\Local\Genymobile\Genymotion\deployed

  5. After you copy you should see this path: C:\Users\'username'\AppData\Local\Genymobile\Genymotion\deployed\Galaxy S4 HTC One Xperia Z - 4.2.2 - with Google Apps - API 17 - 1080x1920

  6. Inside the “Galaxy S4 HTC One Xperia Z – 4.2.2 – with Google Apps – API 17 – 1080×1920" folder you will see many *.vmdk and *.vbox files.

  7. Now open VirtualBox and select Machine->Add and browse for the above folder and import the *.vbox file.

  8. Restart Genymotion. Done.

How do I convert a Django QuerySet into list of dicts?

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

phpMyAdmin allow remote users

use this,it got fixed for me, over centOS 7

<Directory /usr/share/phpMyAdmin/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I bet your machine's culture is not "en-US". From the documentation:

If provider is a null reference (Nothing in Visual Basic), the current culture is used.

If your current culture is not "en-US", this would explain why it works for me but doesn't work for you and works when you explicitly specify the culture to be "en-US".

git rebase: "error: cannot stat 'file': Permission denied"

Just close your IDE (VISUAL STUDIO/ATOM etc). It might work

jQuery: more than one handler for same event

Suppose that you have two handlers, f and g, and want to make sure that they are executed in a known and fixed order, then just encapsulate them:

$("...").click(function(event){
  f(event);
  g(event);
});

In this way there is (from the perspective of jQuery) only one handler, which calls f and g in the specified order.

Getting all types that implement an interface

You could use some LINQ to get the list:

var types = from type in this.GetType().Assembly.GetTypes()
            where type is ISomeInterface
            select type;

But really, is that more readable?

Button background as transparent

You can do it easily by adding below attribute in xml file. This code was tested plenty of time.

android:background="@android:color/transparent"

iOS Swift - Get the Current Local Time and Date Timestamp

For saving Current time to firebase database I use Unic Epoch Conversation:

let timestamp = NSDate().timeIntervalSince1970

and For Decoding Unix Epoch time to Date().

let myTimeInterval = TimeInterval(timestamp)
let time = NSDate(timeIntervalSince1970: TimeInterval(myTimeInterval))

How do I ignore a directory with SVN?

After losing a lot of time looking for how to do this simple activity, I decided to post it was not hard to find a decent explanation.

First let the sample structure

$ svn st ? project/trunk/target ? project/trunk/myfile.x

1 – first configure the editor,in mycase vim export SVN_EDITOR=vim

2 – “svn propedit svn:ignore project/trunk/” will open a new file and you can add your files and subdirectory in us case type “target” save and close file and works

$ svn st ? project/trunk/myfile.x

thanks.

PHP float with 2 decimal places: .00

As far as i know there is no solution for PHP to fix this. All other (above and below) answers given in this thread are nonsense.

The number_format function returns a string as result as written in PHP.net's own specification.

Functions like floatval/doubleval do return integers if you give as value 3.00 .

If you do typejuggling then you will get an integer as result.

If you use round() then you will get an integer as result.

The only possible solution that i can think of is using your database for type conversion to float. MySQL for example:

SELECT CAST('3.00' AS DECIMAL) AS realFloatValue;

Execute this using an abstraction layer which returns floats instead of strings and there you go.


JSON output modification

If you are looking for a solution to fix your JSON output to hold 2 decimals then you can probably use post-formatting like in the code below:

// PHP AJAX Controller

// some code here

// transform to json and then convert string to float with 2 decimals
$output = array('x' => 'y', 'price' => '0.00');
$json = json_encode($output);
$json = str_replace('"price":"'.$output['price'].'"', '"price":'.$output['price'].'', $json);

// output to browser / client
print $json;
exit();

Returns to client/browser:

{"x":"y","price":0.00}

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

This is not the recommended way to solve this error but you can suppress it quickly, it will do the job . I prefer this for prototypes or demos . add

CheckForIllegalCrossThreadCalls = false

in Form1() constructor .

Error: Cannot find module 'gulp-sass'

I had this issue for days looking for answers. My error log was similar to this npm just won't install node sass The only problem was the node version. Maybe it can help some of you.

I downgraded my Node.js from 9.3.0 to 6.12.2 and run:

npm update

How to create file object from URL object (image)

Since Java 7

File file = Paths.get(url.toURI()).toFile();

Left function in c#

Just write what you really wanted to know:

fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")

It's much simpler than anything with substring.

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

This is a kotlin solution. Put this helper method in some kotlin file-

fun EditText.setupClearButtonWithAction() {

    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear else 0
            setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
    })

    setOnTouchListener(View.OnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= (this.right - this.compoundPaddingRight)) {
                this.setText("")
                return@OnTouchListener true
            }
        }
        return@OnTouchListener false
    })
}

And then use it as following in the onCreate method and you should be good to go-

yourEditText.setupClearButtonWithAction()

BTW, you have to add R.drawable.ic_clear or the clear icon at first. This one is from google- https://material.io/tools/icons/?icon=clear&style=baseline

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

Create HTTP post request and receive response using C# console application

HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;

Hope it helps

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

How do I convert a numpy array to (and display) an image?

Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You'll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.

What are POD types in C++?

Why do we need to differentiate between POD's and non-POD's at all?

C++ started its life as an extension of C. While modern C++ is no longer a strict superset of C, people still expect a high level of compatibility between the two. The "C ABI" of a platform also frequently acts as a de-facto standard inter-language ABI for other languages on the platform.

Roughly speaking, a POD type is a type that is compatible with C and perhaps equally importantly is compatible with certain ABI optimisations.

To be compatible with C, we need to satisfy two constraints.

  1. The layout must be the same as the corresponding C type.
  2. The type must be passed to and returned from functions in the same way as the corresponding C type.

Certain C++ features are incompatible with this.

Virtual methods require the compiler to insert one or more pointers to virtual method tables, something that doesn't exist in C.

User-defined copy constructors, move constructors, copy assignments and destructors have implications for parameter passing and returning. Many C ABIs pass and return small parameters in registers, but the references passed to the user defined constructor/assigment/destructor can only work with memory locations.

So there is a need to define what types can be expected to be "C compatible" and what types cannot. C++03 was somewhat over-strict in this regard, any user-defined constructor would disable the built-in constructors and any attempt to add them back in would result in them being user-defined and hence the type being non-pod. C++11 opened things up quite a bit, by allowing the user to re-introduce the built-in constructors.

Get data type of field in select statement in ORACLE

you can use the DBMS_SQL.DESCRIBE_COLUMNS2

    SET SERVEROUTPUT ON;
DECLARE
    STMT CLOB;
    CUR NUMBER;
    COLCNT NUMBER;
    IDX NUMBER;
    COLDESC DBMS_SQL.DESC_TAB2;
BEGIN
    CUR := DBMS_SQL.OPEN_CURSOR;
    STMT := 'SELECT  object_name , to_char(object_id), created FROM    DBA_OBJECTS where rownum<10';

    SYS.DBMS_SQL.PARSE(CUR, STMT, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS2(CUR, COLCNT, COLDESC);
    DBMS_OUTPUT.PUT_LINE('Statement: ' || STMT);
    FOR IDX IN 1 .. COLCNT
    LOOP
        CASE COLDESC(IDX).col_type
        WHEN 2 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': NUMBER');
        WHEN 12 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': DATE');
        WHEN 180 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': TIMESTAMP');
        WHEN 1 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR'||':'|| COLDESC(IDX).col_max_len);
        WHEN 9 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR2');
        -- Insert more cases if you need them
        ELSE
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': OTHERS (' || TO_CHAR(COLDESC(IDX).col_type) || ')');
        END CASE;
    END LOOP;
    SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
EXCEPTION 
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE()) || ': ' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
        SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
END;
/


full example in the below url

https://www.ibm.com/support/knowledgecenter/sk/SSEPGG_9.7.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0055146.html

How to create an empty array in PHP with predefined size?

PHP Arrays don't need to be declared with a size.

An array in PHP is actually an ordered map

You also shouldn't get a warning/notice using code like the example you have shown. The common Notice people get is "Undefined offset" when reading from an array.

A way to counter this is to check with isset or array_key_exists, or to use a function such as:

function isset_or($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}

So that you can avoid the repeated code.

Note: isset returns false if the element in the array is NULL, but has a performance gain over array_key_exists.

If you want to specify an array with a size for performance reasons, look at:

SplFixedArray in the Standard PHP Library.