Programs & Examples On #Gnokii

git: How to ignore all present untracked files?

I came here trying to solve a slightly different problem. Maybe this will be useful to someone else:

I create a new branch feature-a. as part of this branch I create new directories and need to modify .gitignore to suppress some of them. This happens a lot when adding new tools to a project that create various cache folders. .serverless, .terraform, etc.

Before I'm ready to merge that back to master I have something else come up, so I checkout master again, but now git status picks up those suppressed folders again, since the .gitignore hasn't been merged yet.

The answer here is actually simple, though I had to find this blog to figure it out:

Just checkout the .gitignore file from feature-a branch

git checkout feature-a -- feature-a/.gitignore
git add .
git commit -m "update .gitignore from feature-a branch"

How to use a servlet filter in Java to change an incoming servlet request url?

You could use the ready to use Url Rewrite Filter with a rule like this one:

<rule>
  <from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
  <to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>

Check the Examples for more... examples.

What is the difference between XML and XSD?

XML versus XSD

XML defines the syntax of elements and attributes for structuring data in a well-formed document.

XSD (aka XML Schema), like DTD before, powers the eXtensibility in XML by enabling the user to define the vocabulary and grammar of the elements and attributes in a valid XML document.

failed to find target with hash string android-23

Open the Android SDK Manager and Update with latest.

Bootstrap 3 panel header with buttons wrong position

In this case you should add .clearfix at the end of container with floated elements.

<div class="panel-heading">
    <h4>Panel header</h4>
    <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
    </div>
    <span class="clearfix"></span>
</div>

http://www.bootply.com/NCXkOtIkD6

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Running Python in PowerShell?

The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.

The execution policy is saved in the registry, so you need to change it only once on each computer.

To change the execution policy, use the following procedure:

  1. Start Windows PowerShell with the "Run as administrator" option.

  2. At the command prompt, type:

    Set-ExecutionPolicy AllSigned

    -or-

    Set-ExecutionPolicy RemoteSigned

The change is effective immediately.

To run a script, type the full name and the full path to the script file.

For example, to run the Get-ServiceLog.ps1 script in the C:\Scripts directory, type:

C:\Scripts\Get-ServiceLog.ps1

And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py.

To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.

Postgresql: Scripting psql execution with password

Given the security concerns about using the PGPASSWORD environment variable, I think the best overall solution is as follows:

  1. Write your own temporary pgpass file with the password you want to use.
  2. Use the PGPASSFILE environment variable to tell psql to use that file.
  3. Remove the temporary pgpass file

There are a couple points of note here. Step 1 is there to avoid mucking with the user's ~/.pgpass file that might exist. You also must make sure that the file has permissions 0600 or less.

Some have suggested leveraging bash to shortcut this as follows:

PGPASSFILE=<(echo myserver:5432:mydb:jdoe:password) psql -h myserver -U jdoe -p 5432 mydb

This uses the <() syntax to avoid needing to write the data to an actual file. But it doesn't work because psql checks what file is being used and will throw an error like this:

WARNING: password file "/dev/fd/63" is not a plain file

jQuery dialog popup

You can check this link: http://jqueryui.com/dialog/

This code should work fine

$("#dialog").dialog();

Attach to a processes output for viewing

You can use reptyr:

sudo apt install reptyr
reptyr pid

CSS horizontal scroll

check this link here i change display:inline-block http://cssdesk.com/gUGBH

Wordpress plugin install: Could not create directory

If you have installed wordpress using apt, the config files are split in multiple directories. In that case you need to run:

sudo chown -R -h www-data:www-data /var/lib/wordpress/wp-content/
sudo chown -R -h www-data:www-data /usr/share/wordpress/wp-content/

The -h switch changes the permissions for symlinks as well, otherwise they are not removable by user www-data

How to start IIS Express Manually

From the links the others have posted, I'm not seeing an option. -- I just use powershell to kill it -- you can save this to a Stop-IisExpress.ps1 file:

get-process | where { $_.ProcessName -like "IISExpress" } | stop-process

There's no harm in it -- Visual Studio will just pop a new one up when it wants one.

Finding Key associated with max Value in a Java Map

I have two methods, using this méthod to get the key with the max value:

 public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();
        if(null != value && max == value) {
            maxEntry = entry;
        }
    }
    return maxEntry;
}

As an example gettin the Entry with the max value using the method:

  Map.Entry<String, Integer> maxEntry =  getMaxEntry(map);

Using Java 8 we can get an object containing the max value:

Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();      

System.out.println("maxEntry = " + maxEntry);

How to find Max Date in List<Object>?

troubleshooting-friendly style

You should not call .get() directly. Optional<>, that Stream::max returns, was designed to benefit from .orElse... inline handling.

If you are sure your arguments have their size of 2+:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));

If you support empty lists, then return some default value, for example:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElse(new Date(Long.MIN_VALUE));

CREDITS to: @JimmyGeers, @assylias from the accepted answer.

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

Creating a UIImage from a UIColor to use as a background image for UIButton

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

Exiting from python Command Line

This message is the __str__ attribute of exit

look at these examples :

1

>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit

2

>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

3

>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

How do I pick randomly from an array?

arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]

This will return a random element from array.

If You will use the line mentioned below

arr[1+rand(arr.count)]

then in some cases it will return 0 or nil value.

The line mentioned below

rand(number)

always return the value from 0 to number-1.

If we use

1+rand(number)

then it may return number and arr[number] contains no element.

Nested attributes unpermitted parameters

Today I came across this same issue, whilst working on rails 4, I was able to get it working by structuring my fields_for as:

<%= f.select :tag_ids, Tag.all.collect {|t| [t.name, t.id]}, {}, :multiple => true %>

Then in my controller I have my strong params as:

private
def post_params
    params.require(:post).permit(:id, :title, :content, :publish, tag_ids: [])
end

All works!

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In my specific case I seemed to have been missing the dependency

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.3.RELEASE</version>
 </dependency>

What are the differences between delegates and events?

Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx

Briefly, the take away from the article - Events are encapsulation over delegates.

Quote from article:

Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event? Three options:

  1. A public delegate variable

  2. A delegate variable backed by a property

  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

Option 1 is clearly horrible, for all the normal reasons we abhor public variables.

Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.

Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.

Config Error: This configuration section cannot be used at this path

Can You try this:

Go to application path where you're getting deny error, right click

Properties->Security tab

In that, change the permissions and check the checkbox read and write. Then it will work without any error hopefully.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

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

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

How can I introduce multiple conditions in LIKE operator?

I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.

This worked for me in Oracle 11g:

REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*'); 

Why is vertical-align: middle not working on my span or div?

here is a great article of how to vetical align.. I like the float way.

