Programs & Examples On #Displaytag

The display tag library is an open source suite of custom Java Server Pages (JSP) tags that provide high-level web presentation patterns which will work in an MVC model.

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

Data binding in React

This could be achieved with a hook. However, I would not recommend it, as it strictly couples state and layout.

November 2019 Data Bind with Hooks

const useInput = (placeholder, initial) => {
    const [value, setVal] = useState(initial)
    const onChange = (e) => setVal(e.target.value)
    const element = <input value={value} onChange={onChange} placeholder={placeholder}/>
    return {element, value}
}

Use it in any functional component

const BensPlayGround = () => {
    const name = useInput("Enter name here")
    return (
        <>
            {name.element}
            <h1>Hello {name.value}</h1>
        </>
    )
}

Basic version - bind value and onChange

const useDataBind = () => {
    const [value, setVal] = useState("")
    const onChange = (e) => setVal(e.target.value)
    return {value, onChange}
}

const Demo = (props) => {
    const nameProps = useDataBind()
    return (
        <>
            <input {...nameProps} placeholder="Enter name here" />
            <h1>Hello {nameProps.value}</h1>
        </>
    )
}

Getting session value in javascript

var sessionVal = '@Session["EnergyUnit"]';
alert(sessionVal);

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

Build an iOS app without owning a mac?

Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:

1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.

2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal

3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.

I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.

Copy an entire worksheet to a new worksheet in Excel 2010

' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

AngularJS Uploading An Image With ng-upload

You can try ng-file-upload angularjs plugin (instead of ng-upload).

It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.

html

<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script> 
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script> 

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        data: {myObj: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).then(function(response) {
        var data = response.data;
        // file is uploaded successfully
        console.log(data);
      });
    }
  };
}];

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

user authentication libraries for node.js?

I was basically looking for the same thing. Specifically, I wanted the following:

  1. To use express.js, which wraps Connect's middleware capability
  2. "Form based" authentication
  3. Granular control over which routes are authenticated
  4. A database back-end for users/passwords
  5. Use sessions

What I ended up doing was creating my own middleware function check_auth that I pass as an argument to each route I want authenticated. check_auth merely checks the session and if the user is not logged in, then redirects them to the login page, like so:

function check_auth(req, res, next) {

  //  if the user isn't logged in, redirect them to a login page
  if(!req.session.login) {
    res.redirect("/login");
    return; // the buck stops here... we do not call next(), because
            // we don't want to proceed; instead we want to show a login page
  }

  //  the user is logged in, so call next()
  next();
}

Then for each route, I ensure this function is passed as middleware. For example:

app.get('/tasks', check_auth, function(req, res) {
    // snip
});

Finally, we need to actually handle the login process. This is straightforward:

app.get('/login', function(req, res) {
  res.render("login", {layout:false});
});

app.post('/login', function(req, res) {

  // here, I'm using mongoose.js to search for the user in mongodb
  var user_query = UserModel.findOne({email:req.body.email}, function(err, user){
    if(err) {
      res.render("login", {layout:false, locals:{ error:err } });
      return;
    }

    if(!user || user.password != req.body.password) {
      res.render("login",
        {layout:false,
          locals:{ error:"Invalid login!", email:req.body.email }
        }
      );
    } else {
      // successful login; store the session info
      req.session.login = req.body.email;
      res.redirect("/");
    }
  });
});

At any rate, this approach was mostly designed to be flexible and simple. I'm sure there are numerous ways to improve it. If you have any, I'd very much like your feedback.

EDIT: This is a simplified example. In a production system, you'd never want to store & compare passwords in plain text. As a commenter points out, there are libs that can help manage password security.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

How do I use setsockopt(SO_REUSEADDR)?

Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :

   SO_REUSEPORT (since Linux 3.9)
          Permits multiple AF_INET or AF_INET6 sockets to be bound to an
          identical socket address.  This option must be set on each
          socket (including the first socket) prior to calling bind(2)
          on the socket.  To prevent port hijacking, all of the
          processes binding to the same address must have the same
          effective UID.  This option can be employed with both TCP and
          UDP sockets.

As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.

You can set theses two options before calling bind like this :

    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
        perror("setsockopt(SO_REUSEADDR) failed");

#ifdef SO_REUSEPORT
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0) 
        perror("setsockopt(SO_REUSEPORT) failed");
#endif

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

Paulo's help lead me to the solution. It was a combination of the following:

  • the password contained a dollar sign
  • I was trying to connect from a Linux shell

The bash shell treats the dollar sign as a special character for expansion to an environment variable, so we need to escape it with a backslash. Incidentally, we don't have to do this in the case where the dollar sign is the final character of the password.

As an example, if your password is "pas$word", from Linux bash we must connect as follows:

# mysql --host=192.168.233.142 --user=root --password=pas\$word

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

jQuery: Get height of hidden element in jQuery

I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.

flexibox example enter image description here

I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.

Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.

$('[selector]').onVisibleChanged(function(e, isVisible)
{
    var realWidth = $('[selector]').width();
    var realHeight = $('[selector]').height();

    // render or adjust something
});

For more information, Please visit at my project GitHub.

https://github.com/Soul-Master/visible.event.js

demo: http://jsbin.com/ETiGIre/7

How to make HTML table cell editable?

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

_x000D_
_x000D_
function edit(el) {_x000D_
  el.childNodes[0].removeAttribute("disabled");_x000D_
  el.childNodes[0].focus();_x000D_
  window.getSelection().removeAllRanges();_x000D_
}_x000D_
function disable(el) {_x000D_
  el.setAttribute("disabled","");_x000D_
}
_x000D_
<table border>_x000D_
<tr>_x000D_
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

If you use module with c++ code and have the same issue you could try

Build -> Refresh Linked C++ Projects

Also, you should open some file from this module and do

Build -> Make module "YourNativeLibModuleName"

Returning http status code from Web Api controller

Try this :

return new ContentResult() { 
    StatusCode = 404, 
    Content = "Not found" 
};

Get output parameter value in ADO.NET

That looks more explicit for me:

int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;

Node.js get file extension

I believe you can do the following to get the extension of a file name.

var path = require('path')

path.extname('index.html')
// returns
'.html'

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

I moved implementation to module-level build.gradle from root-level build.gradle. It solves the issue.

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How to check whether a int is not null or empty?

An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.

Example:

int x;

// Some Code...

if (x <= 0 || x > 0){
    // What you want the code to do if x has a value
} else {
    // What you want the code to do if x has no value 
}

Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

I like this method:

using Newtonsoft.Json.Linq;
// jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, object> dictObj = jsonObj.ToObject<Dictionary<string, object>>();

You can now access anything you want using the dictObj as a dictionary. You can also use Dictionary<string, string> if you prefer to get the values as strings.

You can use this same method to cast as any kind of .NET object.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Using Python to execute a command on every file in a folder

I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.

It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD

I also add a small interface, hope someone else find it useful!

I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

jQuery Mobile: document ready vs. page events

The simple difference between document ready and page event in jQuery-mobile is that:

  1. The document ready event is used for the whole HTML page,

    $(document).ready(function(e) {
        // Your code
    });
    
  2. When there is a page event, use for handling particular page event:

    <div data-role="page" id="second">
        <div data-role="header">
            <h3>
                Page header
            </h3>
        </div>
        <div data-role="content">
            Page content
        </div> <!--content-->
        <div data-role="footer">
            Page footer
        </div> <!--footer-->
    </div><!--page-->
    

You can also use document for handling the pageinit event:

$(document).on('pageinit', "#mypage", function() {

});

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

catch forEach last iteration

