Programs & Examples On #Http status code 403

The 403 or "Forbidden" error message is a HTTP standard response code indicating that the request was legal and understood but the server refuses to respond to the request.

Nginx 403 error: directory index of [folder] is forbidden

  1. Check that index.html or index.php is not missing in the directory
  2. See the error log file which is location in /var/log/nginx and then open vim error.log

Emulate a 403 error page

I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:

  1. Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
  2. Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
  3. now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
  4. echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!

        <?php header('HTTP/1.0 403 Forbidden');
        $contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
        exit($contents);
    

Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

WAMP 403 Forbidden message on Windows 7

This configuration in httpd.conf work fine for me.

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1 ::1
</Directory>

Nginx 403 forbidden for all files

I dug myself into a slight variant on this problem by mistakenly running the setfacl command. I ran:

sudo setfacl -m user:nginx:r /home/foo/bar

I abandoned this route in favor of adding nginx to the foo group, but that custom ACL was foiling nginx's attempts to access the file. I cleared it by running:

sudo setfacl -b /home/foo/bar

And then nginx was able to access the files.

HTTP error 403 in Python 3 Web Scraping

"This is probably because of mod_security or some similar server security feature which blocks known

spider/bot

user agents (urllib uses something like python urllib/3.3.0, it's easily detected)" - as already mentioned by Stefano Sanfilippo

from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')

The web_byte is a byte object returned by the server and the content type present in webpage is mostly utf-8. Therefore you need to decode web_byte using decode method.

This solves complete problem while I was having trying to scrap from a website using PyCharm

P.S -> I use python 3.4

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

You did not need

Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted

the only thing what you need is...

Require all granted

...inside the directory section.

See Apache 2.4 upgrading side:

http://httpd.apache.org/docs/2.4/upgrading.html

403 Forbidden vs 401 Unauthorized HTTP responses

they are not logged in or do not belong to the proper user group

You have stated two different cases; each case should have a different response:

  1. If they are not logged in at all you should return 401 Unauthorized
  2. If they are logged in but don't belong to the proper user group, you should return 403 Forbidden

Note on the RFC based on comments received to this answer:

If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:

"The request requires user authentication."

If you're unauthenticated, 401 is the correct response. However if you're unauthorized, in the semantically correct sense, 403 is the correct response.

Error message "Forbidden You don't have permission to access / on this server"

I had the same issue, but due to the fact that I changed the path on apache to a folder outside var/www, I started running into problems.

I fixed it by creating a symlink in var/www/html > home/dev/project which seemed to do the trick, without having to change any permissions...

Apache VirtualHost 403 Forbidden

I just spent several hours on this stupid problem

First, change permissions using this in terminal

find htdocs -type f -exec chmod 664 {} + -o -type d -exec chmod 775 {} +

I don't know what the difference is between 664 and 775 I did both 775 like this Also htdocs needs the directory path for instance for me it was

/usr/local/apache2/htdocs 

find htdocs -type f -exec chmod 775 {} + -o -type d -exec chmod 775 {} +

This is the other dumb thing too

make sure that your image src link is your domain name for instance

src="http://www.fakedomain.com/images/photo.png"

Be sure to have

EnableSendfile off in httpd.conf file
EnableMMAP off in httpd.conf file

You edit those using pico in terminal

I also created a directory for images specifically so that when you type in the browser address bar domainname.com/images, you will get a list of photos which can be downloaded and need to be downloaded successfully to indicate image files that are working properly

<Directory /usr/local/apache2/htdocs/images>
AddType images/png .png
</Directory>

And those are the solutions I have tried, now I have functioning images... yay!!!

Onto the next problem(s)

MVC4 HTTP Error 403.14 - Forbidden

I have a bit different issue, on server 2012 somehow i forgot to enable asp.net 4.5 so if you have this issue, double check that you enable it.

how to write javascript code inside php

Just echo the javascript out inside the if function

 <form name="testForm" id="testForm"  method="POST"  >
     <input type="submit" name="btn" value="submit" autofocus  onclick="return true;"/>
 </form>
 <?php
    if(isset($_POST['btn'])){
        echo "
            <script type=\"text/javascript\">
            var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
            </script>
        ";
     }
  ?>

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

How to get the day of week and the month of the year?

  function currentDate() {
      var monthNames = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
                     "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];
      var days = ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'];                       
      var today = new Date();
      var dd   = today.getDate();
      var mm   = monthNames[today.getMonth()]; 
      var yyyy = today.getFullYear();
      var day  = days[today.getDay()];
      today = 'Date is :' + dd + '-' + mm + '-' + yyyy;
      document.write(today +"<br>");
      document.write('Day is : ' + day );
  }
  currentDate();

MySQL Query GROUP BY day / month / year

Here's one more approach. This uses [MySQL's LAST_DAY() function][1] to map each timestamp to its month. It also is capable of filtering by year with an efficient range-scan if there's an index on record_date.

  SELECT LAST_DAY(record_date) month_ending, COUNT(*) record_count
    FROM stats
   WHERE record_date >= '2000-01-01'
     AND record_date <  '2000-01-01' + INTERVAL 1 YEAR
   GROUP BY LAST_DAY(record_date) 

If you want your results by day, use DATE(record_date) instead.

If you want your results by calendar quarter, use YEAR(record_date), QUARTER(record_date).

Here's a writeup. https://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/ [1]: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_last-day

Optional Parameters in Go?

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

  1. If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often.
  2. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.

How can I find where Python is installed on Windows?

I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn't select setting the path when you installed Python 3 that probably won't work - unless you manually updated the path when you installed it. In my case it was at c:\Program Files\Python37\python.exe

Test for array of string type in TypeScript

Try this:

if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}

Dynamically Add Images React Webpack

here is the code

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './image.css';
    import Dropdown from 'react-dropdown';
    import axios from 'axios';

    let obj = {};

    class App extends Component {
      constructor(){
        super();
        this.state = {
          selectedFiles: []
        }
        this.fileUploadHandler = this.fileUploadHandler.bind(this);
      }

      fileUploadHandler(file){
        let selectedFiles_ = this.state.selectedFiles;
        selectedFiles_.push(file);
        this.setState({selectedFiles: selectedFiles_});
      }

      render() {
        let Images = this.state.selectedFiles.map(image => {
          <div className = "image_parent">

              <img src={require(image.src)}
              />
          </div>
        });

        return (
            <div className="image-upload images_main">

            <input type="file" onClick={this.fileUploadHandler}/>
            {Images}

            </div>
        );
      }
    }

    export default App;

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Or you can just use this:

<?
function TestHtml() { 
# PUT HERE YOU PHP CODE
?>
<!-- HTML HERE -->

<? } ?>

to get content from this function , use this :

<?= file_get_contents(TestHtml()); ?>

That's it :)

Pass arguments into C program from command line

In C, this is done using arguments passed to your main() function:

int main(int argc, char *argv[])
{
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

More information can be found online such as this Arguments to main article.

.do extension in web pages?

.do comes from the Struts framework. See this question: Why do Java webapps use .do extension? Where did it come from? Also you can change what your urls look like using mod_rewrite (on Apache).

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

SQL: How to to SUM two values from different tables

SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result

'And so on and so forth.

"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source

How do I create a folder in VB if it doesn't exist?

You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.

Psql list all tables

This can be used in automation scripts if you don't need all tables in all schemas:

  for table in $(psql -qAntc '\dt' | cut -d\| -f2); do
      ...
  done

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

CSS media query to target iPad and iPad only?

/*working only in ipad portrait device*/
@media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
  body{
    background: red !important;
  }  
}
/*working only in ipad landscape device*/
@media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
  body{
    background: green !important;
  }   
}

In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.

Undefined reference to main - collect2: ld returned 1 exit status

Perhaps your main function has been commented out because of e.g. preprocessing. To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i then look with an editor into the generated file es3.i (and search main inside it).

First, you should always (since you are a newbie) compile with

  gcc -Wall -g -c es3.c
  gcc -Wall -g es3.o -o es3

The -Wall flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C till you got no more warnings.

The -g flag is important also, because it asks gcc to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb) to debug your program.

To get the list of symbols in an object file or an executable, you can use nm.

Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).

How to do tag wrapping in VS code?

Embedded Emmet could do the trick:

  1. Select text (optional)
  2. Open command palette (usually Ctrl+Shift+P)
  3. Execute Emmet: Wrap with Abbreviation
  4. Enter a tag div (or an abbreviation .wrapper>p)
  5. Hit Enter