http://www.vanseodesign.com/css/vertical-centering/

The HTML:

<div id="main">
    <div id="floater"></div>
    <div id="inner">Content here</div>
</div>

And the corresponding style:

#main {
   height: 250px;
}

#floater {
   float: left;
   height: 50%;
   width: 100%;
   margin-bottom: -50px;
}

#inner {
   clear: both;
   height: 100px;
}

LINQ query to find if items in a list are contained in another list

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));

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

One of the problems that can cause this is when you forget to put the / character in the WebServlet annotation @WebServlet("/example") @WebServlet("example") I hope it works, it worked for me.

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

How does the stack work in assembly language?

Regarding whether the stack is implemented in the hardware, this Wikipedia article might help.

Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's Application Binary Interface (ABI).

That article and the others it links to might be useful to get a feel for stack usage in processors.

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

Yes you can solve this error by changing the port number of glassfish because the WAMP SERVER or ORACLE database software uses a port number 8080, so there is a conflict of port number.

1)open a path like C:\GlassFish_Server\glassfish\domains\domain1\config\domain.xml.

2)find out the 8080 port number with the help of ctrl+F. You will get the following code...

<network-listener protocol="http-listener-1" port="8080" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp">

3) Change that port number from 8080 to 9090 or 1234 or whatever you like..

4) Save it. Open a Netbeans IDE goto the glassfish server .

5) Right click on the server -> select refresh option.

6) to check the port no. which is given by u just right click on the server-> property.

7) Start the Glassfish server . Yehhh the error is gone...

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can try this:

NSLog(@"%@", NSStringFromCGPoint(cgPoint));

There are a number of functions provided by UIKit that convert the various CG structs into NSStrings. The reason it doesn't work is because %@ signifies an object. A CGPoint is a C struct (and so are CGRects and CGSizes).

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

We can use query instead of queryForObject, major difference between query and queryForObject is that query return list of Object(based on Row mapper return type) and that list can be empty if no data is received from database while queryForObject always expect only single object be fetched from db neither null nor multiple rows and in case if result is empty then queryForObject throws EmptyResultDataAccessException, I had written one code using query that will overcome the problem of EmptyResultDataAccessException in case of null result.

----------


public UserInfo getUserInfo(String username, String password) {
      String sql = "SELECT firstname, lastname,address,city FROM users WHERE id=? and pass=?";
      List<UserInfo> userInfoList = jdbcTemplate.query(sql, new Object[] { username, password },
              new RowMapper<UserInfo>() {
                  public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                      UserInfo user = new UserInfo();
                      user.setFirstName(rs.getString("firstname"));
                      user.setLastName(rs.getString("lastname"));
                      user.setAddress(rs.getString("address"));
                      user.setCity(rs.getString("city"));

                      return user;
                  }
              });

      if (userInfoList.isEmpty()) {
          return null;
      } else {
          return userInfoList.get(0);
      }
  }

Add Whatsapp function to website, like sms, tel

Check this link out Launching Your iPhone App Via Custom URL Scheme

and more on the whats up url scheme document

I did a quick mock up and tried it on my iphone with a link like this from a webpage and it opened the app on my iphone.

<a href="whatsapp://send?text=Hello%2C%20World!">whatsapp</a>

I could not try to send a message as I don't have a current Whatsapp account sorry.

Add user name using abid parameter

let's say your whatsapp username was username then it would be

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

once again sorry I can't test this. Also I have no idea what would happen if the username is the actual user of the current mobile device. eg. You try to whatsapp yourself.

Difference between adjustResize and adjustPan in android?

As doc says also keep in mind the correct value combination:

The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

Facebook API error 191

UPDATE:
To answer the API Error Code: 191
The redirect_uri should be equal (or relative) to the Site URL.
enter image description here

Tip: Use base URLs instead of full URLs pointing to specific pages.

NOT RECOMMENDED: For example, if you use www.mydomain.com/fb/test.html as your Site URL and having www.mydomain.com/fb/secondPage.html as redirect_uri this will give you the 191 error.

RECOMMENDED: So instead have your Site URL set to a base URL like: www.mydomain.com/ OR www.mydomain.com/fb/.


I went through the Facebook Python sample application today, and I was shocked it was stating clearly that you can use http://localhost:8080/ as Site URL if you are developing locally:

Configure the Site URL, and point it to your Web Server. If you're developing locally, you can use http://localhost:8080/

While I was sure you can't do that, based on my own experience (very old test though) it seems that you actually CAN test your Facebook application locally!

So I picked up an old application of mine and edited its name, Site URL and Canvas URL: Site URL: http://localhost:80/fblocal/

I downloaded the latest Facebook PHP-SDK and threw it in my xampp/htdocs/fblocal/ folder.

But I got the same error as yours! I noticed that XAMPP is doing an automatic redirection to http://localhost/fblocal/ so I changed the setting to simply http://localhost/fblocal/ and the error was gone BUT I had to remove the application (from privacy settings) and re-install my application and here are the results:
alt text

After that, asked for the publish_stream permission, and I was able to publish to my profile (using the PHP-SDK):

$user = $facebook->getUser();
if ($user) {
    try {
        $post = $facebook->api('/me/feed', 'post', array('message'=>'Hello World, from localhost!'));
    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}

Results: alt text

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

How do I use T-SQL's Case/When?

If logical test is against a single column then you could use something like

USE AdventureWorks2012;  
GO  
SELECT   ProductNumber, Category =  
      CASE ProductLine  
         WHEN 'R' THEN 'Road'  
         WHEN 'M' THEN 'Mountain'  
         WHEN 'T' THEN 'Touring'  
         WHEN 'S' THEN 'Other sale items'  
         ELSE 'Not for sale'  
      END,  
   Name  
FROM Production.Product  
ORDER BY ProductNumber;  
GO  

More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

How to kill a process in MacOS?

If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.

Solution:

$ sudo kill -9 PID

Okay, sure enough Mac OS/X does give an error message for this case:

$ kill -9 196
-bash: kill: (196) - Operation not permitted

So, if you're not getting an error message, you somehow aren't getting the right PID.

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

Why does a base64 encoded string have an = sign at the end

The equals sign (=) is used as padding in certain forms of base64 encoding. The Wikipedia article on base64 has all the details.

How can I test a change made to Jenkinsfile locally?

TL;DR

Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.

There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.

  1. Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
  2. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
  3. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

Examples

The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

(Windows) If you have already installed MySQL server

cd C:\Program Files\MySQL\MySQL Server X.X\bin mysqld --install

and still cannot connect, then the service did not start automatically. Just try

Start > Search "services"

and scroll down until you see "MySQLXX", where the XX represents the MySQL Server version. If the Status isn't "Started", then

Right Click > Start

If you are here you should be golden: enter image description here

How do I create a circle or square with just CSS - with a hollow center?

You can use special characters to make lots of shapes. Examples: http://jsfiddle.net/martlark/jWh2N/2/

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>hollow square</td>_x000D_
    <td>&#9633;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>solid circle</td>_x000D_
    <td>&bull;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>open circle</td>_x000D_
    <td>&#3664;</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

enter image description here

Many more can be found here: HTML Special Characters

How to emulate GPS location in the Android Emulator?

I use eclipse plug DDMS function to send GPS. enter image description here

Add column with constant value to pandas dataframe

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)