The 2018 ES6+ ANSWER IS:

    const arr = [1, 2, 3];

    arr.forEach((val, key, arr) => {
      if (Object.is(arr.length - 1, key)) {
        // execute last item logic
        console.log(`Last callback call at index ${key} with value ${val}` ); 
      }
    });

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

How to change href attribute using JavaScript after opening the link in a new window?

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

Maven Unable to locate the Javac Compiler in:

It sounds like you have JDK_HOME defined as a user variable and PATH defined as a System variable, or vice versa - echo %PATH% should not contain unresolved variables like ...;%JDK_HOME%.

Make sure that the %JDK_HOME%\bin path is on your PATH variable, unresolved, even if you have to put the path in explicitly.

How to list running screen sessions?

So you're using screen to keep the experiments running in the background, or what? If so, why not just start it in the background?

./experiment &

And if you're asking how to get notification the job i done, how about stringing the experiment together with a mail command?

./experiment && echo "the deed is done" | mail youruser@yourlocalworkstation -s "job on server $HOSTNAME is done"

Set selected option of select box

I had a problem where the value was not set because of a syntax error before the call.

$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.

Check for syntax errors before the call.

Don't understand why UnboundLocalError occurs (closure)

Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line

counter += 1

implicitly makes counter local to increment(). Trying to execute this line, though, will try to read the value of the local variable counter before it is assigned, resulting in an UnboundLocalError.[2]

If counter is a global variable, the global keyword will help. If increment() is a local function and counter a local variable, you can use nonlocal in Python 3.x.

How to get param from url in angular 4?

This should do the trick retrieving the params from the url:

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        let date = params['startdate'];
        console.log(date); // Print the parameter to the console. 
    });
}

The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).

Failed to connect to mailserver at "localhost" port 25

You need to be running a mail server locally. If this is Unix, enable sendmail If this is Windows install the Simple Mail Transfer Server (not sure if the name is correct) component of IIs. E.g. for windows 2003 follow this: http://msdn.microsoft.com/en-us/library/8b83ac7t.aspx

Applying .gitignore to committed files

After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do

  • Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
  • Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
  • Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"

to remove them from the repository (without deleting them from disk).

Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):

apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached

(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)

Now you can just type git apply-gitignore in your repo, and it'll do the work for you!

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Another trap of note is making sure you're not decorating controllers with the Consume Attribute as below:

[Produces("application/json")]
[Consumes("application/json")]
public class MyController : Controller

This will fail with a 415 Unsupported Media Type if the upload is NOT JSON.

A "friend of mine" was recently caught out by this like so:

public class MyFileUploadController : MyCustomController {

}

[Produces("application/json")]
[Consumes("application/json")]
public class MyCustomController : ControllerBase {

}

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

Place ojdbc6.jar in your project resources folder of eclipse. then add the following dependency code in your pom.xml

<dependency>
<groupId> oracle </groupId>
 <artifactId>ojdbc6</artifactId>
 <version>11.2.0</version>
  <scope>system</scope>
  <systemPath>${project.basedir}/src/main/resources/ojdbc6.jar</systemPath>
</dependency>

Select columns in PySpark dataframe

The dataset in ss.csv contains some columns I am interested in:

ss_ = spark.read.csv("ss.csv", header= True, 
                      inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']

but I only need a few:

columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or  k == 'MMWR Week'

The filter returns the list of desired columns, list is evaluated:

sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)

the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:

dfss = ss_.select(*to_keep)
dfss.columns

The result:

['Reporting Area',
 'MMWR Year',
 'MMWR Week',
 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
 'Shiga toxin-producing Escherichia coli, Current week',
 'Shigellosis, Current week']

The df.select() has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop

to drop the list of columns.

Your project contains error(s), please fix it before running it

Simply Deleted my debug certificate under ~/.android/debug.keystore and Project->Clean did solve the problem.

Div table-cell vertical align not working

Sometime floats brake the vertical align, is better to avoid them.

How to get directory size in PHP

Even though there are already many many answers to this post, I feel I have to add another option for unix hosts that only returns the sum of all file sizes in the directory (recursively).

If you look at Jonathan's answer he uses the du command. This command will return the total directory size but the pure PHP solutions posted by others here will return the sum of all file sizes. Big difference!

What to look out for

When running du on a newly created directory, it may return 4K instead of 0. This may even get more confusing after having deleted files from the directory in question, having du reporting a total directory size that does not correspond to the sum of the sizes of the files within it. Why? The command du returns a report based on some file settings, as Hermann Ingjaldsson commented on this post.

The solution

To form a solution that behaves like some of the PHP-only scripts posted here, you can use ls command and pipe it to awk like this:

ls -ltrR /path/to/dir |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'

As a PHP function you could use something like this:

function getDirectorySize( $path )
{
    if( !is_dir( $path ) ) {
        return 0;
    }

    $path   = strval( $path );
    $io     = popen( "ls -ltrR {$path} |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'", 'r' );
    $size   = intval( fgets( $io, 80 ) );
    pclose( $io );

    return $size;
}

CORS with spring-boot and angularjs not working

Step 1

By annotating the controller with @CrossOrigin annotation will allow the CORS configurations.

@CrossOrigin
@RestController
public class SampleController { 
  .....
}

Step 2

Spring already has a CorsFilter even though You can just register your own CorsFilter as a bean to provide your own configuration as follows.

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // Provide list of origins if you want multiple origins
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    config.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

Text border using css (border around text)

I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.

The right tool exists, it's SVG <text> The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too, filter: progid:DXImageTransform can be used or IE < 10 but often doesn't work as expected.

To me the best solution remains SVG with a fallback in not-stroked text for older browser:

This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9

Compared to text-shadow whose supports are: Chrome 4.0, FF 3.5, IE 10, Safari 4.0, Opera 9, it results even more compatible.

_x000D_
_x000D_
.stroke {_x000D_
  margin: 0;_x000D_
  font-family: arial;_x000D_
  font-size:70px;_x000D_
  font-weight: bold;_x000D_
  }_x000D_
  _x000D_
  svg {_x000D_
    display: block;_x000D_
  }_x000D_
  _x000D_
  text {_x000D_
    fill: black;_x000D_
    stroke: red;_x000D_
    stroke-width: 3;_x000D_
  }
_x000D_
<p class="stroke">_x000D_
  <svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
    <text x="0" y="70">Stroked text</text>_x000D_
  </svg>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

How to use callback with useState hook in react

You can use like below -

this.setState(() => ({  subChartType1: value   }), () => this.props.dispatch(setChartData(null)));

Identifying country by IP address

Here is my solution in Python 3.x to return geo-location info given a dataframe containing IP Address(s); efficient parallelized application of function on vectorized pd.series/dataframe is the way to go.

Will contrast performance of two popular libraries to return location.

TLDR: use geolite2 method.

1. geolite2 package from geolite2 library

Input

# !pip install maxminddb-geolite2
import time
from geolite2 import geolite2
geo = geolite2.reader()
df_1 = train_data.loc[:50,['IP_Address']]

def IP_info_1(ip):
    try:
        x = geo.get(ip)
    except ValueError:   #Faulty IP value
        return np.nan
    try:
        return x['country']['names']['en'] if x is not None else np.nan
    except KeyError:   #Faulty Key value
        return np.nan

s_time = time.time()
# map IP --> country
#apply(fn) applies fn. on all pd.series elements
df_1['country'] = df_1.loc[:,'IP_Address'].apply(IP_info_1)
print(df_1.head(), '\n')
print('Time:',str(time.time()-s_time)+'s \n')

print(type(geo.get('48.151.136.76')))

Output

       IP_Address         country
0   48.151.136.76   United States
1    94.9.145.169  United Kingdom
2   58.94.157.121           Japan
3  193.187.41.186         Austria
4   125.96.20.172           China 