Command can be assigned to a keybinding.

enter image description here


This thing even supports passing arguments:

{
    "key": "ctrl+shift+9",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection",
    "args": {
        "abbreviation": "span"
    }
},

Use it like this:

  • span.myCssClass
  • span#myCssId
  • b
  • b.myCssClass

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If you have a one to many relationship in your query, duplicate rows may occurs on one side.

Suppose the following

TABLE TEAM
ID       TEAM_NAME
0        BULLS
1        LAKERS


TABLE PLAYER
ID       TEAM_ID     PLAYER_NAME
0        0           JORDAN
1        0           PIPPEN

And you execute a query like

SELECT 
    TEAM.TEAM_NAME, 
    PLAYER.PLAYER_NAME 
FROM TEAM
INNER JOIN PLAYER

You will get

TEAM_NAME   PLAYER_NAME
BULLS       JORDAN
BULLS       PIPPEN

So you will have duplicate TEAM NAME. Even using DISTINCT clause, your result set will contain duplicate TEAM NAME

So if you do not want duplicate TEAM_NAME in your query, do the following

SELECT ID, TEAM_NAME FROM TEAM

And for each team ID encountered executes

SELECT PLAYER_NAME FROM PLAYER WHERE TEAM_ID = <PUT_TEAM_ID_RIGHT_HERE>

So this way you will not get duplicates references on one side

regards,

How to find the duration of difference between two dates in java?

Date d2 = new Date();
Date d1 = new Date(1384831803875l);

long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) diff / (1000 * 60 * 60 * 24);

System.out.println(diffInDays+"  days");
System.out.println(diffHours+"  Hour");
System.out.println(diffMinutes+"  min");
System.out.println(diffSeconds+"  sec");

How To Convert A Number To an ASCII Character?

You can use one of these methods to convert number to an ASCII / Unicode / UTF-16 character:

You can use these methods convert the value of the specified 32-bit signed integer to its Unicode character:

char c = (char)65;
char c = Convert.ToChar(65); 

Also, ASCII.GetString decodes a range of bytes from a byte array into a string:

string s = Encoding.ASCII.GetString(new byte[]{ 65 });

Keep in mind that, ASCIIEncoding does not provide error detection. Any byte greater than hexadecimal 0x7F is decoded as the Unicode question mark ("?").

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

For those using newer versions of java: jhat has been removed since Java 9. Source: https://www.infoq.com/news/2015/12/OpenJDK-9-removal-of-HPROF-jhat/

That same article recommends using Java VisualVM instead.

What is a daemon thread in Java?

Definition of Daemon (Computing):

A background process that handles requests for services such as print spooling and file transfers, and is dormant when not required.

—— Source: English by Oxford Dictionaries

What is Daemon thread in Java?

  • Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.
  • Daemon threads are threads that run intermittently in the background as long as other non-daemon threads are running.
  • When all of the non-daemon threads complete, daemon threads terminates automatically.
  • Daemon threads are service providers for user threads running in the same process.
  • The JVM does not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is created by us.
  • Daemon threads acts as services in Windows.
  • The JVM stops the daemon threads when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement, for example, a monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped.

psql: FATAL: database "<user>" does not exist

Connect to postgres via existing superuser.

Create a Database by the name of user you are connecting through to postgres.

create database username;

Now try to connect via username

Creating a directory in /sdcard fails

If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

Rotate camera in Three.js with mouse

This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):

class CameraControl {
    zoomMode: boolean = false
    press: boolean = false
    sensitivity: number = 0.02

    constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
        renderer.domElement.addEventListener('mousemove', event => {
            if(!this.press){ return }

            if(event.button == 0){
                camera.position.y -= event.movementY * this.sensitivity
                camera.position.x -= event.movementX * this.sensitivity        
            } else if(event.button == 2){
                camera.quaternion.y -= event.movementX * this.sensitivity/10
                camera.quaternion.x -= event.movementY * this.sensitivity/10
            }

            updateCallback()
        })    

        renderer.domElement.addEventListener('mousedown', () => { this.press = true })
        renderer.domElement.addEventListener('mouseup', () => { this.press = false })
        renderer.domElement.addEventListener('mouseleave', () => { this.press = false })

        document.addEventListener('keydown', event => {
            if(event.key == 'Shift'){
                this.zoomMode = true
            }
        })

        document.addEventListener('keyup', event => {
            if(event.key == 'Shift'){
                this.zoomMode = false
            }
        })

        renderer.domElement.addEventListener('mousewheel', event => {
            if(this.zoomMode){ 
                camera.fov += event.wheelDelta * this.sensitivity
                camera.updateProjectionMatrix()
            } else {
                camera.position.z += event.wheelDelta * this.sensitivity
            }

            updateCallback()
        })
    }
}

drop it in like:

this.cameraControl = new CameraControl(renderer, camera, () => {
    // you might want to rerender on camera update if you are not rerendering all the time
    window.requestAnimationFrame(() => renderer.render(scene, camera))
})

Controls:

  • move while [holding mouse left / single finger on trackpad] to move camera in x/y plane
  • move [mouse wheel / two fingers on trackpad] to move up/down in z-direction
  • hold shift + [mouse wheel / two fingers on trackpad] to zoom in/out via increasing/decreasing field-of-view
  • move while holding [mouse right / two fingers on trackpad] to rotate the camera (quaternion)

Additionally:

If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:

// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)

Can you use Microsoft Entity Framework with Oracle?

Oracle have announced a "statement of direction" for ODP.net and the Entity Framework:

In summary, ODP.Net beta around the end of 2010, production sometime in 2011.

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

How to show grep result with complete path or file name

For me

grep -b "searchsomething" *.log

worked as I wanted

Tab key == 4 spaces and auto-indent after curly braces in Vim

The best way to get filetype-specific indentation is to use filetype plugin indent on in your vimrc. Then you can specify things like set sw=4 sts=4 et in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).

How to prevent Browser cache on Angular 2 site?

In each html template I just add the following meta tags at the top:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.

Generate MD5 hash string with T-SQL

SELECT CONVERT(
      VARCHAR(32),
      HASHBYTES(
                   'MD5',
                   CAST(prescrip.IsExpressExamRX AS VARCHAR(250))
                   + CAST(prescrip.[Description] AS VARCHAR(250))
               ),
      2
  ) MD5_Value;

works for me.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I faced the same problem but the issue was very silly, By mistake I have given wrong relationship I have given relationship between 2 Ids.

could not extract ResultSet in hibernate

If you don't have 'HIBERNATE_SEQUENCE' sequence created in database (if use oracle or any sequence based database), you shall get same type of error;

Ensure the sequence is present there;

Why Does OAuth v2 Have Both Access and Refresh Tokens?

Why not just make the access_token last as long as the refresh_token and not have a refresh_token?

In addition to great answers other people have provided, there is another reason why we would use refresh tokens and it's to do with claims.

Each token contains claims which can include anything from the user's name, their roles, or the provider which created the claim. As a token is refreshed, these claims are updated.

If we refresh the tokens more often, we are obviously putting more strain on our identity services; however, we are getting more accurate and up-to-date claims.

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

How to initialize a two-dimensional array in Python?

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any 'x' value use :

twoD = np.array([[x]*m]*n

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

Merging arrays with the same keys

Two entries in an array can't share a key, you'll need to change the key for the duplicate

Best way to retrieve variable values from a text file?

You can treat your text file as a python module and load it dynamically using imp.load_source:

import imp
imp.load_source( name, pathname[, file]) 

Example:

// mydata.txt
var1 = 'hi'
var2 = 'how are you?'
var3 = { 1:'elem1', 2:'elem2' }
//...

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)
    f.close()

# path to "config" file
getVarFromFile('c:/mydata.txt')
print data.var1
print data.var2
print data.var3
...

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

How to get length of a list of lists in python

if the name of your list is listlen then just type len(listlen). This will return the size of your list in the python.

Putting images with options in a dropdown list

You can't do that in plain HTML, but you can do it with jQuery:

JavaScript Image Dropdown

Are you tired with your old fashion dropdown? Try this new one. Image combo box. You can add an icon with each option. It works with your existing "select" element or you can create by JSON object.

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


How to distinguish mouse "click" and "drag"

Cleaner ES2015