before

df
    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219

after

df
        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I got this error resolved by doing 2 things in chrome browser:

  1. Pressed Ctrl + Shift + Delete and cleared all browsing data from beginning.
  2. Go to Chrome's : Settings ->Advanced Settings -> Open proxy settings -> Internet Properties then Go to the Content window and click on the Clear SSL State Button.

This site has this information and other options as well : https://www.thesslstore.com/blog/fix-err-ssl-protocol-error/

What is the purpose of Order By 1 in SQL select statement?

This is useful when you use set based operators e.g. union

select cola
  from tablea
union
select colb
  from tableb
order by 1;

Changing the color of a clicked table row using jQuery

Create a css class that applies the row color, and use jQuery to toggle the class on/off:

CSS:

.selected {
    background-color: blue;
}

jQuery:

$('#data tr').on('click', function() {
    $(this).toggleClass('selected');
});

The first click will add the class (making the background color blue), and the next click will remove the class, reverting it to whatever it was before. Repeat!

In terms of the two CSS classes you already have, I would change the .nonhighlighted class to apply to all rows of the table by default, then toggle the .highlighted on and off:

<style type="text/css">

.highlighted {
    background: red;
}

#data tr {
    background: white;
}

</style>

$('#data tr').on('click', function() {
    $(this).toggleClass('highlighted');
});

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

The import javax.persistence cannot be resolved

My solution was to select the maven profiles I had defined in my pom.xml in which I had declared the hibernate dependencies.

CTRL + ALT + P in eclipse.

In my project I was experiencing this problem and many others because in my pom I have different profiles for supporting Glassfish 3, Glassfish 4 and also WildFly so I have differet versions of Hibernate per container as well as different Java compilation targets and so on. Selecting the active maven profiles resolved my issue.

How can I easily add storage to a VirtualBox machine with XP installed?

These steps worked for me to increase the space on my windows VM:

  1. Clone the current VM and select "Full Clone" when prompted:

enter image description here

  1. Resize the VDI:

    VBoxManage modifyhd Cloned.vdi --resize 45000

  2. Run your cloned VM, go to Disk Management and extend the volume.

Intercept a form submit in JavaScript and prevent normal submission

<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>
</form>

In JS:

function processForm(e) {
    if (e.preventDefault) e.preventDefault();

    /* do what you want with the form */

    // You must return false to prevent the default form behavior
    return false;
}

var form = document.getElementById('my-form');
if (form.attachEvent) {
    form.attachEvent("submit", processForm);
} else {
    form.addEventListener("submit", processForm);
}

Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.

Edit2: Updated my example to include preventDefault()

Convert int to a bit array in .NET

    public static bool[] Convert(int[] input, int length)
    {
        var ret = new bool[length];
        var siz = sizeof(int) * 8;
        var pow = 0;
        var cur = 0;

        for (var a = 0; a < input.Length && cur < length; ++a)
        {
            var inp = input[a];

            pow = 1;

            if (inp > 0)
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) == pow;

                    pow *= 2;
                }
            }
            else
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) != pow;

                    pow *= 2;
                }
            }
        }

        return ret;
    }

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Determine the size of an InputStream

When explicitly dealing with a ByteArrayInputStream then contrary to some of the comments on this page you can use the .available() function to get the size. Just have to do it before you start reading from it.

From the JavaDocs:

Returns the number of remaining bytes that can be read (or skipped over) from this input stream. The value returned is count - pos, which is the number of bytes remaining to be read from the input buffer.

https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

How to break/exit from a each() function in JQuery?

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});

PL/SQL print out ref cursor returned by a stored procedure

If you want to print all the columns in your select clause you can go with the autoprint command.

CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
  OPEN v_refcur FOR 'select * from dummy_table';
END;

SET autoprint on;

--calling the procedure
VAR vcur refcursor;
DECLARE 
BEGIN
  sps_detail_dtest(vrefcur=>:vcur);
END;

Hope this gives you an alternate solution

Safest way to get last record ID from a table

SELECT LAST(row_name) FROM table_name

Visual Studio: Relative Assembly References Paths

In VS 2017 it is automatic. So just Add Reference as usually.

Note that in Reference Properties absolute path is shown, but in .vbproj/.csproj relative is used.

<Reference Include="NETnetworkmanager">
      <HintPath>..\..\libs\NETnetworkmanager.dll</HintPath>
      <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>

How to get UTF-8 working in Java webapps?

Answering myself as the FAQ of this site encourages it. This works for me:

Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.

To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:

Configuring Tomcat's server.xml

It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:

<Connector port="8080" maxHttpHeaderSize="8192"
 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
 enableLookups="false" redirectPort="8443" acceptCount="100"
 connectionTimeout="20000" disableUploadTimeout="true" 
 compression="on" 
 compressionMinSize="128" 
 noCompressionUserAgents="gozilla, traviata" 
 compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
 URIEncoding="UTF-8"
/>

The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded. As a result, when the user writes the following to the address bar of the browser:

 https://localhost:8443/ID/Users?action=search&name=*?*

the character ? is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6.

POST request are not affected by this.

CharsetFilter

Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:

package fi.foo.filters;

import javax.servlet.*;
import java.io.IOException;

public class CharsetFilter implements Filter {

    private String encoding;

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("requestEncoding");
        if (encoding == null) encoding = "UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
            throws IOException, ServletException {
        // Respect the client-specified character encoding
        // (see HTTP specification section 3.4.1)
        if (null == request.getCharacterEncoding()) {
            request.setCharacterEncoding(encoding);
        }

        // Set the default response content type and encoding
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        next.doFilter(request, response);
    }

    public void destroy() {
    }
}

This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.

The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.

This filter has to be added to the web.xml or the deployment descriptor of the webapp:

 <!--CharsetFilter start--> 

  <filter>
    <filter-name>CharsetFilter</filter-name>
    <filter-class>fi.foo.filters.CharsetFilter</filter-class>
      <init-param>
        <param-name>requestEncoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
  </filter>

  <filter-mapping>
    <filter-name>CharsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