Time: 0.09906983375549316s 

<class 'dict'>

2. DbIpCity package from ip2geotools library

Input

# !pip install ip2geotools
import time
s_time = time.time()
from ip2geotools.databases.noncommercial import DbIpCity
df_2 = train_data.loc[:50,['IP_Address']]
def IP_info_2(ip):
    try:
        return DbIpCity.get(ip, api_key = 'free').country
    except:
        return np.nan
df_2['country'] = df_2.loc[:, 'IP_Address'].apply(IP_info_2)
print(df_2.head())
print('Time:',str(time.time()-s_time)+'s')

print(type(DbIpCity.get('48.151.136.76',api_key = 'free')))

Output

       IP_Address country
0   48.151.136.76      US
1    94.9.145.169      GB
2   58.94.157.121      JP
3  193.187.41.186      AT
4   125.96.20.172      CN

Time: 80.53318452835083s 

<class 'ip2geotools.models.IpLocation'>

A reason why the huge time difference could be due to the Data structure of the output, i.e direct subsetting from dictionaries seems way more efficient than indexing from the specicialized ip2geotools.models.IpLocation object.

Also, the output of the 1st method is dictionary containing geo-location data, subset respecitively to obtain needed info:

x = geolite2.reader().get('48.151.136.76')
print(x)