_x000D_
_x000D_
let drag = false;_x000D_
_x000D_
document.addEventListener('mousedown', () => drag = false);_x000D_
document.addEventListener('mousemove', () => drag = true);_x000D_
document.addEventListener('mouseup', () => console.log(drag ? 'drag' : 'click'));
_x000D_
_x000D_
_x000D_

Didn't experience any bugs, as others comment.

Force youtube embed to start in 720p

This is an embed example of video played in HD 1080.

<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

Let's break apart the code:http://youtube.com/v/ video_id &vq=hd1080

Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.

So far so good, this trick works for playing full HD videos directly on webpages!

You can change the quality to 720 too. &vq=hd720

how to implement Pagination in reactJs

Give you a pagination component, which is maybe a little difficult to understand for newbie to react:

https://www.npmjs.com/package/pagination

HorizontalScrollView within ScrollView Touch Handling

I think I found a simpler solution, only this uses a subclass of ViewPager instead of (its parent) ScrollView.

UPDATE 2013-07-16: I added an override for onTouchEvent as well. It could possibly help with the issues mentioned in the comments, although YMMV.

public class UninterceptableViewPager extends ViewPager {

    public UninterceptableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean ret = super.onInterceptTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean ret = super.onTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }
}

This is similar to the technique used in android.widget.Gallery's onScroll(). It is further explained by the Google I/O 2013 presentation Writing Custom Views for Android.

Update 2013-12-10: A similar approach is also described in a post from Kirill Grouchnikov about the (then) Android Market app.

How to do scanf for single char in C

The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.

One way around the problem is to put a blank space before the conversion specifier in the format string:

scanf(" %c", &c);

The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.

@Resource vs @Autowired

@Autowired + @Qualifier will work only with spring DI, if you want to use some other DI in future @Resource is good option.

other difference which I found very significant is @Qualifier does not support dynamic bean wiring, as @Qualifier does not support placeholder, while @Resource does it very well.

For example: if you have an interface with multiple implementations like this

interface parent {

}
@Service("actualService")
class ActualService implements parent{

}
@Service("stubbedService")
class SubbedService implements parent{

}

with @Autowired & @Qualifier you need to set specific child implementation like

@Autowired
@Qualifier("actualService") or 
@Qualifier("stubbedService") 
Parent object;

which does not provide placeholder while with @Resource you can put placeholder and use property file to inject specific child implementation like

@Resource(name="${service.name}")
Parent object;  

where service.name is set in property file as

#service.name=actualService
 service.name=stubbedService

Hope that helps someone :)

Ping a site in Python?

Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.

import platform,subproccess,re
def Ping(hostname,timeout):
    if platform.system() == "Windows":
        command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
    else:
        command="ping -i "+str(timeout)+" -c 1 " + hostname
    proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
    matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
    if matches:
        return matches.group(1)
    else: 
        return False

Disable beep of Linux Bash on Windows 10

To disable the beeps when ssh-ing in a remote machine, simply create the same ~/.inputrc and ~/.vimrc files on the remote machine to stop ssh itself from beeping.

See the answer from @Nemo for the contents of each file.

Load Image from javascript

Try this.You have some symbols in $imageUrl

<img id="id1" src="$imageUrl" onload="javascript:showImage();">

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

How to trigger event when a variable's value is changed?

The .NET framework actually provides an interface that you can use for notifying subscribers when a property has changed: System.ComponentModel.INotifyPropertyChanged. This interface has one event PropertyChanged. Its usually used in WPF for binding but I have found it useful in business layers as a way to standardize property change notification.

In terms of thread safety I would put a lock under in the setter so that you don't run into any race conditions.

Here are my thoughts in code :) :

public class MyClass : INotifyPropertyChanged
{
    private object _lock;

    public int MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            lock(_lock)
            {
                //The property changed event will get fired whenever
                //the value changes. The subscriber will do work if the value is
                //1. This way you can keep your business logic outside of the setter
                if(value != _myProperty)
                {
                    _myProperty = value;
                    NotifyPropertyChanged("MyProperty");
                }
            }
        }
    }

    private NotifyPropertyChanged(string propertyName)
    {
        //Raise PropertyChanged event
    }
    public event PropertyChangedEventHandler PropertyChanged;
}


public class MySubscriber
{
    private MyClass _myClass;        

    void PropertyChangedInMyClass(object sender, PropertyChangedEventArgs e)
    {
        switch(e.PropertyName)
        {
            case "MyProperty":
                DoWorkOnMyProperty(_myClass.MyProperty);
                break;
        }
    }

    void DoWorkOnMyProperty(int newValue)
    {
        if(newValue == 1)
        {
             //DO WORK HERE
        }
    }
}

Hope this is helpful :)

How to efficiently remove duplicates from an array without using Set

Please check this. It will work for both sorted/unsorted array. The complexity is O(n^2) same as bubble sort. Yes the complexity can be improved further with first sort and then binary search. But this is simple enough to work on every cases except negative element (-1). This can also be changed by using large integer value instead of -1.

void remove_duplicates(int *A, int N)

{

int i,j;

for (i=1; i<N; i++) {
    if (A[i] == -1) continue;
    for (j=i+1; j<=N; j++) {
        if (A[i] == A[j])
            A[j] = -1;
    }
}
}

int main() {

int N;
int A[1001];
int i;

printf("Enter N: ");
scanf("%d", &N);
printf("Enter the elements:\n");
for (i=1; i<=N; i++)
    scanf("%d", &A[i]);

remove_duplicates(A, N);
for (i=1; i<=N; i++) {
    if (A[i] == -1)
        continue;
    printf("%d  ", A[i]);
}
printf("\n");

return 0;
}

Dropping connected users in Oracle database

Issue has been fixed using below procedure :

DECLARE
  v_user_exists NUMBER;
  user_name CONSTANT varchar2(20) := 'SCOTT';
BEGIN
  LOOP
    FOR c IN (SELECT s.sid, s.serial# FROM v$session s WHERE upper(s.username) = user_name)
    LOOP
      EXECUTE IMMEDIATE
        'alter system kill session ''' || c.sid || ',' || c.serial# || ''' IMMEDIATE';
    END LOOP;
    BEGIN
      EXECUTE IMMEDIATE 'drop user ' || user_name || ' cascade';
      EXCEPTION WHEN OTHERS THEN
      IF (SQLCODE = -1940) THEN
        NULL;
      ELSE
        RAISE;
      END IF;
    END;
    BEGIN
      SELECT COUNT(*) INTO v_user_exists FROM dba_users WHERE username = user_name;
      EXIT WHEN v_user_exists = 0;
    END;
  END LOOP;
END;
/

Remove unwanted parts from strings in a column

I often use list comprehensions for these types of tasks because they're often faster.

There can be big differences in performance between the various methods for doing things like this (i.e. modifying every element of a series within a DataFrame). Often a list comprehension can be fastest - see code race below for this task:

import pandas as pd
#Map
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
10000 loops, best of 3: 187 µs per loop
#List comprehension
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in data['result']]
10000 loops, best of 3: 117 µs per loop
#.str
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].str.lstrip('+-').str.rstrip('aAbBcC')
1000 loops, best of 3: 336 µs per loop

How to print the array?

It looks like you have a typo on your array, it should read:

int my_array[3][3] = {...

You don't have the _ or the {.

Also my_array[3][3] is an invalid location. Since computers begin counting at 0, you are accessing position 4. (Arrays are weird like that).

If you want just the last element:

printf("%d\n", my_array[2][2]);

If you want the entire array:

for(int i = 0; i < my_array.length; i++) {
  for(int j = 0; j < my_array[i].length; j++)
    printf("%d ", my_array[i][j]);
  printf("\n");
}

How to retrieve value from elements in array using jQuery?

Use map function

var values = $("input[name^='card']").map(function (idx, ele) {
   return $(ele).val();
}).get();

How can I count the numbers of rows that a MySQL query returned?

The basics

To get the number of matching rows in SQL you would usually use COUNT(*). For example:

SELECT COUNT(*) FROM some_table

To get that in value in PHP you need to fetch the value from the first column in the first row of the returned result. An example using PDO and mysqli is demonstrated below.

However, if you want to fetch the results and then still know how many records you fetched using PHP, you could use count() or avail of the pre-populated count in the result object if your DB API offers it e.g. mysqli's num_rows.

Using MySQLi

Using mysqli you can fetch the first row using fetch_row() and then access the 0 column, which should contain the value of COUNT(*).

// your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'dbuser', 'yourdbpassword', 'db_name');
$mysqli->set_charset('utf8mb4');

// your SQL statement
$stmt = $mysqli->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();

// now fetch 1st column of the 1st row 
$count = $result->fetch_row()[0];

echo $count;

If you want to fetch all the rows, but still know the number of rows then you can use num_rows or count().

// your SQL statement
$stmt = $mysqli->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();

// If you want to use the results, but still know how many records were fetched
$rows = $result->fetch_all(MYSQLI_ASSOC);

echo $result->num_rows;
// or
echo count($rows);

Using PDO

Using PDO is much simpler. You can directly call fetchColumn() on the statement to get a single column value.

// your connection code
$pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
    \PDO::ATTR_EMULATE_PREPARES => false,
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]);