The instructions for making this filter are found at the tomcat wiki (http://wiki.apache.org/tomcat/Tomcat/UTF-8)

JSP page encoding

In your web.xml, add the following:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:

 <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

If some kind of a layout with different JSP-fragments is used, then this is needed in all of them.

HTML-meta tags

JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding. Then it's time to tell the browser in which encoding the html page is:

This is done with the following at the top of each xhtml page produced by the webapp:

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
   <head>
   <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
   ...

JDBC-connection

When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows:

      <Resource name="jdbc/AppDB" 
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="20" maxIdle="10" maxWait="10000"
        username="foo"
        password="bar"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/      ID_development?useEncoding=true&amp;characterEncoding=UTF-8"
    />

MySQL database and tables

The used database must use UTF-8 encoding. This is achieved by creating the database with the following:

   CREATE DATABASE `ID_development` 
   /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;

Then, all of the tables need to be in UTF-8 also:

   CREATE TABLE  `Users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `name` varchar(30) collate utf8_swedish_ci default NULL
    PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;

The key part being CHARSET=utf8.

MySQL server configuration

MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file. In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.

   [client]
   port=3306
   default-character-set=utf8

   [mysql]
   default-character-set=utf8

Mysql procedures and functions

These also need to have the character set defined. For example:

   DELIMITER $$

   DROP FUNCTION IF EXISTS `pathToNode` $$
   CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
   READS SQL DATA
   BEGIN

    DECLARE path VARCHAR(255) CHARACTER SET utf8;

   SET path = NULL;

   ...

   RETURN path;

   END $$

   DELIMITER ;

GET requests: latin1 and UTF-8

If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:

   https://localhost:8443/ID/Users?action=search&name=Petteri
   https://localhost:8443/ID/Users?action=search&name=?

Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.

The Cyrillic character ? is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6.

If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6.

The end result is that all users with name "Petteri" are found and also all users with the name "?" are found.

But what about äåö?

HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following

    https://localhost:8443/ID/Users?action=search&name=*Päivi*

in to the encoded version

    https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*

In latin1 the character ä is encoded as %E4. Even though the page/request/everything is defined to use UTF-8. The UTF-8 encoded version of ä is %C3%A4

The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8

Stuff to read

A very big thank you for the writers of the following for giving the answers for my problem:

  • http://tagunov.tripod.com/i18n/i18n.html
  • http://wiki.apache.org/tomcat/Tomcat/UTF-8
  • http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
  • http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
  • http://jeppesn.dk/utf-8.html
  • http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
  • http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
  • http://www.utf8-chartable.de/

Important Note

supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY column type or use the utf8mb4 character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8 character set in MySQL won't work 100% of the time.

Tomcat with Apache

One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:

  1. Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
  2. Goto your apache folder i.e. /etc/httpd/conf and add AddDefaultCharset utf-8 in httpd.conf file. Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.

Determine if running on a rooted device

Based on some of the answers here, I think this is a nice solution:

    @JvmStatic
    fun isProbablyRooted(): Boolean {
        return try {
            findBinary("su")
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun findBinary(binaryName: String): Boolean {
        val paths = System.getenv("PATH")
        if (!paths.isNullOrBlank()) {
            val systemPlaces: List<String> = paths.split(":")
            return systemPlaces.firstOrNull { File(it, binaryName).exists() } != null
        }
        val places = arrayOf("/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/",
                "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/")
        return places.firstOrNull { File(it, binaryName).exists() } != null
    }

You can also add a check if some popular root-related apps are installed (like of Magisk Manager, which has package-name "com.topjohnwu.magisk"), but just like all solutions here, it's just a guess.

Java: Replace all ' in a string with \'

Use replace()

 s = s.replace("'", "\\'"); 

output:

You\'ll be totally awesome, I\'m really terrible

Multiple SQL joins

You can use something like this :

SELECT
    Books.BookTitle,
    Books.Edition,
    Books.Year,
    Books.Pages,
    Books.Rating,
    Categories.Category,
    Publishers.Publisher,
    Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.

Java Runtime.getRuntime(): getting output from executing a command line program

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

Unable to get spring boot to automatically create database schema

I had same problem and solved it with only this add:

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

Chrome refuses to execute an AJAX script due to wrong MIME type

FYI, I've got the same error from Chrome console. I thought my AJAX function causing it, but I uncommented my minified script from /javascripts/ajax-vanilla.min.js to /javascripts/ajax-vanilla.js. But in reality the source file was at /javascripts/src/ajax-vanilla.js. So in Chrome you getting bad MIME type error even if the file cannot be found. In this case, the error message is described as text/plain bad MIME type.

Show div on scrollDown after 800px

SCROLLBARS & $(window).scrollTop()

What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.

If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop() will not work.

It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.

If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here

Live long and program, CollyG.

initialize a numpy array

numpy.fromiter() is what you are looking for:

big_array = numpy.fromiter(xrange(5), dtype="int")

It also works with generator expressions, e.g.:

big_array = numpy.fromiter( (i*(i+1)/2 for i in xrange(5)), dtype="int" )

If you know the length of the array in advance, you can specify it with an optional 'count' argument.

Swift: Testing optionals for nil

To add to the other answers, instead of assigning to a differently named variable inside of an if condition:

var a: Int? = 5

if let b = a {
   // do something
}

you can reuse the same variable name like this:

var a: Int? = 5

if let a = a {
    // do something
}

This might help you avoid running out of creative variable names...

This takes advantage of variable shadowing that is supported in Swift.

How can I make Visual Studio wrap lines at 80 characters?

See also this answer in order to switch the mode conveniently.

Citation:

I use this feature often enough that I add a custom button to the command bar.

Click on the Add or Remove -> Customize
Click on the Commands tab
Select Edit|Advanced from the list
Find Toggle Word Wrap and drag it onto your bar

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

How to catch all exceptions in c# using try and catch?

Note that besides all other comments there is a small difference, which should be mentioned here for completeness!

With the empty catch clause you can catch non-CLSCompliant Exceptions when the assembly is marked with "RuntimeCompatibility(WrapNonExceptionThrows = false)" (which is true by default since CLR2). [1][2][3]

[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx

[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx

[3] Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Cannot open local file - Chrome: Not allowed to load local resource

This solution worked for me in PHP. It opens the PDF in the browser.

// $path is the path to the pdf file
public function showPDF($path) {
    if($path) {
        header("Content-type: application/pdf");
        header("Content-Disposition: inline; filename=filename.pdf");
        @readfile($path);
    }
}

Initializing a list to a known number of elements in Python

You could do this:

verts = list(xrange(1000))

That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list does a __len__ first to size the new list it should be fairly efficient.

Error: fix the version conflict (google-services plugin)

For fire base to install properly all the versions of the fire base compiles must be in same version so

compile 'com.google.firebase:firebase-messaging:11.0.4' 
compile 'com.google.android.gms:play-services-maps:11.0.4' 
compile 'com.google.android.gms:play-services-location:11.0.4'

this is the correct way to do it.

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

ASP.NET Web Application Message Box

There are several options to create a client-side messagebox in ASP.NET - see here, here and here for example...

Sorting list based on values from another list

You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()

output:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Drop rows with all zeros in pandas data frame

For me this code: df.loc[(df!=0).any(axis=0)] did not work. It returned the exact dataset.

Instead, I used df.loc[:, (df!=0).any(axis=0)] and dropped all the columns with 0 values in the dataset

The function .all() droped all the columns in which are any zero values in my dataset.

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

Why can't I set text to an Android TextView?

In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.

text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");

hope it will work.

Bootstrap Carousel image doesn't align properly

While vekozlov's answer will work in Bootstrap 3 to center your image, it will break when the carousel is scaled down: the image retains its size instead of scaling down with the carousel.

Instead, do this on the top-level carousel div:

<div id="my-carousel" class="carousel slide"
    style="max-width: 900px; margin: 0 auto">
    ...
</div>

This will center the entire carousel and prevent it from growing beyond the width of your images (i.e. 900 px or whatever you want to set it to). However, when the carousel is scaled down the images scale down with it.

You should put this styling info in your CSS/LESS file, of course.

Conda activate not working?

Have you tried with Anaconda command prompt or, cmd it works for me. Giving no error and activation is not working in PowerShell may be some path issue.

Handling ExecuteScalar() when no results are returned

First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:

command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
  string getUserName = userNameObj.ToString()
 ...

I'm not sure about the VB syntax but you get the idea.

How to convert a python numpy array to an RGB image with Opencv 2.4?

This is due to the fact that cv2 uses the type "uint8" from numpy. Therefore, you should define the type when creating the array.

Something like the following:

import numpy
import cv2

b = numpy.zeros([5,5,3], dtype=numpy.uint8)
b[:,:,0] = numpy.ones([5,5])*64
b[:,:,1] = numpy.ones([5,5])*128
b[:,:,2] = numpy.ones([5,5])*192

How to check if a "lateinit" variable has been initialized?

kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized

Bytecode says...blah blah..

public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;

`L0
LINENUMBER 11 L0
ALOAD 0
GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
DUP
IFNONNULL L1
LDC "clientKeypair"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
    L1
ARETURN

L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1

Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object. Above bytecode explained here Solution Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.

http://chromedriver.storage.googleapis.com/index.html?path=2.24/

It is working for me in Win7 64 bit.

How to install SimpleJson Package for Python

Download the source code, unzip it to and directory, and execute python setup.py install.

Remove legend ggplot 2.2

As the question and user3490026's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the OP's question.

One of the things that ggplot2 does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear) appears twice, once for linetype and once for fill, resulting in a combined legend. By contrast, gear has its own legend entry as it is not treated as the same as factor(gear). The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.

# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) + 
theme_bw() 

enter image description here

Remove all legends: @user3490026

p + theme(legend.position = "none")

Remove all legends: @duhaime

p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)

Turn off legends: @Tjebo

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) + 
theme_bw() 

Remove fill so that linetype becomes visible

p + guides(fill = FALSE)

Same as above via the scale_fill_ function:

p + scale_fill_discrete(guide = FALSE)

And now one possible answer to the OP's request

"to keep the legend of one layer (smooth) and remove the legend of the other (point)"

Turn some on some off ad-hoc post-hoc

p + guides(fill = guide_legend(override.aes = list(color = NA)), 
           color = FALSE, 
           shape = FALSE)  

enter image description here

How to find the location of the Scheduled Tasks folder

I want to extend @Jan answer:

It's seems, that Task Scheduler 1.0 API uses C:\Windows\Tasks folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API uses C:\Windows\System32\Tasks to create and enumerate tasks (this example).

It's also seems, that windows console utility schtasks and GUI utility taskschd.msc uses Task Scheduler 2.0 API.

P.S. I found, that if task placed in C:\Windows\Tasks and have not set AccountInformation, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation (even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON - task will be displayed in all standard applications.

Solution found here

Passing a variable to a powershell script via command line

Using param to name the parameters allows you to ignore the order of the parameters:

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

Convert character to ASCII numeric value in java

Or you can use Stream API for 1 character or a String starting in Java 1.8:

public class ASCIIConversion {
    public static void main(String[] args) {
        String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
        text.chars()
                .forEach(System.out::println);
    }
}

How to format a phone number with jQuery

 $(".phoneString").text(function(i, text) {
            text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
            return text;
        });

Output :-(123) 657-8963

What is an AssertionError? In which case should I throw it from my own code?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

assert(x>10);

Output:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

How to open every file in a folder

I was looking for this answer:

import os,glob
folder_path = '/some/path/to/file'
for filename in glob.glob(os.path.join(folder_path, '*.htm')):
  with open(filename, 'r') as f:
    text = f.read()
    print (filename)
    print (len(text))

you can choose as well '*.txt' or other ends of your filename

What's is the difference between include and extend in use case diagram?

Also beware of the UML version : it's been a long time now that << uses >> and << includes >> have been replaced by << include >>, and << extends >> by << extend >> AND generalization.
For me that's often the misleading point : as an example the Stephanie's post and link is about an old version :

When paying for an item, you may choose to pay on delivery, pay using paypal or pay by card. These are all alternatives to the "pay for item" use case. I may choose any of these options depending on my preference.

In fact there is no really alternative to "pay for item" ! In nowadays UML, "pay on delivery" is an extend, and "pay using paypal"/"pay by card" are specializations.

Create a simple HTTP server with Java?

Java 6 has a default embedded http server.

Check the thread here

By the way, if you plan to have a rest web service, here is a simple example using jersey.

Netbeans installation doesn't find JDK

I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"

Hope it helps

How to break out of nested loops?

One way is to put all the nested loops into a function and return from the inner most loop incase of a need to break out of all loops.

function() 
{    
  for(int i=0; i<1000; i++)
  {
   for(int j=0; j<1000;j++)
   {
      if (condition)
        return;
   }
  }    
}

mysql select from n last rows

Last 5 rows retrieve in mysql

This query working perfectly

SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC

or

select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.

Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().

Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath)
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

How do I print the content of httprequest request?

If you want the content string and this string does not have parameters you can use

    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null){
        System.out.println(line);
    }

How to resolve "Server Error in '/' Application" error?

I had this error with VS 2015, in my case going to the project properties page, Web tab, and clicking on Create Virtual Directory button in Servers section solved it