>>>
    {'city': {'geoname_id': 5101798, 'names': {'de': 'Newark', 'en': 'Newark', 'es': 'Newark', 'fr': 'Newark', 'ja': '??????', 'pt-BR': 'Newark', 'ru': '??????'}},

 'continent': {'code': 'NA', 'geoname_id': 6255149, 'names': {'de': 'Nordamerika', 'en': 'North America', 'es': 'Norteamérica', 'fr': 'Amérique du Nord', 'ja': '?????', 'pt-BR': 'América do Norte', 'ru': '???????? ???????', 'zh-CN': '???'}}, 

'country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'location': {'accuracy_radius': 1000, 'latitude': 40.7355, 'longitude': -74.1741, 'metro_code': 501, 'time_zone': 'America/New_York'}, 

'postal': {'code': '07102'}, 

'registered_country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'subdivisions': [{'geoname_id': 5101760, 'iso_code': 'NJ', 'names': {'en': 'New Jersey', 'es': 'Nueva Jersey', 'fr': 'New Jersey', 'ja': '?????????', 'pt-BR': 'Nova Jérsia', 'ru': '???-??????', 'zh-CN': '????'}}]}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.

How to find out what type of a Mat object is with Mat::type() in OpenCV

I always use this link to see what type is the number I get with type():
LIST OF MAT TYPE IN OPENCV
I hope this can help you.

jquery background-color change on focus and blur

What you are trying to do can be simplified down to this.

_x000D_
_x000D_
$('input:text').bind('focus blur', function() {_x000D_
    $(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
    background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
    <input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
    <input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
    <input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How to execute only one test spec with angular-cli

In a bash terminal I like to use the double dash. Using VS Code, you can right click on the spec file in the explorer, or on the open tab. Then select 'Copy Relative Path'. Run the command below pasting the relative path in from the clipboard.

npm t -- --include relative/path/to/file.spec.ts

The double dash signals the end of your command options for npm t and passes anything after that to the next command which is pointing to ng t. It's doesn't require any modification and quickly gives desired results.

Interfaces vs. abstract classes

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

How do you change the launcher logo of an app in Android Studio?

Try this process, this may help you.

  1. Create PNG image file of size 512x512 pixels
  2. In menu, go to File -> New -> Image Asset
  3. Select Image option in Asset type options
  4. Click on Directory Box at right.
  5. Drag image to source asset box
  6. Click Next (Note: Existing launcher files will be overwritten)
  7. Click Finish

***** NB: Icon type should be Launcher Icons (Adaptive and Legacy) *****

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Or try adding this...

$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)

By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Found other similar question, but not the answer.

It would have been interesting to know, where you have found this question.

As far as I can remember and according com.jcraft.jsch.JSchException: Auth cancel try to add to method .addIdentity() a passphrase. You can use "" in case you generated a keyfile without one. Another source of error is the fingerprint string. If it doesn't match you will get an authentication failure either (depends from on the target server).

And at last here my working source code - after I could solve the ugly administration tasks:

public void connect(String host, int port, 
                    String user, String pwd,
                    String privateKey, String fingerPrint,
                    String passPhrase
                  ) throws JSchException{
    JSch jsch = new JSch();

    String absoluteFilePathPrivatekey = "./";
    File tmpFileObject = new File(privateKey);
    if (tmpFileObject.exists() && tmpFileObject.isFile())
    {
      absoluteFilePathPrivatekey = tmpFileObject.getAbsolutePath();
    }

    jsch.addIdentity(absoluteFilePathPrivatekey, passPhrase);
    session = jsch.getSession(user, host, port);

    //Password and fingerprint will be given via UserInfo interface.
    UserInfo ui = new UserInfoImpl(pwd, fingerPrint);
    session.setUserInfo(ui);

    session.connect();

    Channel channel = session.openChannel("sftp");
    channel.connect();
    c = (ChannelSftp) channel;
}

What is the purpose of the var keyword and when should I use it (or omit it)?

@Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.

As you'd expect the following snippet outputs ["text"]:

_x000D_
_x000D_
function var_fun() {_x000D_
  let array = []_x000D_
  array.push('text')_x000D_
  return array_x000D_
}_x000D_
_x000D_
console.log(var_fun())
_x000D_
_x000D_
_x000D_

So does the following snippet (note the missing let before array):

_x000D_
_x000D_
function var_fun() {_x000D_
  array = []_x000D_
  array.push('text')_x000D_
  return array_x000D_
}_x000D_
_x000D_
console.log(var_fun())
_x000D_
_x000D_
_x000D_

Executing the data manipulation asynchronously still produces the same result with a single executor:

_x000D_
_x000D_
function var_fun() {_x000D_
  array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
var_fun().then(result => {console.log(result)})
_x000D_
_x000D_
_x000D_

But behaves differently with multiple ones:

_x000D_
_x000D_
function var_fun() {_x000D_
  array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
[1,2,3].forEach(i => {_x000D_
  var_fun().then(result => {console.log(result)})_x000D_
})
_x000D_
_x000D_
_x000D_

Using let however:

_x000D_
_x000D_
function var_fun() {_x000D_
  let array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
[1,2,3].forEach(i => {_x000D_
  var_fun().then(result => {console.log(result)})_x000D_
})
_x000D_
_x000D_
_x000D_

npm can't find package.json

try re-install Node.js

curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -

sudo apt-get install -y nodejs

sudo apt-get install -y build-essential

and update npm

curl -L https://npmjs.com/install.sh | sudo sh

Convert floats to ints in Pandas?

Here's a simple function that will downcast floats into the smallest possible integer type that doesn't lose any information. For examples,

  • 100.0 can be converted from float to integer, but 99.9 can't (without losing information to rounding or truncation)

  • Additionally, 1.0 can be downcast all the way to int8 without losing information, but the smallest integer type for 100_000.0 is int32

Code examples:

import numpy as np
import pandas as pd

def float_to_int( s ):
    if ( s.astype(np.int64) == s ).all():
        return pd.to_numeric( s, downcast='integer' )
    else:
        return s

# small integers are downcast into 8-bit integers
float_to_int( np.array([1.0,2.0]) )
Out[1]:array([1, 2], dtype=int8)

# larger integers are downcast into larger integer types
float_to_int( np.array([100_000.,200_000.]) )
Out[2]: array([100000, 200000], dtype=int32)

# if there are values to the right of the decimal
# point, no conversion is made
float_to_int( np.array([1.1,2.2]) )
Out[3]: array([ 1.1,  2.2])

Limiting number of displayed results when using ngRepeat

A little late to the party, but this worked for me. Hopefully someone else finds it useful.

<div ng-repeat="video in videos" ng-if="$index < 3">
    ...
</div>

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

This is the check on which it fails:

Which says

def _assert_all_finite(X):
    """Like assert_all_finite, but only for ndarray."""
    X = np.asanyarray(X)
    # First try an O(n) time, O(1) space solution for the common case that
    # everything is finite; fall back to O(n) space np.isfinite to prevent
    # false positives from overflow in sum method.
    if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
            and not np.isfinite(X).all()):
        raise ValueError("Input contains NaN, infinity"
                         " or a value too large for %r." % X.dtype)

So make sure that you have non NaN values in your input. And all those values are actually float values. None of the values should be Inf either.

Signed versus Unsigned Integers

Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.

Why I got " cannot be resolved to a type" error?

I had wrong package names:

main.java.hello and main.test.hello rather than com.blabla.hello.

  1. I renamed my src-folder to src/main/java and created another src-folder src/test/java.
  2. I renamed my package within src/main/java to com.blabla.hello
  3. I created another package with the same name in src/test/java.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you have a proper cors header in place. Your corporate network may be stripping off the cors header. If the website is externally accessible, try accessing it from outside your network to verify whether the network is causing the problem--a good idea regardless of the cause.

How to capture UIView to UIImage without loss of quality on retina display

Here's a Swift 4 UIView extension based on the answer from @Dima.

extension UIView {
   func snapshotImage() -> UIImage? {
       UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
       drawHierarchy(in: bounds, afterScreenUpdates: false)
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image
   }
}

Go to Matching Brace in Visual Studio?

On a Mac use command+shift+\.

Source: a comment on this answer: https://stackoverflow.com/a/37877082/3345085. Tested in Visual Studio Code version 1.10.2.

Android 5.0 - Add header/footer to a RecyclerView

You can use the library SectionedRecyclerViewAdapter to group your items in sections and add a header to each section, like on the image below:

enter image description here

First you create your section class:

class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new SimpleHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }
}

Then you set up the RecyclerView with your sections and change the SpanSize of the headers with a GridLayoutManager:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data
MySection section1 = new MySection("My Section 1 title", dataList1);
MySection section2 = new MySection("My Section 2 title", dataList2);

// Add your Sections to the adapter
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);

// Set up a GridLayoutManager to change the SpanSize of the header
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);

What is the best JavaScript code to create an img element

var img = new Image(1,1); // width, height values are optional params 
img.src = 'http://www.testtrackinglink.com';

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

How to get a list of column names

Yes, you can achieve this by using the following commands:

sqlite> .headers on
sqlite> .mode column

The result of a select on your table will then look like:

id          foo         bar         age         street      address
----------  ----------  ----------  ----------  ----------  ----------
1           val1        val2        val3        val4        val5
2           val6        val7        val8        val9        val10

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

For the Scripting.Dictionary type, you can either use late binding (as already pointed out ) with:

Dim Dict as Object
Set Dict = CreateObject("Scripting.Dictionary")

Which works, but you don't get the code auto completion. Or you use early binding, but you need to make sure that VBA can find the Scripting.Dictionary type by adding the reference to the Microsoft Scripting Library via VBA-->Tools-->References--> "Microsoft Scripting Runtime". Then you can use:

Dim Dict as Scripting.Dictionary
Set Dict = New Scripting.Dictionary

... and auto completion will work.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I wasn't completely happy by the --allow-file-access-from-files solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.

Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

onclick go full screen

I realize this is a very old question, and that the answers provided were adequate, since is active and I came across this by doing some research on fullscreen, I leave here one update to this topic:

There is a way to "simulate" the F11 key, but cannot be automated, the user actually needs to click a button for example, in order to trigger the full screen mode.

  • Toggle Fullscreen status on button click

    With this example, the user can switch to and from fullscreen mode by clicking a button:

    HTML element to act as trigger:

    <input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
    

    JavaScript:

    function toggleFullScreen() {
      if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
       (!document.mozFullScreen && !document.webkitIsFullScreen)) {
        if (document.documentElement.requestFullScreen) {  
          document.documentElement.requestFullScreen();  
        } else if (document.documentElement.mozRequestFullScreen) {  
          document.documentElement.mozRequestFullScreen();  
        } else if (document.documentElement.webkitRequestFullScreen) {  
          document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
        }  
      } else {  
        if (document.cancelFullScreen) {  
          document.cancelFullScreen();  
        } else if (document.mozCancelFullScreen) {  
          document.mozCancelFullScreen();  
        } else if (document.webkitCancelFullScreen) {  
          document.webkitCancelFullScreen();  
        }  
      }  
    }
    
  • Go to Fullscreen on button click

    This example allows you to enable full screen mode without making alternation, ie you switch to full screen but to return to the normal screen will have to use the F11 key:

    HTML element to act as trigger:

    <input type="button" value="click to go fullscreen" onclick="requestFullScreen()">
    

    JavaScript:

    function requestFullScreen() {
    
      var el = document.body;
    
      // Supports most browsers and their versions.
      var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen 
      || el.mozRequestFullScreen || el.msRequestFullScreen;
    
      if (requestMethod) {
    
        // Native full screen.
        requestMethod.call(el);
    
      } else if (typeof window.ActiveXObject !== "undefined") {
    
        // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
    
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
    }
    

Sources found along with useful information on this subject:

Mozilla Developer Network

How to make in Javascript full screen windows (stretching all over the screen)

How to make browser full screen using F11 key event through JavaScript

Chrome Fullscreen API

jQuery fullscreen event plugin, version 0.2.0

jquery-fullscreen-plugin

PHP: How to send HTTP response code?

We can get different return value from http_response_code via the two different environment:

  1. Web Server Environment
  2. CLI environment

At the web server environment, return previous response code if you provided a response code or when you do not provide any response code then it will be print the current value. Default value is 200 (OK).

At CLI Environment, true will be return if you provided a response code and false if you do not provide any response_code.

Example of Web Server Environment of Response_code's return value:

var_dump(http_respone_code(500)); // int(200)
var_dump(http_response_code()); // int(500)

Example of CLI Environment of Response_code's return value:

var_dump(http_response_code()); // bool(false)
var_dump(http_response_code(501)); // bool(true)
var_dump(http_response_code()); // int(501)

state machines tutorials

There is a lot of lesson to learn handcrafting state machines in C, but let me also suggest Ragel state machine compiler:

http://www.complang.org/ragel/

It has quite simple way of defining state machines and then you can generate graphs, generate code in different styles (table-driven, goto-driven), analyze that code if you want to, etc. And it's powerful, can be used in production code for various protocols.

Line break in SSRS expression

I've always had luck with the Chr(10) & Chr(13) - I have provided a sample below. This is an expression for an address text box I have in a report.

=Iif(Fields!GUAR_STREET_2.Value <> "",Fields!GUAR_STREET.Value & Chr(10) & Chr(13) & LTrim(Fields!GUAR_STREET_2.Value),Fields!GUAR_STREET.Value)

Also, if you are building a string you need to concatenate stuff together with an & not a + Here is what I think your example should look like

    =IIF(First(Fields!VCHTYPE.Value, "Dataset1")="C","This is a huge paragrpah of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) &  Chr(10) & Chr(13) & "Its not working though."
, "This is the second huge paragraph of text." &
Chr(10) & Chr(13) & "separated by line feeds at each paragraph." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "I want to separate the paragraphs." &
Chr(10) & Chr(13) & Chr(10) & Chr(13) & "Its not working though." )

How to fix docker: Got permission denied issue

To fix that issue, I searched where is my docker and docker-compose installed. In my case, docker was installed in /usr/bin/docker and docker-compose was installed in /usr/local/bin/docker-compose path. Then, I write this in my terminal:

To docker:

sudo chmod +x /usr/bin/docker

To docker-compose:

sudo chmod +x /usr/local/bin/docker-compose

Now I don't need write in my commands docker the word sudo

/***********************************************************************/

ERRATA:

The best solution of this issue was commented by @mkasberg. I quote comment:

That might work, you might run into issues down the road. Also, it's a security vulnerability. You'd be better off just adding yourself to the docker group, as the docs say. sudo groupadd docker, sudo usermod -aG docker $USER. Docs: https://docs.docker.com/install/linux/linux-postinstall/

Thanks a lot!

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

"Items collection must be empty before using ItemsSource."

I had this same error for a while in a slightly different scenario. I had

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGridTextColumn 
        Header="Account Name" 
        Binding="{Binding Path=AccountName}" />
</wpftoolkit:DataGrid>

which I fixed to be

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGrid.Columns>
        <wpftoolkit:DataGridTextColumn 
            Header="Account Name" 
            Binding="{Binding Path=AccountName}" />
    </wpftoolkit:DataGrid.Columns>
</wpftoolkit:DataGrid>

Linux Command History with date and time

It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history if there is any timestamp there).