// your SQL statement
$stmt = $pdo->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->execute([
    $someVariable
]);

// Fetch the first column of the first row
$count = $stmt->fetchColumn();

echo $count;

Again, if you need to fetch all the rows anyway, then you can get it using count() function.

// your SQL statement
$stmt = $pdo->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->execute([
    $someVariable
]);

// If you want to use the results, but still know how many records were fetched
$rows = $stmt->fetchAll();

echo count($rows);

PDO's statement doesn't offer pre-computed property with the number of rows fetched, but it has a method called rowCount(). This method can tell you the number of rows returned in the result, but it cannot be relied upon and it is generally not recommended to use.

CentOS: Copy directory to another directory

To copy all files, including hidden files use:

cp -r /home/server/folder/test/. /home/server/

Comparing HTTP and FTP for transferring files

Many firewalls drop outbound connections which are not to ports 80 or 443 (http & https); some even drop connections to those ports that are not HTTP(S). FTP may or may not be allowed, not to speak of the active/PASV modes.

Also, HTTP/1.1 allows for much better partial requests ("only send from byte 123456 to the end of file"), conditional requests and caching ("only send if content changed/if last-modified-date changed") and content compression (gzip).

HTTP is much easier to use through a proxy.

From my anecdotal evidence, HTTP is easier to make work with dropped/slow/flaky connections; e.g. it is not needed to (re)establish a login session before (re)initiating transfer.

OTOH, HTTP is stateless, so you'd have to do authentication and building a trail of "who did what when" yourself.

The only difference in speed I've noticed is transferring lots of small files: HTTP with pipelining is faster (reduces round-trips, esp. noticeable on high-latency networks).

Note that HTTP/2 offers even more optimizations, whereas the FTP protocol has not seen any updates for decades (and even extensions to FTP have insignificant uptake by users). So, unless you are transferring files through a time machine, HTTP seems to have won.

(Tangentially: there are protocols that are better suited for file transfer, such as rsync or BitTorrent, but those don't have as much mindshare, whereas HTTP is Everywhere™)

JavaScript code for getting the selected value from a combo box

There is an unnecessary hashtag; change the code to this:

var e = document.getElementById("ticket_category_clone").value;

How to git reset --hard a subdirectory?

If the size of the subdirectory is not particularly huge, AND you wish to stay away from the CLI, here's a quick solution to manually reset the sub-directory:

  1. Switch to master branch and copy the sub-directory to be reset.
  2. Now switch back to your feature branch and replace the sub-directory with the copy you just created in step 1.
  3. Commit the changes.

Cheers. You just manually reset a sub-directory in your feature branch to be same as that of master branch !!

What's the best/easiest GUI Library for Ruby?

Limelight I really enjoy the theatre metaphor.

reading HttpwebResponse json response, C#

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}

Ubuntu, how do you remove all Python 3 but not 2

So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.

All I did was simply remove Jupyter and then alias python=python2.7 and install all packages on Python 2.7 again.

Arguably, I can install virtualenv but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

Convert hex string (char []) to int?

I know this is really old but I think the solutions looked too complicated. Try this in VB:

Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer 
Dim SumValue as Long 
Dim iVal as long
Dim AscVal as long

    iLen = Len(sHEX)
    For i = 1 to Len(sHEX)
      AscVal = Asc(UCase(Mid$(sHEX, i,  1)))
      If AscVal >= 48 And AscVal  <= 57 Then
        iVal  = AscVal - 48
      ElseIf AscVal >= 65 And AscVal <= 70 Then
        iVal = AscVal - 55
      End If 
      SumValue = SumValue + iVal * 16 ^ (iLen- i)
    Next i 
    HexToInt  = SumValue
End Function 

How can I check for NaN values?

How to remove NaN (float) item(s) from a list of mixed data types

If you have mixed types in an iterable, here is a solution that does not use numpy:

from math import isnan

Z = ['a','b', float('NaN'), 'd', float('1.1024')]

[x for x in Z if not (
                      type(x) == float # let's drop all float values…
                      and isnan(x) # … but only if they are nan
                      )]
['a', 'b', 'd', 1.1024]

Short-circuit evaluation means that isnan will not be called on values that are not of type 'float', as False and (…) quickly evaluates to False without having to evaluate the right-hand side.

Failed to Connect to MySQL at localhost:3306 with user root

It worked for me this way:

Step1: Open System Preference > MySQL > Initialize Database.

Step2: Put password you used while installing MySQL.

Step3: Start MySQL server.

Step4: Come back to MySQL Workbench and double connect/ create a new one.

Python Prime number checker

def isprime(n):
    '''check if integer n is a prime'''

    # make sure n is a positive integer
    n = abs(int(n))

    # 0 and 1 are not primes
    if n < 2:
        return False

    # 2 is the only even prime number
    if n == 2: 
        return True    

    # all other even numbers are not primes
    if not n & 1: 
        return False

    # range starts with 3 and only needs to go up 
    # the square root of n for all odd numbers
    for x in range(3, int(n**0.5) + 1, 2):
        if n % x == 0:
            return False

    return True

Taken from:

http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python

How to remove and clear all localStorage data

Using .one ensures this is done only once and not repeatedly.

$(window).one("focus", function() {
    localStorage.clear();
});

It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.

.one is especially useful when you want local storage to be cleared only once the first time a web page is opened or when a mobile application is installed the first time.

   // Fired once when document is ready
   $(document).one('ready', function () {
       localStorage.clear();
   });

How to get current date & time in MySQL?

You can use NOW():

INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())

How can I print a quotation mark in C?

You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:

printf("this is a \"quoted string\"");

Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.

Jquery UI datepicker. Disable array of Dates

If you also want to block Sundays (or other days) as well as the array of dates, I use this code:

jQuery(function($){

    var disabledDays = [
       "27-4-2016", "25-12-2016", "26-12-2016",
       "4-4-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"
    ];

   //replace these with the id's of your datepickers
   $("#id-of-first-datepicker,#id-of-second-datepicker").datepicker({
      beforeShowDay: function(date){
         var day = date.getDay();
         var string = jQuery.datepicker.formatDate('d-m-yy', date);
         var isDisabled = ($.inArray(string, disabledDays) != -1);

         //day != 0 disables all Sundays
         return [day != 0 && !isDisabled];
      }
   });
});   

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

How can I convert an image into a Base64 string?

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

In oracle, how do I change my session to display UTF8?

The character set is part of the locale, which is determined by the value of NLS_LANG. As the documentation makes clear this is an operating system variable:

NLS_LANG is set as an environment variable on UNIX platforms. NLS_LANG is set in the registry on Windows platforms.

Now we can use ALTER SESSION to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.

Show loading image while $.ajax is performed

Use the ajax object's beforeSend and complete functions. It's better to show the gif from inside beforeSend so that all the behavior is encapsulated in a single object. Be careful about hiding the gif using the success function. If the request fails, you'll probably still want to hide the gif. To do this use the Complete function. It would look like this:

$.ajax({
    url: uri,
    cache: false,
    beforeSend: function(){
        $('#image').show();
    },
    complete: function(){
        $('#image').hide();
    },
    success: function(html){
       $('.info').append(html);
    }
});

Twitter Bootstrap - add top space between rows

There is a trick for adding margin automatically only for the 2nd+ row in the container.

.container-row-margin .row + .row {
    margin-top: 1rem;
}

Adding the .container-row-margin to the container, results in:

enter image description here

Complete HTML:

<div class="bg-secondary text-white">
    div outside of the container.