How to prevent auto-closing of console after the execution of batch file

If you are using Maven and you want to skip the typing and prevent the console from close to see the result you need to use the CALL command in the script, besides just the 'mvn clean install'.

Like this will close the console

ECHO This is the wrong exemple
mvn clean install
pause

Like this the console will stay open

ECHO This is the right exemple
CALL mvn clean install
pause

If you dont use the CALL command neither of the pasts exemples will work. Because for some reason the default behaviour of cmd when calling another batch file (which mvn is in this case) is to essentially replace the current process with it, unlike calling an .exe

Font Awesome not working, icons showing as squares

This may help, check to ensure that you haven't inadvertently changed the font family on the icon. If you have changed the .fa item's font family from: FontAwesome the icon will not show. It's always something silly and small.

Hope that helps someone.

C compile error: Id returned 1 exit status

My solution is to try to open another file that you can successfully run that you do at another PC, open that file and run it, after that copy that file and make a new file. Try to run it.

convert ArrayList<MyCustomClass> to JSONArray

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

Get the distance between two geo points

An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).

This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.

The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.

// Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
int R = 6371; // km
double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
double y = (lat2 - lat1);
double distance = Math.sqrt(x * x + y * y) * R;

You can optimize this further by either:

  1. Removing the square root if you simply compare the distance to another (in that case compare both squared distance);
  2. Factoring-out the cosine if you compute the distance from one master point to many others (in that case you do the equirectangular projection centered on the master point, so you can compute the cosine once for all comparisons).

For more info see: http://www.movable-type.co.uk/scripts/latlong.html

There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801

MSDN Standard Date and Time Format Strings

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

MySQL update CASE WHEN/THEN/ELSE

That's because you missed ELSE.

"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

Android - Start service on boot

Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission:

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

CSS: create white glow around image

late to the party here; however just wanted to add a bit of extra fun..

box-shadow: 0px 0px 5px rgba(0,0,0,.3);
padding:7px;

will give you a nice looking padded in image. The padding will give you a simulated white border (or whatever border you have set). the rgba is just allowing you to do an opicity on the particular color; 0,0,0 being black. You could just as easily use any other RGB color.

Hope this helps someone!

git status (nothing to commit, working directory clean), however with changes commited

git status output tells you three things by default:

  1. which branch you are on
  2. What is the status of your local branch in relation to the remote branch
  3. If you have any uncommitted files

When you did git commit , it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.

If you find the output of git status verbose and difficult to comprehend, try using git status -sb this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:

master...origin/master [ahead 1]

git status is pretty useful, in the workflow you described do a git status -sb: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.

Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution

querySelector, wildcard element match?

I just wrote this short script; seems to work.

/**
 * Find all the elements with a tagName that matches.
 * @param {RegExp} regEx  regular expression to match against tagName
 * @returns {Array}       elements in the DOM that match
 */
function getAllTagMatches(regEx) {
  return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) { 
    return el.tagName.match(regEx);
  });
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"

How to parse a CSV in a Bash script?

First prototype using plain old grep and cut:

grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"

If that's fast enough and gives the proper output, you're done.

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

Java default constructor

Hi. As per my knowledge let me clear the concept of default constructor:

The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

I read this information from the Java Tutorials.

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

MySQL: How to allow remote connection to mysql

I had to this challenge when working on a Java Project with MySQL server as the database.

Here's how I did it:

First, confirm that your MySQL server configuration to allow for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below to grant the root user remote access to the database named my_database:

USE my_database;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

Disable F5 and browser refresh using JavaScript

From the site Enrique posted:

window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
    }
}

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

[] extracts a list, [[]] extracts elements within the list

alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))

str(alist[[1]])
 chr [1:3] "a" "b" "c"

str(alist[1])
List of 1
 $ : chr [1:3] "a" "b" "c"

str(alist[[1]][1])
 chr "a"

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

How to access Anaconda command prompt in Windows 10 (64-bit)

To run Anaconda Prompt using icon, I made an icon and put

%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3 The file location would be different in each computer.

at icon -> right click -> Property -> Shortcut -> Target

I see %HOMEPATH% at icon -> right click -> Property -> Start in

OS: Windows 10, Library: Anaconda 10 (64 bit)

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

install python again:

brew install python

try it again:

sudo pip install scrapy

works for me, hope it can help

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

How to remove the character at a given index from a string in C?

This might be one of the fastest ones, if you pass the index:

void removeChar(char *str, unsigned int index) {
    char *src;
    for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
    *src = '\0';
}

How to handle back button in activity

You can handle it like this:

for API level 5 and greater

@Override
public void onBackPressed() {
    // your code.
}

older than API 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Sublime Text 3, convert spaces to tabs

At the bottom of the Sublime window, you'll see something representing your tab/space setting.

You'll then get a dropdown with a bunch of options. The options you care about are:

  • Convert Indentation to Spaces
  • Convert Indentation to Tabs

Apply your desired setting to the entire document.

Hope this helps.

How to dynamic new Anonymous Class?

Of cause it's possible to create dynamic classes using very cool ExpandoObject class. But recently I worked on project and faced that Expando Object is serealized in not the same format on xml as an simple Anonymous class, it was pity =( , that is why I decided to create my own class and share it with you. It's using reflection and dynamic directive , builds Assembly, Class and Instance truly dynamicly. You can add, remove and change properties that is included in your class on fly Here it is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

It is also very simple to use DynamicTypeBuilder, you just need put few lines like this:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

I hope that this code snippet help somebody =) Enjoy!

Visually managing MongoDB documents and collections

If you're able to run PHP scripts you can give PHP MongoDB Admin a try. It's a single PHP script that gives you basic management and searching functionality.

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

I had the same issue, if you enable Microsoft Scripting Runtime you should be good. You can do so under tools > references > and then check the box for Microsoft Scripting Runtime. This should solve your issue.

How do you reinstall an app's dependencies using npm?

The right way is to execute npm update. It's a really powerful command, it updates the missing packages and also checks if a newer version of package already installed can be used.

Read Intro to NPM to understand what you can do with npm.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Override intranet compatibility mode IE8

Michael Irigoyen is correct BUT it is a little more complicated...

if you are using the wonderful boilerplate by Paul Irish then you will have something like the following:-

<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

This will NOT work as expected and force in IE into compatibility mode in an Intranet environment if you have the "Display intranet sites in compatibility view" checked. You need to remove the conditional IE comments to prevent Intranet compatibility mode.

So the following code will work:

<!doctype html>
<html class="no-js" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Basically if you trigger conditional IE comments before the <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> statement then you will be forced into compatibility mode in an Intranet environment if you are running IE9 with the default settings.