To have bash store the timestamp you need to set HISTTIMEFORMAT before executing the commands, e.g. in .bashrc or .bash_profile. This will cause bash to store the timestamps in .bash_history (see the entries starting with #).

Check if a string is a valid date using DateTime.TryParse

If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse

DateTime.TryParse

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.

If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output: 
//       Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM. 
//       Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM. 
//       Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM. 
//       Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

Display all items in array using jquery

You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:

var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
    newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));

Some people prefer to use jQuery's .each() method instead of the for loop which would work like this:

var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
    newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery's .map can be used like this:

var array = [...];
var newHTML = $.map(array, function(value) {
    return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map(). My guess is that the for loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.

FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.


And, if you can live with IE9 or above (or install an ES5 polyfill for .map()), you can use the array version of .map like this:

var array = [...];
$(".element").html(array.map(function(value) {
    return('<span>' + value + '</span>');
}).join(""));

Note: this version also gets rid of the newHTML intermediate variable in the interest of compactness.

Node.js Error: Cannot find module express

D:\learn\Node.js\node app.js
module.js:549
    throw err;
    ^

Error: Cannot find module 'body-parser'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)

Sometimes version not match with package.json Fixed the problem by checking the package.json then use the following commands: npm install [email protected] it resolved for me.

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

Float sum with javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

How do I get the type of a variable?

#include <typeinfo>

...
string s = typeid(YourClass).name()

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

Why does the order in which libraries are linked sometimes cause errors in GCC?

Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

No internet on Android emulator - why and how to fix?

If you run into this problem and are working with a non-Windows/Mac OS (Ubuntu in my case), try starting the emulator by itself in Android SDK and AVD Manager then running your application.

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

When to use malloc for char pointers

malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.

Laravel 5 - redirect to HTTPS

This work for me in Laravel 7.x in 3 simple steps using a middleware:

1) Generate the middleware with command php artisan make:middleware ForceSSL

Middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class ForceSSL
{
    public function handle($request, Closure $next)
    {
        if (!$request->secure() && App::environment() === 'production') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

2) Register the middleware in routeMiddleware inside Kernel file

Kernel

protected $routeMiddleware = [
    //...
    'ssl' => \App\Http\Middleware\ForceSSL::class,
];

3) Use it in your routes

Routes

Route::middleware('ssl')->group(function() {
    // All your routes here

});

here the full documentation about middlewares

========================

.HTACCESS Method

If you prefer to use an .htaccess file, you can use the following code:

<IfModule mod_rewrite.c>
    RewriteEngine On 
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^(.*)$ https://yourdomain.com/$1 [R,L]
</IfModule>

Regards!

Accessing certain pixel RGB value in openCV

The current version allows the cv::Mat::at function to handle 3 dimensions. So for a Mat object m, m.at<uchar>(0,0,0) should work.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

Java unsupported major minor version 52.0

I assumed openjdk8 would work with tomcat8 but I had to remove it and keep openjdk7 only, this fixed the issue in my case. I really don't know why or if there is something else I could have done.

What is difference between Axios and Fetch?

They are HTTP request libraries...

I end up with the same doubt but the table in this post makes me go with isomorphic-fetch. Which is fetch but works with NodeJS.

http://andrewhfarmer.com/ajax-libraries/


The link above is dead The same table is here: https://www.javascriptstuff.com/ajax-libraries/

Or here: enter image description here

MS SQL compare dates?

Use the DATEDIFF function with a datepart of day.

SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0

Note that if you want to test that date1 <= date2 then you need to test that DATEDIFF(day, date1, date2) >= 0, or alternatively you could test DATEDIFF(day, date2, date1) <= 0.

Check if a variable is a string in JavaScript

If you work on the node.js environment, you can simply use the built-in function isString in utils.

const util = require('util');
if (util.isString(myVar)) {}

Edit: as @Jehy mentioned, this is deprecated since v4.

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

You seem to not be depending on "@angular/core". This is an error

Try to run

npm install

in the project folder

Print in one line dynamically

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

How to get the name of the current method from code

I think the best way to get the full name is:

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

or try this

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

Using 'make' on OS X

@Daniel's suggestion worked perfectly for me. To install

make
, open Xcode, go to Preferences -> Downloads -> Components -> Command Line Tools.You can then test with
gcc -v

What online brokers offer APIs?

There are a few. I was looking into MBTrading for a friend. I didn't get too far, as my friend lost interest. Seemed relatively straigt forward with a C# and VB.Net SDK. They had some docs and everything. This was ~6 months ago, so it may be better (or worse) by now.

IIRC, you can create a demo account for free. I don't remember all the details, but it let you connect to their test server and pull quotes and make fake trades and such to get your software fine tuned.

Don't know much about cost for an actual account or anything.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

Creating hard and soft links using PowerShell

In Windows 7, the command is

fsutil hardlink create new-file existing-file

PowerShell finds it without the full path (c:\Windows\system32) or extension (.exe).

SQL Server Format Date DD.MM.YYYY HH:MM:SS

See http://msdn.microsoft.com/en-us/library/ms187928.aspx

You can concatenate it:

SELECT CONVERT(VARCHAR(10), GETDATE(), 104) + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

PHP: HTTP or HTTPS?

You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).

See http://php.net/manual/en/reserved.variables.server.php.

difference between new String[]{} and new String[] in java

You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.

How to remove docker completely from ubuntu 14.04

This removes "docker.io" completely from ubuntu sudo apt-get purge docker.io

Programmatically scroll to a specific position in an Android ListView

If you want to jump directly to the desired position in a listView just use

listView.setSelection(int position);

and if you want to jump smoothly to the desired position in listView just use

listView.smoothScrollToPosition(int position);

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

Setting core.filemode to false does work, but make sure the settings in ~/.gitconfig aren't being overridden by those in .git/config.

Copy tables from one database to another in SQL Server

  1. Script the create table in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)

  2. INSERT bar.[schema].table SELECT * FROM foo.[schema].table

How to have multiple colors in a Windows batch file?

Several methods are covered in
"51} How can I echo lines in different colors in NT scripts?"
http://www.netikka.net/tsneti/info/tscmd051.htm