</div>
<div class="container container-row-margin">
    <div class="row">
        <div class="col col-4 bg-warning">
            Row without top margin
        </div>
    </div>
    <div class="row">
        <div class="col col-4 bg-primary text-white">
            Row with top margin
        </div>
    </div>
    <div class="row">
        <div class="col col-4 bg-primary text-white">
            Row with top margin
        </div>
    </div>
</div>
<div class="bg-secondary text-white">
    div outside of the container.
</div>

Taken from official samples.

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

How to delete stuff printed to console by System.out.println()?

I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:

   import java.awt.AWTException;
   import java.awt.Robot;
   import java.awt.event.KeyEvent;

   public void wipeConsole() throws AWTException{
        Robot robbie = new Robot();
        //shows the Console View
        robbie.keyPress(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyRelease(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyPress(KeyEvent.VK_C);
        robbie.keyRelease(KeyEvent.VK_C);

        //clears the console
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_F10);
        robbie.keyRelease(KeyEvent.VK_SHIFT);
        robbie.keyRelease(KeyEvent.VK_F10);
        robbie.keyPress(KeyEvent.VK_R);
        robbie.keyRelease(KeyEvent.VK_R);
    }

Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

You can also use replace(tzinfo=None) for other datetime.

if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

None of the above worked out for me until I changed the Action as [HttpPost]. and made the ajax type as POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

And the ajax call as

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});

Keep overflow div scrolled to bottom unless user scrolls up

I couldn't get the top two answers to work, and none of the other answers were helpful to me. So I paid three people $30 from Reddit r/forhire and Upwork and got some really good answers. This answer should save you $90.



Justin Hundley / The Site Bros' solution

HTML

<div id="chatscreen">
  <div id="inner">
  
  </div>
</div>

CSS

#chatscreen {
  width: 300px;
  overflow-y: scroll;
  max-height:100px;
}

Javascript

$(function(){
    var scrolled = false;
  var lastScroll = 0;
  var count = 0;
    $("#chatscreen").on("scroll", function() {
    var nextScroll = $(this).scrollTop();

    if (nextScroll <= lastScroll) {
        scrolled = true;
    }
    lastScroll = nextScroll;
    
    console.log(nextScroll, $("#inner").height())
    if ((nextScroll + 100) == $("#inner").height()) {
        scrolled = false;
    }
  });
 
  function updateScroll(){
      if(!scrolled){
          var element = document.getElementById("chatscreen");
          var inner = document.getElementById("inner");
          element.scrollTop = inner.scrollHeight;
      }
  }

  // Now let's load our messages
  function load_messages(){
      $( "#inner" ).append( "Test" + count + "<br/>" );
      count = count + 1;
      updateScroll();
  }

    setInterval(load_messages,300); 
});

Preview the site bros' solution

portfolio



Lermex / Sviatoslav Chumakov's solution

HTML

<div id="chatscreen">

</div>

CSS

#chatscreen {
  height: 300px;
  border: 1px solid purple;
  overflow: scroll;
}

Javascript

$(function(){
var isScrolledToBottom = false;
// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
    updateScr();
}

var out = document.getElementById("chatscreen");
var c = 0;

$("#chatscreen").on('scroll', function(){
        console.log(out.scrollHeight);
    isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 10;
});

function updateScr() {
        // allow 1px inaccuracy by adding 1
    //console.log(out.scrollHeight - out.clientHeight,  out.scrollTop + 1);
    var newElement = document.createElement("div");

    newElement.innerHTML = c++;
    out.appendChild(newElement);
    
    console.log(isScrolledToBottom);

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}

var add = setInterval(updateScr, 1000);

setInterval(load_messages,300); // change to 300 to show the latest message you sent after pressing enter // comment this line and it works, uncomment and it fails
                                // leaving it on 1000 shows the second to last message
setInterval(updateScroll,30);
});

Preview Sviatoslav's solution

portfolio



Igor Rusinov's Solution

HTML

<div id="chatscreen"></div>

CSS

#chatscreen {
  height: 100px;
  overflow: scroll;
  border: 1px solid #000;
}

Javascript

$(function(){

// Now let's load our messages
function load_messages(){
    $( "#chatscreen" ).append( "<br>Test" );
}

var out = document.getElementById("chatscreen");
var c = 0;
var add = setInterval(function() {
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
    load_messages();

    // scroll to bottom if isScrolledToBotto
    if(isScrolledToBottom) {out.scrollTop = out.scrollHeight - out.clientHeight; }
}, 1000);
setInterval(updateScroll,30);
});

Preview Igor's solution

portfolio

mysql -> insert into tbl (select from another table) and some default values

With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:

INSERT INTO course_payment 
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

How to check if running as root in a bash script

In a bash script, you have several ways to check if the running user is root.

As a warning, do not check if a user is root by using the root username. Nothing guarantees that the user with ID 0 is called root. It's a very strong convention that is broadly followed but anybody could rename the superuser another name.

I think the best way when using bash is to use $EUID, from the man page:

EUID   Expands to the effective user ID of the current  user,  initialized
       at shell startup.  This variable is readonly.

This is a better way than $UID which could be changed and not reflect the real user running the script.

if (( $EUID != 0 )); then
    echo "Please run as root"
    exit
fi

A way I approach that kind of problem is by injecting sudo in my commands when not run as root. Here is an example:

SUDO=''
if (( $EUID != 0 )); then
    SUDO='sudo'
fi
$SUDO a_command

This ways my command is run by root when using the superuser or by sudo when run by a regular user.

If your script is always to be run by root, simply set the rights accordingly (0500).

Only read selected columns

To read a specific set of columns from a dataset you, there are several other options:

1) With freadfrom the data.table-package:

You can specify the desired columns with the select parameter from fread from the data.table package. You can specify the columns with a vector of column names or column numbers.

For the example dataset:

library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))

Alternatively, you can use the drop parameter to indicate which columns should not be read:

dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))

All result in:

> data
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

UPDATE: When you don't want fread to return a data.table, use the data.table = FALSE-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)

2) With read.csv.sql from the sqldf-package:

Another alternative is the read.csv.sql function from the sqldf package:

library(sqldf)
dat <- read.csv.sql("data.txt",
                    sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                    sep = "\t")

3) With the read_*-functions from the readr-package:

library(readr)
dat <- read_table("data.txt",
                  col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                        Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
                  col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                   Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')

From the documentation an explanation for the used characters with col_types:

each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column

What is trunk, branch and tag in Subversion?

The "trunk", "branches", and "tags" directories are conventions in Subversion. Subversion does not require you to have these directories nor assign special meaning to them. However, this convention is very common and, unless you have a really good reason, you should follow the convention. The book links that other readers have given describe the convention and how to use it.

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

css h1 - only as wide as the text

You can use display:inline-block to force this behavior

How to create an empty file with Ansible?

Building on the accepted answer, if you want the file to be checked for permissions on every run, and these changed accordingly if the file exists, or just create the file if it doesn't exist, you can use the following:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin 
        owner=root
        group=sys
        mode=0555
        state={{ "file" if  p.stat.exists else "touch"}}

Detect rotation of Android phone in the browser with JavaScript

It is possible in HTML5.
You can read more (and try a live demo) here: http://slides.html5rocks.com/#slide-orientation.

window.addEventListener('deviceorientation', function(event) {
    var a = event.alpha;
    var b = event.beta;
    var g = event.gamma;
}, false);

It also supports deskop browsers but it will always return the same value.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

What i did was i commented out the

props.put("mail.smtp.starttls.enable","true"); 

Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.

What is the difference between origin and upstream on GitHub?

In a nutshell answer.

  • origin: the fork
  • upstream: the forked

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

How to determine SSL cert expiration date from a PEM encoded certificate?

Same as accepted answer, But note that it works even with .crt file and not just .pem file, just in case if you are not able to find .pem file location.

openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt

Result:

notAfter=Mar 29 06:15:00 2020 GMT

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

How do I compare strings in Java?

In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

The == operator checks if the two strings are exactly the same object.

The .equals() method check if the two strings have the same value.

Date to milliseconds and back to date in Swift

As @Travis Solution works but in some cases

var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

with error

Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

Here is Updated Answer

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

About Int definitions.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

Hope it is helpful to someone who also has same problem

get one item from an array of name,value JSON

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

Maybe you want to do something like:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Why doesn't file_get_contents work?

The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:

sudo chmod 777 file.jpeg

and then you can access if the above mentioned problems are not your case.

Javascript/DOM: How to remove all events of a DOM object?

You can add a helper function that clears event listener for example

function clearEventListener(element) {
 const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}

just pass in the element to the function and that's it...

How can I use JavaScript in Java?

You can use ScriptEngine, example:


public class Main {
    public static void main(String[] args) {
        StringBuffer javascript = null;
        ScriptEngine runtime = null;

        try {
            runtime = new ScriptEngineManager().getEngineByName("javascript");
            javascript = new StringBuffer();

            javascript.append("1 + 1");

            double result = (Double) runtime.eval(javascript.toString());

            System.out.println("Result: " + result);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

How can I add reflection to a C++ application?

even though reflection is not supported out-of-the-box in c++, it is not too hard to implement. I've encountered this great article: http://replicaisland.blogspot.co.il/2010/11/building-reflective-object-system-in-c.html

the article explains in great detail how you can implement a pretty simple and rudimentary reflection system. granted its not the most wholesome solution, and there are rough edges left to be sorted out but for my needs it was sufficient.

the bottom line - reflection can pay off if done correctly, and it is completely feasible in c++.

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

How to modify JsonNode in Java?

JsonNode is immutable and is intended for parse operation. However, it can be cast into ObjectNode (and ArrayNode) that allow mutations:

((ObjectNode)jsonNode).put("value", "NO");

For an array, you can use:

((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How to force DNS refresh for a website?

If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.

Creating a JSON response using Django and Python

In View use this:

form.field.errors|striptags

for getting validation messages without html

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

Make selected block of text uppercase

It is the same as in eclipse:

  • Select text for upper case and Ctrl + Shift + X
  • Select text for lower case and Ctrl + Shift + Y

Using .htaccess to make all .html pages to run as .php files?

I'm using PHP7.1 running in my Raspberry Pi 3.

In the file /etc/apache2/mods-enabled/php7.1.conf I added at the end:

AddType application/x-httpd-php .html .htm .png .jpg .gif

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

Set markers for individual points on a line in Matplotlib

For future reference - the Line2D artist returned by plot() also has a set_markevery() method which allows you to only set markers on certain points - see https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_markevery

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

If you are using Windows try out the following:

  1. Press (Windows+R)
  2. enter "services.msc" and click "OK"
  3. locate service with name 'wampapache'

and check if it's status is 'Running'. In case not, right click >> start.

Hope this helps!


If you have removed WAMP from boot services, it won't work – try the following:

  • Press (Windows+R)
  • enter "services.msc" and click "OK"
  • locate service with name 'wampapache'
  • Right click wampapache and wampmysqld, Click 'properties'
  • and change Start Type to Manual or automatic

This will work!

Set Windows process (or user) memory limit

No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.

The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.

The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.

An efficient compression algorithm for short text strings

Check out Smaz:

Smaz is a simple compression library suitable for compressing very short strings.

What is ADT? (Abstract Data Type)

The term data type is as the type of data which a particular variable can hold - it may be an integer, a character, a float, or any range of simple data storage representation. However, when we build an object oriented system, we use other data types, known as abstract data type, which represents more realistic entities.

E.g.: We might be interested in representing a 'bank account' data type, which describe how all bank account are handled in a program. Abstraction is about reducing complexity, ignoring unnecessary details.

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

Escaping HTML strings with jQuery

There is also the solution from mustache.js

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How do I declare a 2d array in C++ using new?

Below example may help,

int main(void)
{
    double **a2d = new double*[5]; 
    /* initializing Number of rows, in this case 5 rows) */
    for (int i = 0; i < 5; i++)
    {
        a2d[i] = new double[3]; /* initializing Number of columns, in this case 3 columns */
    }

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            a2d[i][j] = 1; /* Assigning value 1 to all elements */
        }
    }

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << a2d[i][j] << endl;  /* Printing all elements to verify all elements have been correctly assigned or not */
        }
    }

    for (int i = 0; i < 5; i++)
        delete[] a2d[i];

    delete[] a2d;


    return 0;
}

How to drop all tables from a database with one SQL query?

For me I just do


DECLARE @cnt INT = 0;

WHILE @cnt < 10 --Change this if all tables are not dropped with one run
BEGIN
SET @cnt = @cnt + 1;
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
END

When should I use a struct rather than a class in C#?

Struct can be used to improve garbage collection performance. While you usually don't have to worry about GC performance, there are scenarios where it can be a killer. Like large caches in low latency applications. See this post for an example:

http://00sharp.wordpress.com/2013/07/03/a-case-for-the-struct/

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

JavaScript DOM: Find Element Index In Container

If you want to write this compactly all you need is:

var i = 0;
for (;yourElement.parentNode[i]!==yourElement;i++){}
indexOfYourElement = i;

We just cycle through the elements in the parent node, stopping when we find your element.

You can also easily do:

for (;yourElement.parentNode.getElementsByTagName("li")[i]!==yourElement;i++){}

if that's all you want to look through.

How to get date representing the first day of a month?

SELECT  CAST(FLOOR(CAST(DATEADD(d, 1 - DAY(GETDATE()), GETDATE()) AS FLOAT)) AS DATETIME)

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

How can I easily view the contents of a datatable or dataview in the immediate window

and if you want this anywhere... to be a helper on DataTable this assumes you want to capture the output to Log4Net but the excellent starting example I worked against just dumps to the console... This one also has editable column width variable nMaxColWidth - ultimately I will pass that from whatever context...

public static class Helpers
    {
        private static ILog Log = Global.Log ?? LogManager.GetLogger("MyLogger");
        /// <summary>
        /// Dump contents of a DataTable to the log
        /// </summary>
        /// <param name="table"></param>
        public static void DebugTable(this DataTable table)
        {
            Log?.Debug("--- DebugTable(" + table.TableName + ") ---");
            var nRows = table.Rows.Count;
            var nCols = table.Columns.Count;
            var nMaxColWidth = 32;

            // Column Headers

            var sColFormat = @"{0,-" + nMaxColWidth + @"} | ";
            var sLogMessage = string.Empty;
            for (var i = 0; i < table.Columns.Count; i++)
            {
                sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, table.Columns[i].ToString()));
            }
            //Debug.Write(Environment.NewLine);
            Log?.Debug(sLogMessage);

            var sUnderScore = string.Empty;
            var sDashes = string.Empty;
            for (var j = 0; j <= nMaxColWidth; j++)
            {
                sDashes = sDashes + "-";
            }


            for (var i = 0; i < table.Columns.Count; i++)
            {
                sUnderScore = string.Concat(sUnderScore, sDashes + "|-");
            }

            sUnderScore = sUnderScore.TrimEnd('-');

            //Debug.Write(Environment.NewLine);
            Log?.Debug(sUnderScore);

            // Data
            for (var i = 0; i < nRows; i++)
            {
                DataRow row = table.Rows[i];
                //Debug.WriteLine("{0} {1} ", row[0], row[1]);
                sLogMessage = string.Empty;

                for (var j = 0; j < nCols; j++)
                {
                    string s = row[j].ToString();
                    if (s.Length > nMaxColWidth) s = s.Substring(0, nMaxColWidth - 3) + "...";
                    sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, s));
                }

                Log?.Debug(sLogMessage);
                //Debug.Write(Environment.NewLine);
            }           
            Log?.Debug(sUnderScore);
        }
}

Adobe Reader Command Line Reference

Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n

string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe"; 
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();

C# DataRow Empty-check

I did it like this:

var listOfRows = new List<DataRow>();
foreach (var row in resultTable.Rows.Cast<DataRow>())
{
    var isEmpty = row.ItemArray.All(x => x == null || (x!= null && string.IsNullOrWhiteSpace(x.ToString())));
    if (!isEmpty)
    {
        listOfRows.Add(row);
    }
}

Simple export and import of a SQLite database on Android

This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a

    public class ExportImportDB extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
            File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");

               if(!direct.exists())
                {
                    if(direct.mkdir()) 
                      {
                       //directory is created;
                      }

                }
            exportDB();
            importDB();

        }
    //importing database
        private void importDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data  = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File  backupDB= new File(data, currentDBPath);
                    File currentDB  = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }
    //exporting database 
        private void exportDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

Dont forget to add this permission to proceed it

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

Enjoy

How to do a redirect to another route with react-router?

1) react-router > V5 useHistory hook:

If you have React >= 16.8 and functional components you can use the useHistory hook from react-router.

import React from 'react';
import { useHistory } from 'react-router-dom';