UPDATE — ADDITIONAL INFO: But note that there is a trick that will make the HTML5 boilplate work:

Add an emtpy, conditional comment before the DOCTYPE. And note as well, that when you do that, then you can also add conditional comments around the X-UA-Compatible directive, making the page HTML5-valid as well. So for instance:

<!--[if HTML5]><![endif]-->
<!doctype html>
<!--[if the boilerplate conditionals goes here<![endif]-->
<head>
<!--[if !HTML5]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->

A blog post that was inspired by the first part of this answer, has more detail. And by the way: As mentioned in that blog post, one can also replace the conditional comment before the DOCTYPE with a semi conditional comment with no condition: <!--[]-->. Thus, like so:

<!--[]-->
<!doctype html>
<!--[if the boilerplate conditionals goes here<![endif]-->
<head>
<!--[if !HTML5]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->

But note that the latter variant (<--[]--><!DOCTYPE html>) will, as explained e.g by this answer to another question, activate the well know problem that it — for legacy IE versions without support for the X-UA-Compatioble (read: for IE7 and IE6) — bring the browser into into quirks-mode.

How to print formatted BigDecimal values?

BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I just had the same error. I have two tables with a parent child relationship, but I configured a "on delete cascade" on the foreign key column in the table definition of the child table. So when I manually delete the parent row (via SQL) in the database it will automatically delete the child rows.

However this did not work in EF, the error described in this thread showed up. The reason for this was, that in my entity data model (edmx file) the properties of the association between the parent and the child table were not correct. The End1 OnDelete option was configured to be none ("End1" in my model is the end which has a multiplicity of 1).

I manually changed the End1 OnDelete option to Cascade and than it worked. I do not know why EF is not able to pick this up, when I update the model from the database (I have a database first model).

For completeness, this is how my code to delete looks like:

   public void Delete(int id)
    {
        MyType myObject = _context.MyTypes.Find(id);

        _context.MyTypes.Remove(myObject);
        _context.SaveChanges(); 
   }    

If I hadn´t a cascade delete defined, I would have to delete the child rows manually before deleting the parent row.

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Typescript solution based off of @krzysztof-dabrowski 's answer

export interface HoursMinutes {
  hours: number;
  minutes: number;
}
export function convert12to24(time12h: string): HoursMinutes {
  const [time, modifier] = time12h.split(' ');
  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (minutes.length === 1) {
    minutes = `0${minutes}`;
  }

  if (modifier.toUpperCase() === 'PM') {
    hours = parseInt(hours, 10) + 12 + '';
  }

  return {
    hours: parseInt(hours, 10),
    minutes: parseInt(minutes, 10)
  };
}

Formatting a float to 2 decimal places

You can pass the format in to the ToString method, e.g.:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

Standard Number Format Strings

Is < faster than <=?

You could say that line is correct in most scripting languages, since the extra character results in slightly slower code processing. However, as the top answer pointed out, it should have no effect in C++, and anything being done with a scripting language probably isn't that concerned about optimization.

Filter items which array contains any of given values

Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz

You'll probably want a Bool Query (or more likely Filter alongside another query), with a should clause.

The bool query has three main properties: must, should, and must_not. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should clause may specify a list filters, a match against any one of which will return the document you're looking for.

From the docs:

In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

Here's an example of what that Bool query might look like in isolation:

{
  "bool": {
    "should": [
      { "term": { "tag": "c" }},
      { "term": { "tag": "d" }}
    ]
  }
}

And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "bool": {
        "should": [
          { "term": { "tag": "c" }},
          { "term": { "tag": "d" }}
        ]
      }
    }
  }
}

Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.

It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.

Elasticsearch blog: All About Elasticsearch Filter Bitsets

Update with a refactored query...

Now, with all of that out of the way, the terms query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool + should using the minimum_should_match options, and overall is a bit more terse.

Here's that last query refactored a bit:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tag": [ "c", "d" ],
        "minimum_should_match": 1
      }
    }
  }
}

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
    jQuery.ajax({
        type: 'POST',
        url:"functions.php",
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {
             $("#show1").html(returnval);
             $('#show1').show();
         }
    });
}

Just print the file details and check. You will get Output. If error let me know.

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

How to convert ASCII code (0-255) to its corresponding character?

upper answer only near solving the Problem. heres your answer:

Integer.decode(Character.toString(char c));

How do I load an url in iframe with Jquery

$("#frame").click(function () { 
    this.src="http://www.google.com/";
});

Sometimes plain JavaScript is even cooler and faster than jQuery ;-)

How can I specify the schema to run an sql file against in the Postgresql command line

I'm using something like this and works very well:* :-)

(echo "set schema 'acme';" ; \
  cat ~/git/soluvas-framework/schedule/src/main/resources/org/soluvas/schedule/tables_postgres.sql) \
  | psql -Upostgres -hlocalhost quikdo_app_dev 

Note: Linux/Mac/Bash only, though probably there's a way to do that in Windows/PowerShell too.

failed to push some refs to [email protected]

It is probably due to an Outdated yarn.lock file

Just run the following commands

yarn install
git add yarn.lock
git commit -m "Updated Yarn lockfile"
git push heroku master

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

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

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

No restricted globals

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

import { useLocation } from 'react-router-dom';

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

What is the difference between function and procedure in PL/SQL?

The following are the major differences between procedure and function,

  1. Procedure is named PL/SQL block which performs one or more tasks. where function is named PL/SQL block which performs a specific action.
  2. Procedure may or may not return value where as function should return one value.
  3. we can call functions in select statement where as procedure we cant.

How to configure encoding in Maven?

In my case I was using the maven-dependency-plugin so in order to resolve the issue I had to add the following property:

  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

See Apache Maven Resources Plugin / Specifying a character encoding scheme

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I just wasted 3 hours with this problem until I managed to make it work. I had this error in the Eclipse Terminal when issuing a mvn compile command:

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

So I read here that I have to make a new system variable called JAVA_HOME and make it point towards the jdk installation folder. However this generated another error:

Source option 1.5 is no longer supported. Use 1.6 or later

Couldn't find a fix for this one so...

So the fix to make it all go away is install Java SE Development Kit 8! I was using 9 thinking that if it's the latest it must be better...