One of the alternatives: If you can get hold of QBASIC, using colors is relatively easy:

  @echo off & setlocal enableextensions
  for /f "tokens=*" %%f in ("%temp%") do set temp_=%%~sf
  set skip=
  findstr "'%skip%QB" "%~f0" > %temp_%\tmp$$$.bas
  qbasic /run %temp_%\tmp$$$.bas
  for %%f in (%temp_%\tmp$$$.bas) do if exist %%f del %%f
  endlocal & goto :EOF
  ::
  CLS 'QB
  COLOR 14,0 'QB
  PRINT "A simple "; 'QB
  COLOR 13,0 'QB
  PRINT "color "; 'QB
  COLOR 14,0 'QB
  PRINT "demonstration" 'QB
  PRINT "By Prof. (emer.) Timo Salmi" 'QB
  PRINT 'QB
  FOR j = 0 TO 7 'QB
    FOR i = 0 TO 15 'QB
      COLOR i, j 'QB
      PRINT LTRIM$(STR$(i)); " "; LTRIM$(STR$(j)); 'QB
      COLOR 1, 0 'QB
      PRINT " "; 'QB
    NEXT i 'QB
    PRINT 'QB
  NEXT j 'QB
  SYSTEM 'QB

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

EDIT: Please use @cbowns solution - deviceconsole is compatible with iOS9 and much easier to use.

This is a open-source program that displays the iDevice's system log in Terminal (in a manner similar to tail -F). No jailbreak is required, and the output is fully grep'able so you can filter to see output from your program only. What's particularly good about this solution is you can view the log whether or not the app was launched in debug mode from XCode.

Here's how:

Grab the libimobiledevice binary for Mac OS X from my github account at https://github.com/benvium/libimobiledevice-macosx/zipball/master

Follow the install instructions here: https://github.com/benvium/libimobiledevice-macosx/blob/master/README.md

Connect your device, open up Terminal.app and type:

idevicesyslog

Up pops a real-time display of the device's system log.

With it being a console app, you can filter the log using unix commands, such as grep

For instance, see all log messages from a particular app:

idevicesyslog | grep myappname

Taken from my blog at http://pervasivecode.blogspot.co.uk/2012/06/view-log-output-of-any-app-on-iphone-or.html

Git push error: Unable to unlink old (Permission denied)

sudo chown -R $USER:$USER .

Did the job for me.

Email and phone Number Validation in android

XML

<android.support.v7.widget.AppCompatEditText
    android:id="@+id/et_email_contact"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1"
    android:hint="Enter Email or Phone Number"/>

Java

private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;     

et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String regex = "^[+]?[0-9]{10,13}$";
        String emailContact = s.toString();
        if (TextUtils.isEmpty(emailContact)) {
            Log.e("Validation", "Enter Mobile No or Email");
        } else {
            if (emailContact.matches(regex)) {
                Log.e("Validation", "Valid Mobile No");
                validPhone = true;
                validEmail = false;
            } else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
                Log.e("Validation", "Valid Email Address");
                validPhone = false;
                validEmail = true;
            } else {
                validPhone = false;
                validEmail = false;
                Log.e("Validation", "Invalid Mobile No or Email");
            }
        }
    }
});

if (validPhone || validEmail) {
    Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}

Custom format for time command

The accepted answer gives me this output