const YourComponent = () => {
    const history = useHistory();

    const handleClick = () => {
        history.push("/path/to/push");
    }

    return (
        <div>
            <button onClick={handleClick} type="button" />
        </div>
    );
}

export default YourComponent;

2) react-router > V4 withRouter HOC:

As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter

import React, { Component } from 'react';
import { withRouter } from "react-router-dom";

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

export default withRouter(YourComponent);

3) React-router < V4 with browserHistory

You can achieve this functionality using react-router BrowserHistory. Code below:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';

export default class YourComponent extends Component {
    handleClick = () => {
        browserHistory.push('/login');
    };

    render() {
        return (
            <div>
                <button onClick={this.handleClick} type="button">
            </div>
        );
    };
}

4) Redux connected-react-router

If you have connected your component with redux, and have configured connected-react-router all you have to do is this.props.history.push("/new/url"); ie, you don't need withRouter HOC to inject history to the component props.

// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';

export default (history) => combineReducers({
    router: connectRouter(history),
    ... // rest of your reducers
});


// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();

export default function configureStore(preloadedState) {
    const store = createStore(
        createRootReducer(history), // root reducer with router state
        preloadedState,
        compose(
            applyMiddleware(
                routerMiddleware(history), // for dispatching history actions
                // ... other middlewares ...
            ),
        ),
    );

    return store;
}


// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)

ReactDOM.render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <> { /* your usual react-router v4/v5 routing */ }
                <Switch>
                    <Route exact path="/yourPath" component={YourComponent} />
                </Switch>
            </>
        </ConnectedRouter>
    </Provider>,
    document.getElementById('root')
);


// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...

class YourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
          <div>
            <button onClick={this.handleClick} type="button">
          </div>
        );
      }
    };

}

export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

jQuery validation: change default error message

This worked for me:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

php $_POST array empty upon form submission

I've found that when posting from HTTP to HTTPS, the $_POST comes empty. This happened while testing the form, but took me a while until I realize that.

Complexities of binary tree traversals

O(n), because you traverse each node once. Or rather - the amount of work you do for each node is constant (does not depend on the rest of the nodes).

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

How to make full screen background in a web page

I have followed this tutorial: https://css-tricks.com/perfect-full-page-background-image/

Specifically, the first Demo was the one that helped me out a lot!

CSS
 {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}

this might help!

Entity Framework. Delete all rows in table

var data = (from n in db.users select n);
db.users.RemoveRange(data);
db.SaveChanges();

Adding data attribute to DOM

to get the text from a

<option value="1" data-sigla="AC">Acre</option>

uf = $("#selectestado option:selected").attr('data-sigla');

How do I get the fragment identifier (value after hash #) from a URL?

You may do it by using following code:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

SEE DEMO

How do I combine a background-image and CSS3 gradient on the same element?

If you also want to set background position for your image, than you can use this:

background-color: #444; // fallback
background: url('PATH-TO-IMG') center center no-repeat; // fallback

background: url('PATH-TO-IMG') center center no-repeat, -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
background: url('PATH-TO-IMG') center center no-repeat, -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
background: url('PATH-TO-IMG') center center no-repeat, -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
background: url('PATH-TO-IMG') center center no-repeat, -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
background: url('PATH-TO-IMG') center center no-repeat, linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10

or you can also create a LESS mixin (bootstrap style):

#gradient {
    .vertical-with-image(@startColor: #555, @endColor: #333, @image) {
        background-color: mix(@startColor, @endColor, 60%); // fallback
        background-image: @image; // fallback

        background: @image, -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
        background: @image, -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
        background: @image, -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
        background: @image, -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
        background: @image, linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10
    }
}

change text of button and disable button in iOS

SWIFT 4 with extension

set:

// set button label for all states
extension UIButton {
    public func setAllStatesTitle(_ newTitle: String){
        self.setTitle(newTitle, for: .normal)
        self.setTitle(newTitle, for: .selected)
        self.setTitle(newTitle, for: .disabled)
    }
}

and use:

yourBtn.setAllStatesTitle("btn title")

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Difference between Hashing a Password and Encrypting it

I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.

Android Webview - Completely Clear the Cache

CookieSyncManager.createInstance(this);    
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.removeAllCookie();

It can clear google account in my webview

C++ performance vs. Java/C#

Actually Sun's HotSpot JVM uses "mixed-mode" execution. It interprets the method's bytecode until it determines (usually through a counter of some sort) that a particular block of code (method, loop, try-catch block, etc.) is going to be executed a lot, then it JIT compiles it. The time required to JIT compile a method often takes longer than if the method were to be interpreted if it is a seldom run method. Performance is usually higher for "mixed-mode" because the JVM does not waste time JITing code that is rarely, if ever, run. C# and .NET do not do this. .NET JITs everything which, often times, wastes time.

How to set background image of a view?

use this

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]];

How to resize Twitter Bootstrap modal dynamically based on the content

I couldn't get PSL's answer working for me so I found all I have to do is set the div holding the modal content with style="display: table;". The modal content itself says how big it wants to be and the modal accommodates it.

Filter Pyspark dataframe column with None value

You can use Column.isNull / Column.isNotNull:

df.where(col("dt_mvmt").isNull())

df.where(col("dt_mvmt").isNotNull())

If you want to simply drop NULL values you can use na.drop with subset argument:

df.na.drop(subset=["dt_mvmt"])

Equality based comparisons with NULL won't work because in SQL NULL is undefined so any attempt to compare it with another value returns NULL:

sqlContext.sql("SELECT NULL = NULL").show()
## +-------------+
## |(NULL = NULL)|
## +-------------+
## |         null|
## +-------------+


sqlContext.sql("SELECT NULL != NULL").show()
## +-------------------+
## |(NOT (NULL = NULL))|
## +-------------------+
## |               null|
## +-------------------+

The only valid method to compare value with NULL is IS / IS NOT which are equivalent to the isNull / isNotNull method calls.

How to ping ubuntu guest on VirtualBox

In most cases simply switching the virtual machine network adapter to bridged mode is enough to make the guest machine accessible from outside.

Switching virtual machine network adapter type

Sometimes it's possible for the guest machine to not automatically receive an IP which matches the host's IP range after switching to bridged mode (even after rebooting the guest machine). This is often caused by a malfunctioning or badly configured DHCP on the host network.

For example, if the host IP is 192.168.1.1 the guest machine needs to have an IP in the format 192.168.1.* where only the last group of numbers is allowed to be different from the host IP.

You can use a terminal (shell) and type ifconfig (ipconfig for Windows guests) to check what IP is assigned to the guest machine and change it if required.

Getting the guest's machine IP

If the host and guest IPs do not match simply setting a static IP for the guest machine explicitly should resolve the issue.

Get the current date in java.sql.Date format

In order to get "the current date" (as in today's date), you can use LocalDate.now() and pass that into the java.sql.Date method valueOf(LocalDate).

import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());

How to use SharedPreferences in Android to store, fetch and edit values

Singleton Shared Preferences Class. it may help for others in future.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

To Write data

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

To Read Data

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

if you think you followed everything good but still unlucky, just make sure you/capistrano run touch tmp/restart.txt or equivalent at the end. I was in the unlucky list but now :)

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Personally I use small subset of Bootstrap functionality and don't need to attach Tether.

This should help:

window.Tether = function () {
  throw new Error('Your Bootstrap may actually need Tether.');
};

Create an ISO date object in javascript

I solved this problem instantiating a new Date object in node.js:...

In Javascript, send the Date().toISOString() to nodejs:...

var start_date = new Date(2012, 01, 03, 8, 30);

$.ajax({
    type: 'POST',
    data: { start_date: start_date.toISOString() },
    url: '/queryScheduleCollection',
    dataType: 'JSON'
}).done(function( response ) { ... });

Then use the ISOString to create a new Date object in nodejs:..

exports.queryScheduleCollection = function(db){
    return function(req, res){

        var start_date = new Date(req.body.start_date);

        db.collection('schedule_collection').find(
            { start_date: { $gte: start_date } }
        ).toArray( function (err,d){
            ...
            res.json(d)
        })
    }
};

Note: I'm using Express and Mongoskin.

.append(), prepend(), .after() and .before()

To try and answer your main question:

why would you use .append() rather then .after() or vice verses?

When you are manipulating the DOM with jquery the methods you use depend on the result you want and a frequent use is to replace content.