Anyway...

  1. Uninstall all java versions from your computer
  2. Install JDK8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

  3. Then define the JAVA_HOME system environmental value - tutorial here: https://docs.oracle.com/cd/E19509-01/820-3208/inst_cli_jdk_javahome_t/

  4. Restart Eclipse and enjoy! (at least that's what I did)

Hoping this spares some poor wanderer of some trouble.

Trying to make bootstrap modal wider

Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever

This is the default modal css for 768px and up:

@media (min-width: 768px) {
  .modal-dialog {
    width: 600px;
    margin: 30px auto;
  }
  ...
}

They have a class modal-lg for larger widths

@media (min-width: 992px) {
  .modal-lg {
    width: 900px;
  }
}

If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.

@media (min-width: 768px) {
  .modal-xl {
    width: 90%;
   max-width:1200px;
  }
}

HTML

<div class="modal-dialog modal-xl">

Demo: http://jsbin.com/yefas/1

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

Read file As String

this is working for me

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;

}

Map enum in JPA with fixed values?

The best approach would be to map a unique ID to each enum type, thus avoiding the pitfalls of ORDINAL and STRING. See this post which outlines 5 ways you can map an enum.

Taken from the link above:

1&2. Using @Enumerated

There are currently 2 ways you can map enums within your JPA entities using the @Enumerated annotation. Unfortunately both EnumType.STRING and EnumType.ORDINAL have their limitations.

If you use EnumType.String then renaming one of your enum types will cause your enum value to be out of sync with the values saved in the database. If you use EnumType.ORDINAL then deleting or reordering the types within your enum will cause the values saved in the database to map to the wrong enums types.

Both of these options are fragile. If the enum is modified without performing a database migration, you could jeopodise the integrity of your data.

3. Lifecycle Callbacks

A possible solution would to use the JPA lifecycle call back annotations, @PrePersist and @PostLoad. This feels quite ugly as you will now have two variables in your entity. One mapping the value stored in the database, and the other, the actual enum.

4. Mapping unique ID to each enum type

The preferred solution is to map your enum to a fixed value, or ID, defined within the enum. Mapping to predefined, fixed value makes your code more robust. Any modification to the order of the enums types, or the refactoring of the names, will not cause any adverse effects.

5. Using Java EE7 @Convert

If you are using JPA 2.1 you have the option to use the new @Convert annotation. This requires the creation of a converter class, annotated with @Converter, inside which you would define what values are saved into the database for each enum type. Within your entity you would then annotate your enum with @Convert.

My preference: (Number 4)

The reason why I prefer to define my ID's within the enum as oppose to using a converter, is good encapsulation. Only the enum type should know of its ID, and only the entity should know about how it maps the enum to the database.

See the original post for the code example.

Changing website favicon dynamically

I use favico.js in my projects.

It allows to change the favicon to a range of predefined shapes and also custom ones.

Internally it uses canvas for rendering and base64 data URL for icon encoding.

The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

Android XML Percent Symbol

Try this one (right):

<string name="content" formatted="false">Great application %s  ?  %s  ?  %s \\n\\nGo to download this application %s</string>

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Get month name from Date

To get Date formatted as "dd-MMM-yyyy" using JavaScript use the below code

_x000D_
_x000D_
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ];

    const d = new Date();
    var dd = String(d.getDate()).padStart(2, '0');
    var mm = String(d.getMonth() + 1).padStart(2, '0');
    var yyyy = d.getFullYear();
    var fullDate = +dd +"-"+ monthNames[d.getMonth()] +"-"+ yyyy;
    document.write("The date is : "+ fullDate);
_x000D_
_x000D_
_x000D_

How to change the DataTable Column Name?

Use this

dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";

Convert string to float?

Using Float.parseFloat()?

class Test {
    public static void main(String[] args) {
        String s = "3.14";
        float f = Float.parseFloat(s);
        System.out.println(f);
    }
}

Eclipse: Set maximum line length for auto formatting?

Comments have their own line length setting at the bottom of the setting page java->code style->formatter-> Edit... ->comments

Javascript return number of days,hours,minutes,seconds between two dates

Here's my take:

timeSince(123456) => "1 day, 10 hours, 17 minutes, 36 seconds"

And the code:

function timeSince(date, longText) {
    let seconds = null;
    let leadingText = null;

    if (date instanceof Date) {
        seconds = Math.floor((new Date() - date) / 1000);
        if (seconds < 0) {
            leadingText = " from now";
        } else {
            leadingText = " ago";
        }
        seconds = Math.abs(seconds);
    } else {
        seconds = date;
        leadingText = "";
    }

    const intervals = [
        [31536000, "year"  ],
        [ 2592000, "month" ],
        [   86400, "day"   ],
        [    3600, "hour"  ],
        [      60, "minute"],
        [       1, "second"],
    ];

    let interval = seconds;
    let intervalStrings = [];
    for (let i = 0; i < intervals.length; i++) {
        let divResult = Math.floor(interval / intervals[i][0]);
        if (divResult > 0) {
            intervalStrings.push(divResult + " " + intervals[i][1] + ((divResult > 1) ? "s" : ""));
            interval = interval % intervals[i][0];
            if (!longText) {
                break;
            }
        }
    }
    let intStr = intervalStrings.join(", ");

    return intStr + leadingText;
}

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Split a string by another string in C#

This is also easy:

string data = "THExxQUICKxxBROWNxxFOX";
string[] arr = data.Split("xx".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

How to pre-populate the sms body text via an html link

Every OS version has a different way of doing it. Take a look at the sms-link library

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

Java constant examples (Create a java file having only constants)

This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:

Enum:

public enum Planck {
    REDUCED();
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
    public static final double PI = 3.14159;
    public final double REDUCED_PLANCK_CONSTANT;

    Planck() {
        this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
    }

    public double getValue() {
        return REDUCED_PLANCK_CONSTANT;
    }
}

Client class:

public class PlanckClient {

    public static void main(String[] args) {
        System.out.println(getReducedPlanckConstant());
        // or using Enum itself as below:
        System.out.println(Planck.REDUCED.getValue());
    }

    public static double getReducedPlanckConstant() {
        return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
    }

}

Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

You could use the query:

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, 
       NUMERIC_PRECISION, DATETIME_PRECISION, 
       IS_NULLABLE 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='TableName'

to get all the metadata you require except for the Pk information.

Python conversion from binary string to hexadecimal

Use python's binascii module

import binascii

binFile = open('somebinaryfile.exe','rb')
binaryData = binFile.read(8)

print binascii.hexlify(binaryData)

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

NoClassDefFoundError on Maven dependency

This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.

You can include dependent jars using plugin.

Add below snippet into your pom's plugins section

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

How to allow users to check for the latest app version from inside the app?

I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,

getFilesDir() vs Environment.getDataDirectory()

Try this

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()

Math functions in AngularJS bindings

While the accepted answer is right that you can inject Math to use it in angular, for this particular problem, the more conventional/angular way is the number filter:

<p>The percentage is {{(100*count/total)| number:0}}%</p>

You can read more about the number filter here: http://docs.angularjs.org/api/ng/filter/number