# bash date.sh
Time in seconds: 51
date.sh: line 12: unexpected EOF while looking for matching `"'
date.sh: line 21: syntax error: unexpected end of file

This is how I solved the issue

#!/bin/bash

date1=$(date --date 'now' +%s) #date since epoch in seconds at the start of script
somecommand
date2=$(date --date 'now' +%s) #date since epoch in seconds at the end of script
difference=$(echo "$((date2-$date1))") # difference between two values
date3=$(echo "scale=2 ; $difference/3600" | bc) # difference/3600 = seconds in hours
echo SCRIPT TOOK $date3 HRS TO COMPLETE # 3rd variable for a pretty output.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

How do I return JSON without using a template in Django?

In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.

However, you can have HTML that is rendered from a template withing your JSON response.

html = render_to_string("some.html", some_dictionary)
serialized_data = simplejson.dumps({"html": html})
return HttpResponse(serialized_data, mimetype="application/json")

What is the purpose of a self executing function in javascript?

Self executing function are used to manage the scope of a Variable.

The scope of a variable is the region of your program in which it is defined.

A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.

As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.

var globalvar = "globalvar"; // this var can be accessed anywhere within the script

function scope() {
    alert(globalvar);
    var localvar = "localvar"; //can only be accessed within the function scope
}

scope(); 

So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

Could you explain STA and MTA?

Each EXE which hosts COM or OLE controls defines it's apartment state. The apartment state is by default STA (and for most programs should be STA).

STA - All OLE controls by necessity must live in a STA. STA means that your COM-object must be always manipulated on the UI thread and cannot be passed to other threads (much like any UI element in MFC). However, your program can still have many threads.

MTA - You can manipulate the COM object on any thread in your program.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

Compatibility Guide for JDK 8 says that in Java 8 the command line flag MaxPermSize has been removed. The reason is that the permanent generation was removed from the hotspot heap and was moved to native memory. So in order to remove this message edit MAVEN_OPTS Environment User Variable:

Java 7

MAVEN_OPTS -Xmx512m -XX:MaxPermSize=128m

Java 8

MAVEN_OPTS -Xmx512m

MySQL 'Order By' - sorting alphanumeric correctly

I hate this, but this will work

order by lpad(name, 10, 0)  <-- assuming maximum string length is 10
                            <-- you can adjust to a bigger length if you want to

Javascript onload not working

You are missing the ()

<body onload="imageRefreshBig();">

DateTime group by date and hour

SQL Server :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);

Oracle :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');

MySQL :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )

"The page has expired due to inactivity" - Laravel 5.5

In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false

'secure' => env('SESSION_SECURE_COOKIE', false),

How to get name of dataframe column in pyspark?

If you want the column names of your dataframe, you can use the pyspark.sql class. I'm not sure if the SDK supports explicitly indexing a DF by column name. I received this traceback:

>>> df.columns['High'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str

However, calling the columns method on your dataframe, which you have done, will return a list of column names:

df.columns will return ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']

If you want the column datatypes, you can call the dtypes method:

df.dtypes will return [('Date', 'timestamp'), ('Open', 'double'), ('High', 'double'), ('Low', 'double'), ('Close', 'double'), ('Volume', 'int'), ('Adj Close', 'double')]

If you want a particular column, you'll need to access it by index:

df.columns[2] will return 'High'

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

How can I see the entire HTTP request that's being sent by my Python application?

r = requests.get('https://api.github.com', auth=('user', 'pass'))

r is a response. It has a request attribute which has the information you need.

r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

r.request.headers gives the headers:

{'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

Then r.request.data has the body as a mapping. You can convert this with urllib.urlencode if they prefer:

import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

depending on the type of the response the .data-attribute may be missing and a .body-attribute be there instead.

java.io.FileNotFoundException: (Access is denied)

  1. check the rsp's reply
  2. check that you have permissions to read the file
  3. check whether the file is not locked by other application. It is relevant mostly if you are on windows. for example I think that you can get the exception if you are trying to read the file while it is opened in notepad

How to log PostgreSQL queries?

I was trying to set the log_statement in some postgres config file but in fact the file was not read by our postgres.

I confirmed that using the request :

select *
from pg_settings

[...]
log_statement   none # That was not the value i was expected for !!!

I use this way https://stackoverflow.com/a/41912295/2294168

command: postgres -c config_file=/etc/postgresql.conf

how to avoid extra blank page at end while printing?

set display:none for all other elements which are not for prints. setting visibility:hidden will keep them hidden, but they all are still there and have taken space for them. empty page is for those hidden elements.

Display QImage with QtGui

Thanks All, I found how to do it, which is the same as Dave and Sergey:

I am using QT Creator:

In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")

In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:

void MainWindow::on_pushButton_clicked()
{
     QImage imageObject;
     imageObject.load(imagePath);
     ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));

     //OR use the other way by setting the Pixmap directly

     QPixmap pixmapObject(imagePath");
     ui->myLabel2->setPixmap(pixmapObject);
}

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

This is a likely a linker error. Add the -lm switch to specify that you want to link against the standard C math library (libm) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

What are some ways of accessing Microsoft SQL Server from Linux?

I was not confortable with the freetds solution, it's why i coded a class (command history, autocompletion on tables and fields, etc.)

http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html

Ubuntu: Using curl to download an image

For ones who got permission denied for saving operation, here is the command that worked for me:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png

Is there a way to get version from package.json in nodejs code?

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

How can I initialize an ArrayList with all zeroes in Java?

// apparently this is broken. Whoops for me!
java.util.Collections.fill(list,new Integer(0));

// this is better
Integer[] data = new Integer[60];
Arrays.fill(data,new Integer(0));
List<Integer> list = Arrays.asList(data);

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

Locate the nginx.conf file my nginx is actually using

All other answers are useful but they may not help you in case nginx is not on PATH so you're getting command not found when trying to run nginx:

I have nginx 1.2.1 on Debian 7 Wheezy, the nginx executable is not on PATH, so I needed to locate it first. It was already running, so using ps aux | grep nginx I have found out that it's located on /usr/sbin/nginx, therefore I needed to run /usr/sbin/nginx -t.

If you want to use a non-default configuration file (i.e. not /etc/nginx/nginx.conf), run it with the -c parameter: /usr/sbin/nginx -c <path-to-configuration> -t.

You may also need to run it as root, otherwise nginx may not have permissions to open for example logs, so the command would fail.

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

Split string with PowerShell and do something with each token

-split outputs an array, and you can save it to a variable like this:

$a = -split 'Once  upon    a     time'
$a[0]

Once

Another cute thing, you can have arrays on both sides of an assignment statement:

$a,$b,$c = -split 'Once  upon    a'
$c

a

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

What is the iOS 5.0 user agent string?

This site seems to keep a complete list that's still maintained

iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).

You do need to assemble the full user-agent string out of the information listed in the page's columns.

How to change the DataTable Column Name?

try this

"columns": [
{data: "id", name: "aaa", sortable: false},
{data: "userid", name: "userid", sortable: false},
{data: "group_id", name: "group_id", sortable: false},
{data: "group_name", name: "group_name", sortable: false},
{data: "group_member", name: "group_member"},
{data: "group_fee", name: "group_fee"},
{data: "dynamic_type", name: "dynamic_type"},
{data: "dynamic_id", name: "dynamic_id"},
{data: "content", name: "content", sortable: false},
{data: "images", name: "images", sortable: false},
{data: "money", name: "money"},
{data: "is_audit", name: "is_audit", sortable: false},
{data: "audited_at", name: "audited_at", sortable: false}

]

enter image description here

How to change fonts in matplotlib (python)?

Say you want Comic Sans for the title and Helvetica for the x label.

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()

Hibernate: How to fix "identifier of an instance altered from X to Y"?

This is an old question, but I'm going to add the fix for my particular issue (Spring Boot, JPA using Hibernate, SQL Server 2014) since it doesn't exactly match the other answers included here:

I had a foreign key, e.g. my_id = '12345', but the value in the referenced column was my_id = '12345 '. It had an extra space at the end which hibernate didn't like. I removed the space, fixed the part of my code that was allowing this extra space, and everything works fine.

What are Unwind segues for and how do you use them?

Something that I didn't see mentioned in the other answers here is how you deal with unwinding when you don't know where the initial segue originated, which to me is an even more important use case. For example, say you have a help view controller (H) that you display modally from two different view controllers (A and B):

A ? H
B ? H

How do you set up the unwind segue so that you go back to the correct view controller? The answer is that you declare an unwind action in A and B with the same name, e.g.:

// put in AViewController.swift and BViewController.swift
@IBAction func unwindFromHelp(sender: UIStoryboardSegue) {
    // empty
}

This way, the unwind will find whichever view controller (A or B) initiated the segue and go back to it.

In other words, think of the unwind action as describing where the segue is coming from, rather than where it is going to.

Case in Select Statement

The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.

http://msdn.microsoft.com/en-us/library/ms181765.aspx

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
  CASE 
     WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
     WHEN ListPrice < 50 THEN 'Under $50'
     WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
     WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
     ELSE 'Over $1000'
  END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.

How do I define the name of image built with docker-compose

As per docker-compose 1.6.0:

You can now specify both a build and an image key if you're using the new file format. docker-compose build will build the image and tag it with the name you've specified, while docker-compose pull will attempt to pull it.

So your docker-compose.yml would be

version: '2'
services:
  wildfly:
      build: /path/to/dir/Dockerfile
      image: wildfly_server
      ports:
       - 9990:9990
       - 80:8080

To update docker-compose

sudo pip install -U docker-compose==1.6.0

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

Changing selection in a select with the Chosen plugin

Sometimes you have to remove the current options in order to manipulate the selected options.

Here is an example how to set options:

<select id="mySelectId" class="chosen-select" multiple="multiple">
  <option value=""></option>
  <option value="Argentina">Argentina</option>
  <option value="Germany">Germany</option>
  <option value="Greece">Greece</option>
  <option value="Japan">Japan</option>
  <option value="Thailand">Thailand</option>
</select>

<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);

function activateChosen($container, param) {
    param = param || {};
    $container.find('.chosen-select:visible').chosen(param);
    $container.find('.chosen-select').trigger("chosen:updated");
}

function selectChosenOptions($select, values) {
    $select.val(null);                                  //delete current options
    $select.val(values);                                //add new options
    $select.trigger('chosen:updated');
}
</script>

JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

How to use global variable in node.js?

you can define it with using global or GLOBAL, nodejs supports both.

for e.g

global.underscore = require("underscore");

or

GLOBAL.underscore = require("underscore");

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

jQuery UI Slider (setting programmatically)

One part of @gaurav solution worked for jQuery 2.1.3 and JQuery UI 1.10.2 with multiple sliders. My project is using four range sliders to filter data with this filter.js plugin. Other solutions were resetting the slider handles back to their starting end points just fine, but apparently they were not firing an event that filter.js understood. So here's how I looped through the sliders:

$("yourSliderSelection").each (function () {
    var hs = $(this); 
    var options = $(this).slider('option');

    //reset the ui
    $(this).slider( 'values', [ options.min, options.max ] ); 

    //refresh/trigger event so that filter.js can reset handling the data
    hs.slider('option', 'slide').call(
        hs, 
        null, 
        {
            handle: $('.ui-slider-handle', hs),
            values: [options.min, options.max]
        }
    );

});

The hs.slider() code resets the data, but not the UI in my scenario. Hope this helps others.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

Using CSS in Laravel views?

That is not possible bro, Laravel assumes everything is in public folder.

So my suggestion is:

  1. Go to the public folder.
  2. Create a folder, preferably named css.
  3. Create the folder for the respective views to make things organized.
  4. Put the respective css inside of those folders, that would be easier for you.

Or

If you really insist to put css inside of views folder, you could try creating Symlink (you're mac so it's ok, but for windows, this will only work for Vista, Server 2008 or greater) from your css folder directory to the public folder and you can use {{HTML::style('your_view_folder/myStyle.css')}} inside of your view files, here's a code for your convenience, in the code you posted, put these before the return View::make():

$css_file = 'myStyle.css';
$folder_name = 'your_view_folder';
$view_path = app_path() . '/views/' . $folder_name . '/' . $css_file;
$public_css_path = public_path() . '/' . $folder_name;
if(file_exists($public_css_path)) exec('rm -rf ' . $public_css_path);
exec('mkdir ' . $public_css_path);
exec('ln -s ' . $view_path .' ' . $public_css_path . '/' . $css_file);

If you really want to try doing your idea, try this:

<link rel="stylesheet" href="<?php echo app_path() . 'views/your_view_folder/myStyle.css'?>" type="text/css">

But it won't work even if the file directory is correct because Laravel won't do that for security purposes, Laravel loves you that much.

download file using an ajax request

Decoding a filename from the header is a little bit more complex...

    var filename = "default.pdf";
    var disposition = req.getResponseHeader('Content-Disposition');

    if (disposition && disposition.indexOf('attachment') !== -1) 
    {
       var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
       var matches = filenameRegex.exec(disposition);

       if (matches != null && matches[1]) 
           filename = matches[1].replace(/['"]/g, '');
    }

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.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

In My Aws Windows I Solved it and steps are

  1. Open "C:\ProgramData\MySQL\MySQL Server 8.0"
  2. Open My.ini
  3. Find "[mysql]"
  4. After "no-beep=" Brake Line and insert "default-character-set=utf8"
  5. Find "[mysqld]"
  6. Insert "collation-server = utf8_unicode_ci"
  7. Insert "character-set-server = utf8"

example

...
# socket=MYSQL

port=3306

[mysql]
no-beep=
default-character-set=utf8
# default-character-set=

# SERVER SECTION
# ----------------------------------------------------------------------
# 
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.=
# 
# server_type=2
[mysqld]

collation-server = utf8_unicode_ci
character-set-server = utf8
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking=
# enable-named-pipe=
# shared-memory=
...

mysql screenshot

How to remove focus from input field in jQuery?

For all textbox :

$(':text').blur()

Get value from JToken that may not exist (best practices)

You can simply typecast, and it will do the conversion for you, e.g.

var with = (double?) jToken[key] ?? 100;

It will automatically return null if said key is not present in the object, so there's no need to test for it.

password-check directive in angularjs

I had the same problem when i was trying to build my own directive, and i fixed with this add

ctrl.$validate();

where ctrl is my ngModelController

this is my view

<input type="password" match="signupCtrl.registrationData.password" name="confirmPassword" class="form-control" placeholder="Confirm Password" data-ng-model="signupCtrl.registrationData.confirmPassword" required>
        <span ng-messages="registerForm.confirmPassword.$error">
            <span ng-message="match">The Password must match</span>
        </span>

this is my directive

(function () {
    'use strict';
    angular.module('matchDirective', [
        // Angular modules
        // Custom modules
        // 3rd Party Modules
    ]);
})(); 
(function () {
    'use strict';
    angular
        .module('matchDirective')
        .directive('match', match);
    match.$inject = ['$window'];

    function match($window) {
        // Usage:
        //     <element match="source"></element>
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'A',
            require: 'ngModel',
        };
        return directive;

        function link(scope, element, attrs, ctrl) {
            scope.$watch(attrs['match'], function (newVal, oldVal) {
                ctrl.$validators.match = function (modelValue, viewValue) {
                    if (newVal == modelValue) {
                        return true;
                    } else {
                        return false;
                    }
                }
                ctrl.$validate();
            });
        }
    }
})();

Completely removing phpMyAdmin

I had to run the following command:

sudo apt-get autoremove phpmyadmin

Then I cleared my cache and it worked!

How to modify existing, unpushed commit messages?

Amending the most recent commit message

git commit --amend

will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:

git commit --amend -m "New commit message"

…however, this can make multi-line commit messages or small corrections more cumbersome to enter.

Make sure you don't have any working copy changes staged before doing this or they will get committed too. (Unstaged changes will not get committed.)

Changing the message of a commit that you've already pushed to your remote branch

If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also need to force push the commit with:

git push <remote> <branch> --force
# Or
git push <remote> <branch> -f

Warning: force-pushing will overwrite the remote branch with the state of your local one. If there are commits on the remote branch that you don't have in your local branch, you will lose those commits.

Warning: be cautious about amending commits that you have already shared with other people. Amending commits essentially rewrites them to have different SHA IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.


Perform an interactive rebase

Another option is to use interactive rebase. This allows you to edit any message you want to update even if it's not the latest message.

In order to do a Git squash, follow these steps:

// n is the number of commits up to the last commit you want to be able to edit
git rebase -i HEAD~n

Once you squash your commits - choose the e/r for editing the message:

Enter image description here

Important note about interactive rebase

When you use git rebase -i HEAD~n there can be more than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .

Good tip:

If you have to do it for more than a single branch and you might face conflicts when amending the content, set up git rerere and let Git resolve those conflicts automatically for you.


Documentation

Git push/clone to new server

remote server> cd /home/ec2-user
remote server> git init --bare --shared  test
add ssh pub key to remote server
local> git remote add aws ssh://ec2-user@<hostorip>:/home/ec2-user/dev/test
local> git push aws master

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

ls command: how can I get a recursive full-path listing, one line per file?

ls -ld $(find .)

if you want to sort your output by modification time:

ls -ltd $(find .)

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.

Colouring plot by factor in R

The lattice library is another good option. Here I've added a legend on the right side and jittered the points because some of them overlapped.

xyplot(Sepal.Width ~ Sepal.Length, group=Species, data=iris, 
       auto.key=list(space="right"), 
       jitter.x=TRUE, jitter.y=TRUE)

example plot

Open Cygwin at a specific folder

To create a Windows shortcut that launches a Cygwin terminal in a directory of your own choosing, try the following:

  • Right-click on the Windows desktop, select 'New', and then select 'Shortcut'.

  • For location of the item, enter the following text, changing the mintty path as needed and substituting the name of the desired directory where indicated.

    C:\cygwin64\bin\mintty.exe /bin/sh -lc 'cd DESIRED-DIRECTORY; exec bash'
    

    For example, the OP would use the following text:

    C:\cygwin64\bin\mintty.exe /bin/sh -lc 'cd /cygdrive/c/Users/Tom/Desktop/; exec bash'
    
  • Click 'Next'.

  • Enter the desired name for the shortcut and click 'Finish'.

Multiple shortcuts can be placed on the desktop to open Cygwin terminals in various often-accessed directories.

Inspired by solution posted on How to open a Cygwin shell at a specific directory from Netbeans? at superuser.com.

Node.js - Find home directory in platform agnostic way

os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());

Inserting a tab character into text using C#

It can also be useful to use String.Format, e.g.

String.Format("{0}\t{1}", FirstName,Count);

How to do join on multiple criteria, returning all combinations of both criteria

SELECT  aa.*,
        bb.meal
FROM    table1 aa
        INNER JOIN table2 bb
            ON aa.tableseat = bb.tableseat AND
                aa.weddingtable = bb.weddingtable
        INNER JOIN
        (
            SELECT  a.tableSeat
            FROM    table1 a
                    INNER JOIN table2 b
                        ON a.tableseat = b.tableseat AND
                            a.weddingtable = b.weddingtable
            WHERE b.meal IN ('chicken', 'steak')
            GROUP by a.tableSeat
            HAVING COUNT(DISTINCT b.Meal) = 2
        ) c ON aa.tableseat = c.tableSeat

is it possible to update UIButton title/text programmatically?

I solved the problem just setting the title parameter for UIControlStateNormal, and it automatically works on the other states. The problem seems to be when you set another UIControlState.

[myButton setTitle: @"myTitle" forState: UIControlStateNormal];

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.