In replacing content you want to .remove() the content and replace it with new content. If you .remove() the existing tag and then try to use .append() it won't work because the tag itself has been removed, whereas if you use .after(), the new content is added 'outside' the (now removed) tag and isn't affected by the previous .remove().

Removing object properties with Lodash

Get a list of properties from model using _.keys(), and use _.pick() to extract the properties from credentials to a new object:

_x000D_
_x000D_
var model = {
   fname:null,
   lname:null
};

var credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
};

var result = _.pick(credentials, _.keys(model));

console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

If you don't want to use Lodash, you can use Object.keys(), and Array.prototype.reduce():

_x000D_
_x000D_
var model = {
   fname:null,
   lname:null
};

var credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
};

var result = Object.keys(model).reduce(function(obj, key) {
  obj[key] = credentials[key];
  return obj;
}, {});

console.log(result);
_x000D_
_x000D_
_x000D_

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

How to set default font family for entire Android app

Another way to do this for the whole app is using reflection based on this answer

public class TypefaceUtil {
    /**
     * Using reflection to override default typefaces
     * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE
     * OVERRIDDEN
     *
     * @param typefaces map of fonts to replace
     */
    public static void overrideFonts(Map<String, Typeface> typefaces) {
        try {
            final Field field = Typeface.class.getDeclaredField("sSystemFontMap");
            field.setAccessible(true);
            Map<String, Typeface> oldFonts = (Map<String, Typeface>) field.get(null);
            if (oldFonts != null) {
                oldFonts.putAll(typefaces);
            } else {
                oldFonts = typefaces;
            }
            field.set(null, oldFonts);
            field.setAccessible(false);
        } catch (Exception e) {
            Log.e("TypefaceUtil", "Can not set custom fonts");
        }
    }

    public static Typeface getTypeface(int fontType, Context context) {
        // here you can load the Typeface from asset or use default ones
        switch (fontType) {
            case BOLD:
                return Typeface.create(SANS_SERIF, Typeface.BOLD);
            case ITALIC:
                return Typeface.create(SANS_SERIF, Typeface.ITALIC);
            case BOLD_ITALIC:
                return Typeface.create(SANS_SERIF, Typeface.BOLD_ITALIC);
            case LIGHT:
                return Typeface.create(SANS_SERIF_LIGHT, Typeface.NORMAL);
            case CONDENSED:
                return Typeface.create(SANS_SERIF_CONDENSED, Typeface.NORMAL);
            case THIN:
                return Typeface.create(SANS_SERIF_MEDIUM, Typeface.NORMAL);
            case MEDIUM:
                return Typeface.create(SANS_SERIF_THIN, Typeface.NORMAL);
            case REGULAR:
            default:
                return Typeface.create(SANS_SERIF, Typeface.NORMAL);
        }
    }
}

then whenever you want to override the fonts you can just call the method and give it a map of typefaces as follows:

Typeface regular = TypefaceUtil.getTypeface(REGULAR, context);
Typeface light = TypefaceUtil.getTypeface(REGULAR, context);
Typeface condensed = TypefaceUtil.getTypeface(CONDENSED, context);
Typeface thin = TypefaceUtil.getTypeface(THIN, context);
Typeface medium = TypefaceUtil.getTypeface(MEDIUM, context);
Map<String, Typeface> fonts = new HashMap<>();
fonts.put("sans-serif", regular);
fonts.put("sans-serif-light", light);
fonts.put("sans-serif-condensed", condensed);
fonts.put("sans-serif-thin", thin);
fonts.put("sans-serif-medium", medium);
TypefaceUtil.overrideFonts(fonts);

for full example check

This only works for Android SDK 21 and above for earlier versions check the full example

Understanding lambda in python and using it to pass multiple arguments

I believe bind always tries to send an event parameter. Try:

self.entry_1.bind("<Return>", lambda event: self.calculate(self.buttonOut_1.grid_info(), 1))

You accept the parameter and never use it.

./configure : /bin/sh^M : bad interpreter

When you write your script on windows environment and you want to run it on unix environnement you need to be careful about the encodage :

dos2unix $filePath

How to convert an array to a string in PHP?

PHP's implode function can be used to convert an array into a string --- it is similar to join in other languages.

You can use it like so:

$string_product = implode(',', $array);

With an array like [1, 2, 3], this would result in a string like "1,2,3".

Multiple commands in an alias for bash

Does this not work?

alias whatever='gnome-screensaver ; gnome-screensaver-command --lock'

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

For googlers and completeness sake:

Here's a reference I always use when I need to go through the pain of implementing html email-templates or signatures: http://www.campaignmonitor.com/css/

I'ts a list of CSS support for most, if not all, CSS options, nicely compared between some of the most used email clients.

For centering, feel free to just use CSS (as the align attribute is deprecated in HTML 4.01).

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td style="text-align: center;">
            Your Content
        </td>
    </tr>
</table>

Calling remove in foreach loop in Java

  1. Try this 2. and change the condition to "WINTER" and you will wonder:
public static void main(String[] args) {
  Season.add("Frühling");
  Season.add("Sommer");
  Season.add("Herbst");
  Season.add("WINTER");
  for (String s : Season) {
   if(!s.equals("Sommer")) {
    System.out.println(s);
    continue;
   }
   Season.remove("Frühling");
  }
 }

Get max and min value from array in JavaScript

Instead of .each, another (perhaps more concise) approach to getting all those prices might be:

var prices = $(products).children("li").map(function() {
    return $(this).prop("data-price");
}).get();

additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:

prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });

then use Sergey's solution above:

var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);

Convert String to double in Java

Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.

Guava offers a utility method for this which returns null in case your String can't be parsed.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)

Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);

In runtime, a malformed String input yields null assigned to valueDouble

How can I tell gcc not to inline a function?

You want the gcc-specific noinline attribute.

This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm ("");

Use it like this:

void __attribute__ ((noinline)) foo() 
{
  ...
}

Constructor in an Interface?

See this question for the why (taken from the comments).

If you really need to do something like this, you may want an abstract base class rather than an interface.

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Get cookie by name

Following function will return a key-value pair of the required cookie, where key is the cookie name and value will be the value of the cookie.

/**
 * Returns cookie key-value pair
 */
var getCookieByName = function(name) {
    var result = ['-1','-1'];
    if(name) {
        var cookieList = document.cookie.split(';');
        result = $.grep(cookieList,function(cookie) { 
            cookie = cookie.split('=')[0];
            return cookie == name;
        });
    }
    return result;
};

Hash table in JavaScript

The Javascript interpreter natively stores objects in a hash table. If you're worried about contamination from the prototype chain, you can always do something like this:

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true

Could not find main class HelloWorld

JAVA_HOME is not necessary if you start java and javac from the command line. But JAVA_HOME should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0 in your case.

I'd never use the CLASSPATH environment variable outside of build scripts, especially not global defined. The -cp flag is better. But in your case, as you do not need additional libraries (rt.jardoesn't count), you won't need a classpath declaration. A missing -cp is equivalent to a -cp . and that's what you need here)

The HelloWorld class needs to be declared as public. This actually may be the cause for your problems. (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)

jQuery Ajax PUT with parameters

You can use the PUT method and pass data that will be included in the body of the request:

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), // access in body
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I came across the same problem using a Wordpress page and plugin. This didn't work for the iframe plugin

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730#?platform=iphone"]

but this does:

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730"  width="100%" height="480" ]

As you see, I just left off the #?platform=iphone part in the end.

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

How to set up a cron job to run an executable every hour?

Did you mean the executable fails to run , if invoked from any other directory? This is rather a bug on the executable. One potential reason could be the executable requires some shared libraires from the installed folder. You may check environment variable LD_LIBRARY_PATH

Cannot instantiate the type List<Product>

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

How do I check if an object has a specific property in JavaScript?

You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.

How to check if a radiobutton is checked in a radiogroup in Android?

  rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch(i) {
                case R.id.type_car:
                    num=1;
                    Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
                    break;
                case R.id.type_bike:
                    num=2;
                    Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    });

Splitting a Java String by the pipe symbol using split("|")

You can also use .split("[|]").

(I used this instead of .split("\\|"), which didn't work for me.)

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

i think that is what you want.

SELECT 
      A.SalesOrderID, 
      A.OrderDate, 
      FooFromB.*

FROM A,
     (SELECT TOP 1 B.Foo
      FROM B
      WHERE A.SalesOrderID = B.SalesOrderID
      ) AS FooFromB

WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'