Programs & Examples On #Structured data

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

Cannot implicitly convert type 'int?' to 'int'.

You can change the last line to following (assuming you want to return 0 when there is nothing in db):

return OrdersPerHour == null ? 0 : OrdersPerHour.Value;

How do you clear the focus in javascript?

None of the answers provided here are completely correct when using TypeScript, as you may not know the kind of element that is selected.

This would therefore be preferred:

if (document.activeElement instanceof HTMLElement)
    document.activeElement.blur();

I would furthermore discourage using the solution provided in the accepted answer, as the resulting blurring is not part of the official spec, and could break at any moment.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

I have just tested Google Geocoder and got the same problem as you have. I noticed I only get the OVER_QUERY_LIMIT status once every 12 requests So I wait for 1 second (that's the minimum delay to wait) It slows down the application but less than waiting 1 second every request

info = getInfos(getLatLng(code)); //In here I call Google API
record(code, info);
generated++; 
if(generated%interval == 0) {
holdOn(delay); // Every x requests, I sleep for 1 second
}

With the basic holdOn method :

private void holdOn(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ex) {
            // ignore
        }
    }

Hope it helps

SQL Server: Error converting data type nvarchar to numeric

In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.

SELECT ISNUMERIC('2.81104e+006') 

returns 1.

SELECT convert(decimal(15,2), '2.81104e+006') 

returns

error: Error converting data type varchar to numeric.

And

SELECT try_convert(decimal(15,2), '2.81104e+006') 

returns NULL.

SELECT convert(float, '2.81104e+006') 

returns the correct value 2811040.

scroll image with continuous scrolling using marquee tag

Try this:

<marquee behavior="" Height="200px"  direction="up" scroll onmouseover="this.setAttribute('scrollamount', 0, 0);this.stop();" onmouseout="this.setAttribute('scrollamount', 3, 0);this.start();" scrollamount="3" valign="center">

    <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
    </marquee>

yii2 redirect in controller action does not work?

here is another way to do this

if(!Yii::$app->request->getIsPost()) {
    return Yii::$app->getResponse()->redirect(array('/user/index',302));
}

How to join multiple lines of file names into one with custom delimiter?

If Python3 is your cup of tea, you can do this (but please explain why you would?):

ls -1 | python -c "import sys; print(','.join(sys.stdin.read().splitlines()))"

Android Activity as a dialog

If your activity is being rendered as a dialog, simply add a button to your activity's xml,

<Button
    android:id="@+id/close_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Dismiss" />

Then attach a click listener in your Activity's Java code. In the listener, simply call finish()

Button close_button = (Button) findViewById(R.id.close_button);
close_button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

That should dismiss your dialog, returning you to the calling activity.

Using grep to search for a string that has a dot in it

grep -F -r '0.49' * treats 0.49 as a "fixed" string instead of a regular expression. This makes . lose its special meaning.

Bootstrap 3 and Youtube in Modal

Using LATEST Bootstrap 4.5+

  • Use the same modal repeatedly by passing different Youtube URL's from the HTML Page
  • With a great Play button icon and Autoplay enabled
  • Just COPY the code and you are all SET!!!
  • View solution in Codepen

_x000D_
_x000D_
    // javascript using jQuery - can embed in the script tag
$(".video-link").click(function () {
  var theModal = $(this).data("target");
  videoSRC = $(this).attr("data-video");
  videoSRCauto = videoSRC + "?modestbranding=1&rel=0&showinfo=0&html5=1&autoplay=1";
  $(theModal + ' iframe').attr('src', videoSRCauto);
  $(theModal + ' button.close').click(function () {
    $(theModal + ' iframe').attr('src', videoSRC);
  });
});
_x000D_
#video-section .modal-content {
  min-width: 600px;
}

#video-section .modal-content iframe {
  width: 560px;
  height: 315px;
}
_x000D_
<!-- HTML with Bootstrap 4.5 and Fontawesome -->
<html>
   <head>
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css"
         integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
   </head>

   <body>
      <section id="video-section" class="py-5 text-center text-white">
         <div class="container h-100 d-flex justify-content-center">
            <div class="row align-self-center">
               <div class="col">
                  <div class="card bg-dark border-0 mb-2 text-white">
                     <div class="card-body">
                        <a href="#" class="btn btn-primary bg-dark stretched-link video-link" data-video="https://www.youtube.com/embed/HnwsG9a5riA" data-toggle="modal" data-target="#video-modal">
                        <i class="fas fa-play fa-3x"></i>
                        </a>
                        <h1 class="card-title">Play Video</h1>
                     </div>
                  </div>
               </div>
            </div>
         </div>

         <!-- Video Modal -->
         <div class="modal fade" id="video-modal" tabindex="-1" role="dialog">
            <div class="modal-dialog h-100 d-flex align-items-center">
               <div class="modal-content">
                  <div class="modal-body">
                     <button type="button" class="close" data-dismiss="modal">
                     <span>&times;</span>
                     </button>
                     <iframe frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                  </div>
               </div>
            </div>
         </div>
      </section>

      <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

   </body>
</html>
_x000D_
_x000D_
_x000D_



  [1]: https://codepen.io/richierich25/pen/yLOOYBL

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

Can you require two form fields to match with HTML5?

The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'. This will only be visible if developer tools are open but it still doesn't seem like a good idea.

Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.

I also think these methods won't work well if the user switches between inputs.

Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.

For a real page you would change the input types to 'password'.

<form>
    <input type="text" id="password1" oninput="setPasswordConfirmValidity();">
    <input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
    function setPasswordConfirmValidity(str) {
        const password1 = document.getElementById('password1');
        const password2 = document.getElementById('password2');

        if (password1.value === password2.value) {
             password2.setCustomValidity('');
        } else {
            password2.setCustomValidity('Passwords must match');
        }
        console.log('password2 customError ', document.getElementById('password2').validity.customError);
        console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
    }
</script>

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

How can I simulate an anchor click via jquery?

Although this is very old question i found something easier to handle this task. It is jquery plugin developed by jquery UI team called simulate. you can include it after jquery and then you can do something like

<a href="http://stackoverflow.com/"></a>
$('a').simulate('click');

works fine in chrome, firefox, opera and IE10.you can download it from https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js

jquery UI dialog: how to initialize without a title bar?

go to your jquery-ui.js (in my case jquery-ui-1.10.3.custom.js) and search for this._createTitlebar(); and comment it.

now anyone of yours dialog will appear with headers. If you want to customize the header just go to _createTitlebar(); and edit the code inside.

by

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

MessageBodyWriter not found for media type=application/json

In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:

  1. you have jersey-media-json-jackson in you pom.xml if using maven or added to your build path;
  2. you have an empty constructor in the data type you are trying to de-/serialize;
  3. you have the relevant annotation at the class and field level for your custom data type (xmlelement and/or jsonproperty);

However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:

GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
return Response.status(httpCode).entity(entity).build();

This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain

So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.

sh: react-scripts: command not found after running npm start

I just randomly experienced this "react-scripts: command not found" error after issuing a react-scripts build request, which was previously working just fine.

A simple reboot of my system corrected the issue.

Unable to resolve host "<URL here>" No address associated with host name

I had the same issue. My virtual device was showing a crossed-out WiFi icon at the top bar of the device. I rebooted the virtual device and everything was back to normal.

Location of WSDL.exe

And on my Windows 7 machine it is here:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools

Note that the file wsdl.exe is portable, in that you can copy it to another windows machine and it works. I have not tried to see if the 4.5 exe will work on a machine that only have .NET 2.0, but this would be interesting to know.

How a thread should close itself in Java?

Thread is a class, not an instance; currentThread() is a static method that returns the Thread instance corresponding to the calling thread.

Use (2). interrupt() is a bit brutal for normal use.

How do I create directory if it doesn't exist to create a file?

You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional information for basic file I/O concepts.

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.

server error:405 - HTTP verb used to access this page is not allowed

In my case, IIS was fine but.. uh.. all the files in the folder except web.config had been deleted (a manual deployment half-done on a test site).

File URL "Not allowed to load local resource" in the Internet Browser

You just need to replace all image network paths to byte strings in HTML string. For this first you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

        // Decode the encoded string.
        StringWriter myWriter = new StringWriter();
        HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
        string DecodedHtmlString = myWriter.ToString();

        //find and replace each img src with byte string
         HtmlDocument document = new HtmlDocument();
         document.LoadHtml(DecodedHtmlString);
         document.DocumentNode.Descendants("img")
          .Where(e =>
        {
            string src = e.GetAttributeValue("src", null) ?? "";
            return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
        })
        .ToList()
                    .ForEach(x =>
                    {
                        string currentSrcValue = x.GetAttributeValue("src", null);                                
                        string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                        string filename = Path.GetFileName(currentSrcValue);
                        string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                        FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        br.Close();
                        fs.Close();
                        x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                    });

        string result = document.DocumentNode.OuterHtml;
        //Encode HTML string
        string myEncodedString = HttpUtility.HtmlEncode(result);

        Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

using if else with eval in aspx page

<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

How to get current time in milliseconds in PHP?

Use this:

function get_millis(){
  list($usec, $sec) = explode(' ', microtime());
  return (int) ((int) $sec * 1000 + ((float) $usec * 1000));
}

Bye

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

You need to paste these two in your info.plist, The only way that worked in iOS 11 for me.

    <key>NSPhotoLibraryUsageDescription</key>
    <string>This app requires access to the photo library.</string>

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>This app requires access to the photo library.</string>

Convert String with Dot or Comma as decimal separator to number in JavaScript

Do a replace first:

parseFloat(str.replace(',','.').replace(' ',''))

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

Python Infinity - Any caveats?

So does C99.

The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).

All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.

Display more Text in fullcalendar

I needed the ability to display quite a bit of info (without a tooltip) and it turned out quite nice. I used FullCalendars title prop to store all my HTML. The only thing you have to do to ensure it works after render is to parse the title fields HTML.

// `data` ismy JSON object.
$.each(data, function(index, value) {
  value.title = '<div class="title">' + value.title + '</div>';
  value.title += '<div class="deets"><span class="time"><img src="/themes/custom/bp/images/clock.svg">' + value.start_time + ' - ' + value.end_time + '</span>';
  value.title += '<span class="location"><img src="/themes/custom/bp/images/pin.svg">' + value.location + '</span></div>';
  value.title += '<div class="learn-more">LEARN MORE <span class="arrow"></span></span>';
});

// Initialize the calendar object.
calendar = new FullCalendar.Calendar(cal, {
  events: data,
  plugins: ['dayGrid'],
  eventRender: function(event) {
    // This is required to parse the HTML.
    const title = $(event.el).find('.fc-title');
    title.html(title.text());
  }
});
calendar.render();

I would have used template literals, but had to support IE11

calender

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for usersontxt.php;

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for create_userson.php:

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. Now we create the script that Inserts, Deletes, and Selects data in the userson table (For explanations about the code, see the comments in script).
  • Add the code below in another php file (named usersmysql.php): In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .

The code for usersmysql.php:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.

  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>

Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5

Visitors: 3 Users: 2

  • MarPlo
  • Marius

Delete all files in directory (but not directory) - one liner solution

Another Java 8 Stream solution to delete all the content of a folder, sub directories included, but not the folder itself.

Usage:

Path folder = Paths.get("/tmp/folder");
CleanFolder.clean(folder);

and the code:

public interface CleanFolder {
    static void clean(Path folder) throws IOException {

        Function<Path, Stream<Path>> walk = p -> {
            try { return Files.walk(p);
        } catch (IOException e) {
            return Stream.empty();
        }};

        Consumer<Path> delete = p -> {
            try {
                Files.delete(p);
            } catch (IOException e) {
            }
        };

        Files.list(folder)
            .flatMap(walk)
            .sorted(Comparator.reverseOrder())
            .forEach(delete);
    }
}

The problem with every stream solution involving Files.walk or Files.delete is that these methods throws IOException which are a pain to handle in streams.

I tried to create a solution which is more concise as possible.

What's the difference between passing by reference vs. passing by value?

Here is an example that demonstrates the differences between pass by value - pointer value - reference:

void swap_by_value(int a, int b){
    int temp;

    temp = a;
    a = b;
    b = temp;
}   
void swap_by_pointer(int *a, int *b){
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}    
void swap_by_reference(int &a, int &b){
    int temp;

    temp = a;
    a = b;
    b = temp;
}

int main(void){
    int arg1 = 1, arg2 = 2;

    swap_by_value(arg1, arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 1 2

    swap_by_pointer(&arg1, &arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 2 1

    arg1 = 1;                               //reset values
    arg2 = 2;
    swap_by_reference(arg1, arg2);
    cout << arg1 << " " << arg2 << endl;    //prints 2 1
}

The “passing by reference” method has an important limitation. If a parameter is declared as passed by reference (so it is preceded by the & sign) its corresponding actual parameter must be a variable.

An actual parameter referring to “passed by value” formal parameter may be an expression in general, so it is allowed to use not only a variable but also a literal or even a function invocation's result.

The function is not able to place a value in something other than a variable. It cannot assign a new value to a literal or force an expression to change its result.

PS: You can also check Dylan Beattie answer in the current thread that explains it in plain words.

Any reason not to use '+' to concatenate two strings?

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.

OSError: [Errno 8] Exec format error

It wouldn't be wrong to mention that Pexpect does throw a similar error

#python -c "import pexpect; p=pexpect.spawn('/usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 430, in __init__
    self._spawn (command, args)
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 560, in _spawn
    os.execv(self.command, self.args)
OSError: [Errno 8] Exec format error

Over here, the openssl_1.1.0f file at the specified path has exec command specified in it and is running the actual openssl binary when called.

Usually, I wouldn't mention this unless I have the root cause, but this problem was not there earlier. Unable to find the similar problem, the closest explanation to make it work is the same as the one provided by @jfs above.

what worked for me is both

  • adding /bin/bash at the beginning of the command or file you are
    facing the problem with, or
  • adding shebang #!/bin/sh as the first line.

for ex.

#python -c "import pexpect; p=pexpect.spawn('/bin/bash /usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
OpenSSL 1.1.0f  25 May 2017

SSH SCP Local file to Remote in Terminal Mac Os X

At first, you need to add : after the IP address to indicate the path is following:

scp magento.tar.gz [email protected]:/var/www

I don't think you need to sudo the scp. In this case it doesn't affect the remote machine, only the local command.

Then if your user@xx.x.x.xx doesn't have write access to /var/www then you need to do it in 2 times:

Copy to remote server in your home folder (: represents your remote home folder, use :subfolder/ if needed, or :/home/user/ for full path):

scp magento.tar.gz [email protected]:

Then SSH and move the file:

ssh [email protected]
sudo mv magento.tar.gz /var/www

Selenium WebDriver can't find element by link text

This doesn't seem to have <a> </a> tags so selenium might not be able to detect it as a link.

You may try and use

driver.findElement(By.xpath("//*[@class='ng-binding']")).click();

if this is the only element in that page with this class .

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

Regarding 'main(int argc, char *argv[])'

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

Java SSLHandshakeException "no cipher suites in common"

It looks like you are trying to connect using TLSv1.2, which isn't widely implemented on servers. Does your destination support tls1.2?

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

In my experience, to use wmic in a script, you need to get the nested quoting right:

wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive 

quoting both the query and the name. But wmic will only uninstall things installed via windows installer.

How to delete cookies on an ASP.NET website

You have to set the expiration date to delete cookies

Request.Cookies[yourCookie]?.Expires.Equals(DateTime.Now.AddYears(-1));

This won't throw an exception if the cookie doesn't exist.

Compiling with g++ using multiple cores

There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la

make -j4

Or you can use pmake or similar parallel make systems.

Display tooltip on Label's hover?

Tooltips in bootstrap are good, but there is also a very good tooltip function in jQuery UI, which you can read about here.

Example:

<label for="male" id="foo" title="Hello This Will Have Some Value">Hello...</label>

Then, assuming you have already referenced jQuery and jQueryUI libraries in your head, add a script element like this:

<script type="text/javascript">
$(document).ready(function(){
    $(this).tooltip();
});
</script>

This will display the contents of the title attribute as a tooltip when you rollover any element with a title attribute.

Quick way to list all files in Amazon S3 bucket?

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

What is "Advanced" SQL?

I would expect:

  • stored procedure creation and usage
  • joins (inner and outer) and how to correctly use GROUP BY
  • performance evaluation/tuning
  • knowledge of efficient (and inefficient) ways of doing things in queries (understanding how certain things can affect performance, e.g. using functions in WHERE clauses)
  • dynamic SQL and knowledge of cursors (and IMO the few times they should be used)
  • understanding of schema design, indexing, and referential integrity

How to drop a PostgreSQL database if there are active connections to it?

PostgreSQL 9.2 and above:

SELECT pg_terminate_backend(pid)FROM pg_stat_activity WHERE datname = 'YOUR_DATABASE_NAME_HERE'

Undefined function mysql_connect()

If someone came here with the problem of docker php official images, type below command inside the docker container.

$ docker-php-ext-install mysql mysqli pdo pdo_mysql

For more information, please refer to the link above How to install more PHP extensions section(But it's a bit difficult for me...).

Or this doc may help you.

https://docs.docker.com/samples/library/php/

Make selected block of text uppercase

Creator of the change-case extension here. I've updated the extension to support spanning lines.

To map the upper case command to a keybinding (e.g. CTRL+T+U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t ctrl+u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}

EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings. They also work with multi-line blocks.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake_case, kebab-case, etc.

Converting unix timestamp string to readable date

i just successfully used:

>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date

hadoop No FileSystem for scheme: file

Assuming that you are using mvn and cloudera distribution of hadoop. I'm using cdh4.6 and adding these dependencies worked for me.I think you should check the versions of hadoop and mvn dependencies.

<dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>2.0.0-mr1-cdh4.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.0.0-cdh4.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>2.0.0-cdh4.6.0</version>
    </dependency>

don't forget to add cloudera mvn repository.

<repository>
        <id>cloudera</id>
        <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>

What is the difference between re.search and re.match?

re.match attempts to match a pattern at the beginning of the string. re.search attempts to match the pattern throughout the string until it finds a match.

Route [login] not defined

Am late to the party. if your expectation is some sort of json returned other than being redirected, then edit the exception handler so do just that.

Go to go to App\Exceptions\Handler.php Then edit this code:

public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

to

public function render($request, Exception $exception)
    {
        return response()->json(
            [
                'errors' => [
                    'status' => 401,
                    'message' => 'Unauthenticated',
                ]
            ], 401
        );
    }

System.BadImageFormatException An attempt was made to load a program with an incorrect format

i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem

MySQL SELECT query string matching

Just turn the LIKE around

SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')

Best way to add Gradle support to IntelliJ Project

Add:

build.gradle 

in your root project folder, and use plugin for example:

apply plugin: 'idea'
//and standard one
apply plugin: 'java'

and with this fire from command line:

gradle cleanIdea 

and after that:

gradle idea

After that everything should work

Initialising a multidimensional array in Java

You can also use the following construct:

String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                             { "X1", "Y1"},
                                             { "X2", "Y2"},
                                             { "X3", "Y3"},
                                             { "X4", "Y4"} };

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case I had two issues...

1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"

enter image description here

2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

enter image description here

Calling jQuery method from onClick attribute in HTML

I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $button = $('<input id="1" type="button" value="ahaha" />');_x000D_
  $('body').append($button);_x000D_
  $button.click(function() {_x000D_
    console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
_x000D_
_x000D_

Recursive file search using PowerShell

Use the Get-ChildItem cmdlet with the -Recurse switch:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

Regular expression field validation in jQuery

A simple nowadays example:

$('#some_input_id').attr('oninput',
"this.value=this.value.replace(/[^0-9A-Za-z\s_-]/g,'');")

that means all that doesnt match regex becomes nothing , i.e. ''

AsyncTask Android example

You need to declare the button onclicklistener. Once clicked, it calls AsyncTask class DownloadJson.

The process will be shown below:

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

        btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DownloadJson().execute();
            }
        });
    }

    // DownloadJSON AsyncTask
    private class DownloadJson extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            newlist = new ArrayList<HashMap<String, String>>();
            json = jsonParser.makeHttpRequest(json, "POST");
            try {
                newarray = new JSONArray(json);
                    for (int i = 0; i < countdisplay; i++) {
                        HashMap<String, String> eachnew = new HashMap<String, String>();
                        newobject = newarray.getJSONObject(i);
                        eachnew.put("id", newobject.getString("ID"));
                        eachnew.put("name", newobject.getString("Name"));
                        newlist.add(eachnew);
                    }
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            newlisttemp.addAll(newlist);
            NewAdapterpager newadapterpager = new NewAdapterpager(ProcesssActivitypager.this, newlisttemp);
            newpager.setAdapter(newadapterpager);
        }
    }

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.

How to execute logic on Optional if not present?

You will have to split this into multiple statements. Here is one way to do that:

if (!obj.isPresent()) {
  logger.fatal("Object not available");
}

obj.ifPresent(o -> o.setAvailable(true));
return obj;

Another way (possibly over-engineered) is to use map:

if (!obj.isPresent()) {
  logger.fatal("Object not available");
}

return obj.map(o -> {o.setAvailable(true); return o;});

If obj.setAvailable conveniently returns obj, then you can simply the second example to:

if (!obj.isPresent()) {
  logger.fatal("Object not available");
}

return obj.map(o -> o.setAvailable(true));

How to split a string with any whitespace chars as delimiters

String str = "Hello   World";
String res[] = str.split("\\s+");

How to resize images proportionally / keeping the aspect ratio?

After some trial and error I came to this solution:

function center(img) {
    var div = img.parentNode;
    var divW = parseInt(div.style.width);
    var divH = parseInt(div.style.height);
    var srcW = img.width;
    var srcH = img.height;
    var ratio = Math.min(divW/srcW, divH/srcH);
    var newW = img.width * ratio;
    var newH = img.height * ratio;
    img.style.width  = newW + "px";
    img.style.height = newH + "px";
    img.style.marginTop = (divH-newH)/2 + "px";
    img.style.marginLeft = (divW-newW)/2 + "px";
}

I'm getting favicon.ico error

It's a nightmare since each browser/device handles it differently.

Favicon generator helps me a lot for those applications where we need to cover the most possible scenarios.

https://realfavicongenerator.net/

You just need a png image 260px x 260px (at least) and from there the generator will create all references you need within your web page.

You just need to add this references and images to your application.

enter image description here

Giving my function access to outside variable

Two Answers

1. Answer to the asked question.

2. A simple change equals a better way!

Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.

<?php

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();

// Create a Class
class Array_Pushing_Example_1 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Primary Contents Array as Parameter in __construct
    public function __construct($content_arrays){

        // Declare it
        $this->content_arrays = $content_arrays;

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.

<?php

// Create a Class
class Array_Pushing_Example_2 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Declare Contents Array and Sub Arrays in __construct
    public function __construct(){

        // Declare them
        $this->content_arrays["modals"] = array();
        $this->content_arrays["js_custom"] = array();

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).

Output:

Array Custom Content Results

Modals - Count: 5

a

b

c

FOO

foo

JS Custom - Count: 9

1

2B or not 2B

3

42

5

car

house

bike

glass

How to extract file name from path?

The simplest approach if you are sure the file physically exists on the disk:

Dim fileName, filePath As String
filePath = "C:\Documents\myfile.pdf"
fileName = Dir(filePath)

If you are not sure about existence of file or just want to extract filename from a given path then, simplest approach is:

fileName = Mid(filePath, InStrRev(filePath, "\") + 1)

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

The best answer I got was exporting your key, instead of just trying to import the cert file.

When you export the key from the keychain that generated the request, you get a Certificates.p12 file, which rolls the keys you need together.

Then import this into the new computer.

With keys like this, it's probably good to keep a rolled, certificate package file, because many times the "public" key, or cert file, is not enough to restore things from.

Headers and client library minor version mismatch

If u had access cpanel or whm for domain web hosting ...

In cPanel, Go to "Softwares and services" tab, >> and then click "Select PHP Version" >> set your desired version of php...

Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:50547 Library:50628 in chennaitechnologies.com

Eg. Current PHP version:

PHP Version [5.2] ( list of 5.2, 5.3, 5.4, 5.5, 5.6 available php versions)

Warning: Changing php modules and php options via PHP Selector for native php version is impossible

I selected 5.6 php version, after that error cleared on my wordpress blog site...

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

How do I link a JavaScript file to a HTML file?

To include an external Javascript file you use the <script> tag. The src attribute points to the location of your Javascript file within your web project.

<script src="some.js" type="text/javascript"></script>

JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

How to record phone calls in android?

Below code is working for me to record a outgoing phone call

//Call Recording varibales
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";

private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
        MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
        AUDIO_RECORDER_FILE_EXT_3GP };

AudioManager audioManager;

//put this methods to outside of oncreate() method

private String getFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, AUDIO_RECORDER_FOLDER);

    if (!file.exists()) {
        file.mkdirs();
    }

    return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
                .show();
    }
};

//below part of code to make your device on speaker

    audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE); 
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    audioManager.setSpeakerphoneOn(true);

//below part of code to start recording

recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(output_formats[currentFormat]);
    //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(getFilename());
    recorder.setOnErrorListener(errorListener);
    recorder.setOnInfoListener(infoListener);

    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException e) {
         Log.e("REDORDING :: ",e.getMessage());
            e.printStackTrace();
    } catch (IOException e) {
        Log.e("REDORDING :: ",e.getMessage());
        e.printStackTrace();
    }

//For stop recording and keep in mind to set speaker off while call end or stop

audioManager.setSpeakerphoneOn(false);

    try{
        if (null != recorder) {
            recorder.stop();
            recorder.reset();
            recorder.release();

            recorder = null;
        }
    }catch(RuntimeException stopException){

    }

And give permission to manifest file,

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

Could not load type 'XXX.Global'

Ensure compiled dll of your project placed in proper bin folder.

In my case, when i have changed the compiled directory of our subproject to bin folder of our main project, it worked.

Access properties file programmatically with Spring?

If all you want to do is access placeholder value from code, there is the @Value annotation:

@Value("${settings.some.property}")
String someValue;

To access placeholders From SPEL use this syntax:

#('${settings.some.property}')

To expose configuration to views that have SPEL turned off, one can use this trick:

package com.my.app;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.stereotype.Component;

@Component
public class PropertyPlaceholderExposer implements Map<String, String>, BeanFactoryAware {  
    ConfigurableBeanFactory beanFactory; 

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (ConfigurableBeanFactory) beanFactory;
    }

    protected String resolveProperty(String name) {
        String rv = beanFactory.resolveEmbeddedValue("${" + name + "}");

        return rv;
    }

    @Override
    public String get(Object key) {
        return resolveProperty(key.toString());
    }

    @Override
    public boolean containsKey(Object key) {
        try {
            resolveProperty(key.toString());
            return true;
        }
        catch(Exception e) {
            return false;
        }
    }

    @Override public boolean isEmpty() { return false; }
    @Override public Set<String> keySet() { throw new UnsupportedOperationException(); }
    @Override public Set<java.util.Map.Entry<String, String>> entrySet() { throw new UnsupportedOperationException(); }
    @Override public Collection<String> values() { throw new UnsupportedOperationException(); }
    @Override public int size() { throw new UnsupportedOperationException(); }
    @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); }
    @Override public void clear() { throw new UnsupportedOperationException(); }
    @Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
    @Override public String remove(Object key) { throw new UnsupportedOperationException(); }
    @Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}

And then use the exposer to expose properties to a view:

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    <property name="attributesMap">
        <map>
            <entry key="config">
                <bean class="com.my.app.PropertyPlaceholderExposer" />
            </entry>
        </map>
    </property>
</bean>

Then in view, use the exposed properties like this:

${config['settings.some.property']}

This solution has the advantage that you can rely on standard placeholder implementation injected by the context:property-placeholder tag.

Now as a final note, if you really need a to capture all placeholder properties and their values, you have to pipe them through StringValueResolver to make sure that placeholders work inside the property values as expected. The following code will do that.

package com.my.app;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.StringValueResolver;

public class AppConfig extends PropertyPlaceholderConfigurer implements Map<String, String> {

    Map<String, String> props = new HashMap<String, String>();

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
            throws BeansException {

        this.props.clear();
        for (Entry<Object, Object> e: props.entrySet())
            this.props.put(e.getKey().toString(), e.getValue().toString());

        super.processProperties(beanFactory, props);
    }

    @Override
    protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
            StringValueResolver valueResolver) {

        super.doProcessProperties(beanFactoryToProcess, valueResolver);

        for(Entry<String, String> e: props.entrySet())
            e.setValue(valueResolver.resolveStringValue(e.getValue()));
    }

    // Implement map interface to access stored properties
    @Override public Set<String> keySet() { return props.keySet(); }
    @Override public Set<java.util.Map.Entry<String, String>> entrySet() { return props.entrySet(); }
    @Override public Collection<String> values() { return props.values(); }
    @Override public int size() { return props.size(); }
    @Override public boolean isEmpty() { return props.isEmpty(); }
    @Override public boolean containsValue(Object value) { return props.containsValue(value); }
    @Override public boolean containsKey(Object key) { return props.containsKey(key); }
    @Override public String get(Object key) { return props.get(key); }
    @Override public void clear() { throw new UnsupportedOperationException(); }
    @Override public String put(String key, String value) { throw new UnsupportedOperationException(); }
    @Override public String remove(Object key) { throw new UnsupportedOperationException(); }
    @Override public void putAll(Map<? extends String, ? extends String> t) { throw new UnsupportedOperationException(); }
}

In Python, how do you convert a `datetime` object to seconds?

To convert a datetime object that represents time in UTC to POSIX timestamp:

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

To convert a datetime object that represents time in the local timezone to POSIX timestamp:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.

Follow the links if you need solutions for <3.3 Python versions.

How to define Gradle's home in IDEA?

In case you are using Mac, most probably your gradle home should be /usr/local/gradle-2.0 for example.

In preference of IDEA search for gradle and set gradle home as given above. It should work

Converting an int or String to a char array on Arduino

None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...

String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string

str = str + '\r' + '\n'; // Add the required carriage return, optional line feed

byte str_len = str.length();

// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...

byte arrayPointer = 0;

while (str_len)
{
    // I was outputting the digits to the TX buffer

    if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
    {
        UDR0 = str[arrayPointer];
        --str_len;
        ++arrayPointer;
    }
}

Retrieve the commit log for a specific line in a file?

See also Git: discover which commits ever touched a range of lines.


Since Git 1.8.4, git log has -L to view the evolution of a range of lines.

For example, suppose you look at git blame's output. Here -L 150,+11 means "only look at the lines 150 to 150+11":

$ git blame -L 150,+11 -- git-web--browse.sh
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 150)            die "The browser $browser is not
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 151)    fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 152) fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 153) 
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 154) case "$browser" in
81f42f11 git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:38 +0100 155) firefox|iceweasel|seamonkey|iceape)
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 156)    # Check version because firefox < 2.0 do
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 157)    vers=$(expr "$($browser_path -version)" 
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 158)    NEWTAB='-new-tab'
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 159)    test "$vers" -lt 2 && NEWTAB=''
a0685a4f git-web--browse.sh (Dmitry Potapov   2008-02-09 23:22:22 -0800 160)    "$browser_path" $NEWTAB "$@" &

And you want to know the history of what is now line 155.

Then, use git log. Here, -L 155,155:git-web--browse.sh means "trace the evolution of lines 155 to 155 in the file named git-web--browse.sh".

$ git log --pretty=short -u -L 155,155:git-web--browse.sh
commit 81f42f11496b9117273939c98d270af273c8a463
Author: Giuseppe Bilotta <[email protected]>

    web--browse: support opera, seamonkey and elinks

diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -143,1 +143,1 @@
-firefox|iceweasel)
+firefox|iceweasel|seamonkey|iceape)

commit a180055a47c6793eaaba6289f623cff32644215b
Author: Giuseppe Bilotta <[email protected]>

    web--browse: coding style

diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -142,1 +142,1 @@
-    firefox|iceweasel)
+firefox|iceweasel)

commit 5884f1fe96b33d9666a78e660042b1e3e5f9f4d9
Author: Christian Couder <[email protected]>

    Rename 'git-help--browse.sh' to 'git-web--browse.sh'.

diff --git a/git-web--browse.sh b/git-web--browse.sh
--- /dev/null
+++ b/git-web--browse.sh
@@ -0,0 +127,1 @@
+    firefox|iceweasel)

select a value where it doesn't exist in another table

SELECT ID 
  FROM A 
 WHERE NOT EXISTS( SELECT 1
                     FROM B
                    WHERE B.ID = A.ID
                 )

Issue pushing new code in Github

This error occurs when you push the data from your local directory to your remote git repository by following git command: git push -u origin master

As local directory and git remote directory's files conflicted.

Solution :

After committing all files to staging follow below steps.

  1. Fetch the files from the remote repository as its conflict with the local working directory.

    • git pull <remoter-url> <branch-name>
  2. Commit the changes again.

    • git add -A
    • git commit -m ‘<comment>'
  3. After committed merge files with both directory you can use

    • git push -u origin master

This will fix the issue. Thanks.

What is the Python equivalent of Matlab's tic and toc functions?

Updating Eli's answer to Python 3:

class Timer(object):
    def __init__(self, name=None, filename=None):
        self.name = name
        self.filename = filename

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
        if self.name:
            message = '[%s] ' % self.name + message
        print(message)
        if self.filename:
            with open(self.filename,'a') as file:
                print(str(datetime.datetime.now())+": ",message,file=file)

Just like Eli's, it can be used as a context manager:

import time 
with Timer('Count'):
    for i in range(0,10_000_000):
        pass

Output:

[Count] Elapsed: 0.27 seconds

I have also updated it to print the units of time reported (seconds) and trim the number of digits as suggested by Can, and with the option of also appending to a log file. You must import datetime to use the logging feature:

import time
import datetime 
with Timer('Count', 'log.txt'):    
    for i in range(0,10_000_000):
        pass

clear javascript console in Google Chrome

I use the following to alias cls when debugging locally in Chrome (enter the following JavaScript into the console):

Object.defineProperty(window, 'cls', {
    get: function () {
        return console.clear();
    }
});

now entering cls in the console will clear the console.

Create session factory in Hibernate 4

Configuration hibConfiguration = new Configuration()
            .addResource("wp4core/hibernate/config/table.hbm.xml")
            .configure();       

serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(hibConfiguration.getProperties())
            .buildServiceRegistry();

sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
session = sessionFactory.withOptions().openSession();

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Sort a Map<Key, Value> by values

Simple way to sort any map in Java 8 and above

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

List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());

Collections.sort(list, Comparator.comparing(o -> o.getValue().getAttribute()));

HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
   sortedMap.put(map.getKey(), map.getValue());
}

if you are using Java 7 and below

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

List<Map.Entry<String, Object>> list = new LinkedList<>(mapToSort.entrySet());

Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
    @Override
    public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
       return o1.getValue().getAttribute().compareTo(o2.getValue().getAttribute());      
    }
});

HashMap<String, Object> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> map : list) {
   sortedMap.put(map.getKey(), map.getValue());
}

How to add a right button to a UINavigationController?

-(void) viewWillAppear:(BOOL)animated
{

    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setFrame:CGRectMake(0, 0, 30, 44)];
    [btnRight setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [barBtnRight setTintColor:[UIColor whiteColor]];
    [[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];

}

Assign format of DateTime with data annotations?

Did you try this?

[DataType(DataType.Date)]

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \
      http://localhost:3570/index.php/trainingServer/screencast.json

and see if that helps any.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

Error : ORA-01704: string literal too long

INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
            TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

How to get array keys in Javascript?

I think you should use an Object ({}) and not an array ([]) for this.

A set of data is associated with each key. It screams for using an object. Do:

var obj = {};
obj[46] = { sel:46, min:0,  max:52 };
obj[666] = { whatever:true };

// This is what for..in is for
for (var prop in obj) {
  console.log(obj[prop]);
}

Maybe some utility stuff like this can help:

window.WidthRange = (function () {
  var obj = {};
  return {
    getObj: function () {return obj;}
    , add: function (key, data) {
        obj[key] = data;
        return this; // enabling chaining
      }
  }
})();

// Usage (using chaining calls):
WidthRange.add(66, {foo: true})
.add(67, {bar: false})
.add(69, {baz: 'maybe', bork:'absolutely'});

var obj = WidthRange.getObj();
for (var prop in obj) {
  console.log(obj[prop]);
}

Zookeeper connection error

I start standalone instance in my machine, and encounter the same problem. Finally, I change from ip "127.0.0.1" to "localhost" and the problem is gone.

numbers not allowed (0-9) - Regex Expression in javascript

Like this: ^[^0-9]+$

Explanation:

  • ^ matches the beginning of the string
  • [^...] matches anything that isn't inside
  • 0-9 means any character between 0 and 9
  • + matches one or more of the previous thing
  • $ matches the end of the string

How to get primary key of table?

If you want to generate the list of primary keys dynamically via PHP in one go without having to run through each table you can use

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.key_column_usage 
WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY' 

though you do need to have access to the information.schema to do this.

how to fire event on file select

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

How can I completely remove TFS Bindings

File -> Source Control -> Advanced -> Change Source Control and then unbind and/or disconnect all projects and the solution.

This should remove all bindings from the solution and project files. (After this you can switch the SCC provider in Tools -> Options -> Source Control -> Plug-in Selection).

The SCC specification prescribes that all SCC providers should implement this behavior. (I only tested it for VSS, TFS and AnkhSVN)

Disable a textbox using CSS

**just copy paste this code and run you can see the textbox disabled **

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title> 

<style>.container{float:left;width:200px;height:25px;position:relative;}
       .container input{float:left;width:200px;height:25px;}
       .overlay{display:block;width:208px;position:absolute;top:0px;left:0px;height:32px;} 
</style>
 </head>
<body>
      <div class="container">
       <input type="text" value="[email protected]" />
       <div class="overlay">
        </div>
       </div> 
</body>
</html>

Start systemd service after specific service?

In the .service file under the [Unit] section:

[Unit]
Description=My Website
After=syslog.target network.target mongodb.service

The important part is the mongodb.service

The manpage describes it however due to formatting it's not as clear on first sight

systemd.unit - well formatted

systemd.unit - not so well formatted

AngularJS: how to implement a simple file upload with multipart form?

I just had this issue. So there are a few approaches. The first is that new browsers support the

var formData = new FormData();

Follow this link to a blog with info about how support is limited to modern browsers but otherwise it totally solves this issue.

Otherwise you can post the form to an iframe using the target attribute. When you post the form be sure to set the target to an iframe with its display property set to none. The target is the name of the iframe. (Just so you know.)

I hope this helps

How do I apply CSS3 transition to all properties except background-position?

Hope not to be late. It is accomplished using only one line!

-webkit-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-moz-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
-o-transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0;
transition: all 0.2s ease-in-out, width 0, height 0, top 0, left 0; 

That works on Chrome. You have to separate the CSS properties with a comma.

Here is a working example: http://jsfiddle.net/H2jet/

HTML Canvas Full Screen

The javascript has

var canvasW     = 640;
var canvasH     = 480;

in it. Try changing those as well as the css for the canvas.

Or better yet, have the initialize function determine the size of the canvas from the css!

in response to your edits, change your init function:

function init()
{
    canvas = document.getElementById("mainCanvas");
    canvas.width = document.body.clientWidth; //document.width is obsolete
    canvas.height = document.body.clientHeight; //document.height is obsolete
    canvasW = canvas.width;
    canvasH = canvas.height;

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.

html, body {
    overflow: hidden;
}

Edit: document.width and document.height are obsolete. Replace with document.body.clientWidth and document.body.clientHeight

How to read an external local JSON file in JavaScript?

You must create a new XMLHttpRequest instance and load the contents of the json file.

This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):

 function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

 loadJSON(function(response) {
    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });

How to use GROUP_CONCAT in a CONCAT in MySQL

First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table. Second there is no need for subqueries, which beats up the server. You do this in one query, like this

SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id

You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique. There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better. Like this :

SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name

Why does .json() return a promise?

In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:

function callApi(url) {
  return fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json().then(response => ({ response }));
      }

      return response.json().then(error => ({ error }));
    })
  ;
}

let url = 'http://jsonplaceholder.typicode.com/posts/6';

const { response, error } = callApi(url);
if (response) {
  // handle json decoded response
} else {
  // handle json decoded 500 series response
}

What is the best way to paginate results in SQL Server

There is a good overview of different paging techniques at http://www.codeproject.com/KB/aspnet/PagingLarge.aspx

I've used ROWCOUNT method quite often mostly with SQL Server 2000 (will work with 2005 & 2008 too, just measure performance compared to ROW_NUMBER), it's lightning fast, but you need to make sure that the sorted column(s) have (mostly) unique values.

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

What worked for me:

  1. Add a folder to the project call it ThirdParty.
  2. Add in the ThirdParty folder both DocumentFormat.OpenXML.dll and WindowsBase.dll
  3. Make sure the the project uses the ThirdParty dir as reference for both the DLLs
  4. Build and published to an external server.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

The difference between fork(), vfork(), exec() and clone()

  • execve() replaces the current executable image with another one loaded from an executable file.
  • fork() creates a child process.
  • vfork() is a historical optimized version of fork(), meant to be used when execve() is called directly after fork(). It turned out to work well in non-MMU systems (where fork() cannot work in an efficient manner) and when fork()ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()). POSIX has standardized the posix_spawn() to replace these latter two more modern uses of vfork().
  • posix_spawn() does the equivalent of a fork()/execve(), and also allows some fd juggling in between. It's supposed to replace fork()/execve(), mainly for non-MMU platforms.
  • pthread_create() creates a new thread.
  • clone() is a Linux-specific call, which can be used to implement anything from fork() to pthread_create(). It gives a lot of control. Inspired on rfork().
  • rfork() is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.

How can I show an element that has display: none in a CSS rule?

I can see that you want to write you own short javascript for this, but have you considered to use Frameworks for HTML manipulation instead? jQuery is my prefered tool for such a task, eventhough its an overkill for your current question as it has SO many extra functionalities.

Have a look at jQuery here

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

Pandas: Looking up the list of sheets in an excel file

I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.

Correctly Parsing JSON in Swift 3

First of all never load data synchronously from a remote URL, use always asynchronous methods like URLSession.

'Any' has no subscript members

occurs because the compiler has no idea of what type the intermediate objects are (for example currently in ["currently"]!["temperature"]) and since you are using Foundation collection types like NSDictionary the compiler has no idea at all about the type.

Additionally in Swift 3 it's required to inform the compiler about the type of all subscripted objects.

You have to cast the result of the JSON serialization to the actual type.

This code uses URLSession and exclusively Swift native types

let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
  if error != nil {
    print(error)
  } else {
    do {

      let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
      let currentConditions = parsedData["currently"] as! [String:Any]

      print(currentConditions)

      let currentTemperatureF = currentConditions["temperature"] as! Double
      print(currentTemperatureF)
    } catch let error as NSError {
      print(error)
    }
  }

}.resume()

To print all key / value pairs of currentConditions you could write

 let currentConditions = parsedData["currently"] as! [String:Any]

  for (key, value) in currentConditions {
    print("\(key) - \(value) ")
  }

A note regarding jsonObject(with data:

Many (it seems all) tutorials suggest .mutableContainers or .mutableLeaves options which is completely nonsense in Swift. The two options are legacy Objective-C options to assign the result to NSMutable... objects. In Swift any variable is mutable by default and passing any of those options and assigning the result to a let constant has no effect at all. Further most of the implementations are never mutating the deserialized JSON anyway.

The only (rare) option which is useful in Swift is .allowFragments which is required if if the JSON root object could be a value type(String, Number, Bool or null) rather than one of the collection types (array or dictionary). But normally omit the options parameter which means No options.

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

Some general considerations to parse JSON

JSON is a well-arranged text format. It's very easy to read a JSON string. Read the string carefully. There are only six different types – two collection types and four value types.


The collection types are

  • Array - JSON: objects in square brackets [] - Swift: [Any] but in most cases [[String:Any]]
  • Dictionary - JSON: objects in curly braces {} - Swift: [String:Any]

The value types are

  • String - JSON: any value in double quotes "Foo", even "123"or "false" – Swift: String
  • Number - JSON: numeric values not in double quotes 123 or 123.0 – Swift: Int or Double
  • Bool - JSON: true or false not in double quotes – Swift: true or false
  • null - JSON: null – Swift: NSNull

According to the JSON specification all keys in dictionaries are required to be String.


Basically it's always recommeded to use optional bindings to unwrap optionals safely

If the root object is a dictionary ({}) cast the type to [String:Any]

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] { ...

and retrieve values by keys with (OneOfSupportedJSONTypes is either JSON collection or value type as described above.)

if let foo = parsedData["foo"] as? OneOfSupportedJSONTypes {
    print(foo)
} 

If the root object is an array ([]) cast the type to [[String:Any]]

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] { ...

and iterate through the array with

for item in parsedData {
    print(item)
}

If you need an item at specific index check also if the index exists

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]], parsedData.count > 2,
   let item = parsedData[2] as? OneOfSupportedJSONTypes {
      print(item)
    }
}

In the rare case that the JSON is simply one of the value types – rather than a collection type – you have to pass the .allowFragments option and cast the result to the appropriate value type for example

if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String { ...

Apple has published a comprehensive article in the Swift Blog: Working with JSON in Swift


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

In Swift 4+ the Codable protocol provides a more convenient way to parse JSON directly into structs / classes.

For example the given JSON sample in the question (slightly modified)

let jsonString = """
{"icon": "partly-cloudy-night", "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precip_intensity": 0, "wind_speed": 6.04, "summary": "Partly Cloudy", "ozone": 321.13, "temperature": 49.45, "dew_point": 41.75, "apparent_temperature": 47, "wind_bearing": 332, "cloud_cover": 0.28, "time": 1480846460}
"""

can be decoded into the struct Weather. The Swift types are the same as described above. There are a few additional options:

  • Strings representing an URL can be decoded directly as URL.
  • The time integer can be decoded as Date with the dateDecodingStrategy .secondsSince1970.
  • snaked_cased JSON keys can be converted to camelCase with the keyDecodingStrategy .convertFromSnakeCase

struct Weather: Decodable {
    let icon, summary: String
    let pressure: Double, humidity, windSpeed : Double
    let ozone, temperature, dewPoint, cloudCover: Double
    let precipProbability, precipIntensity, apparentTemperature, windBearing : Int
    let time: Date
}

let data = Data(jsonString.utf8)
do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let result = try decoder.decode(Weather.self, from: data)
    print(result)
} catch {
    print(error)
}

Other Codable sources:

JSON Array iteration in Android/Java

You are using the same Cast object for every entry. On each iteration you just changed the same object instead creating a new one.

This code should fix it:

JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();

for (int i=0; i < jCastArr.length(); i++) {
    Cast person = new Cast();  // create a new object here
    JSONObject jpersonObj = jCastArr.getJSONObject(i);

    person.castId = (String) jpersonObj.getString("id");
    person.castFullName = (String) jpersonObj.getString("name");

    castList.add(person);
}
details.castList = castList;

What is the facade design pattern?

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

How do I specify "close existing connections" in sql script

try this C# code to drop your database

public static void DropDatabases(string dataBase) {

        string sql =  "ALTER DATABASE "  + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;

        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
        {
            connection.Open();
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
            sql = "DROP DATABASE " + dataBase;
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
        }
    }

Volley JsonObjectRequest Post request not working

I had the same issue once, the empty POST array is caused due a redirection of the request (on your server side), fix the URL so it doesn't have to be redirected when it hits the server. For Example, if https is forced using the .htaccess file on your server side app, make sure your client request has the "https://" prefix. Usually when a redirect happens the POST array is lost. I Hope this helps!

How can I recover the return value of a function passed to multiprocessing.Process?

I think the approach suggested by @sega_sai is the better one. But it really needs a code example, so here goes:

import multiprocessing
from os import getpid

def worker(procnum):
    print('I am number %d in process %d' % (procnum, getpid()))
    return getpid()

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print(pool.map(worker, range(5)))

Which will print the return values:

I am number 0 in process 19139
I am number 1 in process 19138
I am number 2 in process 19140
I am number 3 in process 19139
I am number 4 in process 19140
[19139, 19138, 19140, 19139, 19140]

If you are familiar with map (the Python 2 built-in) this should not be too challenging. Otherwise have a look at sega_Sai's link.

Note how little code is needed. (Also note how processes are re-used).

Error: Cannot invoke an expression whose type lacks a call signature

Add a type to your variable and then return.

Eg:

const myVariable : string [] = ['hello', 'there'];

const result = myVaraible.map(x=> {
  return
  {
    x.id
  }
});

=> Important part is adding the string[] type etc:

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

Line Break in XML?

At the end of your lines, simply add the following special character: &#xD;

That special character defines the carriage-return character.

PHP Curl And Cookies

You can specify the cookie file with a curl opt. You could use a unique file for each user.

curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );

The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.

    function fetch( $url, $z=null ) {
            $ch =  curl_init();

            $useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';

            curl_setopt( $ch, CURLOPT_URL, $url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
            curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );

            if( isset($z['post']) )         curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
            if( isset($z['refer']) )        curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );

            curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
            curl_setopt( $ch, CURLOPT_COOKIEJAR,  $z['cookiefile'] );
            curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );

            $result = curl_exec( $ch );
            curl_close( $ch );
            return $result;
    }

I use this for quick grabs. It takes the url and an array of options.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

make: Nothing to be done for `all'

That is not an error; the make command in unix works based on the timestamps. I.e let's say if you have made certain changes to factorial.cpp and compile using make then make shows the information that only the cc -o factorial.cpp command is executed. Next time if you execute the same command i.e make without making any changes to any file with .cpp extension the compiler says that the output file is up to date. The compiler gives this information until we make certain changes to any file.cpp.

The advantage of the makefile is that it reduces the recompiling time by compiling the only files that are modified and by using the object (.o) files of the unmodified files directly.

How can I get the list of files in a directory using C or C++?

you can get all direct of files in your root directory by using std::experimental:: filesystem::directory_iterator(). Then, read the name of these pathfiles.

#include <iostream>
#include <filesystem>
#include <string>
#include <direct.h>
using namespace std;
namespace fs = std::experimental::filesystem;
void ShowListFile(string path)
{
for(auto &p: fs::directory_iterator(path))  /*get directory */
     cout<<p.path().filename()<<endl;   // get file name
}

int main() {

ShowListFile("C:/Users/dell/Pictures/Camera Roll/");
getchar();
return 0;
}

Comparing Class Types in Java

If you don't want to or can't use instanceof, then compare with equals:

 if(obj.getClass().equals(MyObject.class)) System.out.println("true");

BTW - it's strange because the two Class instances in your statement really should be the same, at least in your example code. They may be different if:

  • the classes have the same short name but are defined in different packages
  • the classes have the same full name but are loaded by different classloaders.

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

Animate visibility modes, GONE and VISIBLE

There is no easy way to animate hiding/showing views. You can try method described in following answer: How do I animate View.setVisibility(GONE)

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

How to make Bootstrap carousel slider use mobile left/right swipe

I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).

It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.

This is how you use it:

$('.carousel').bcSwipe({ threshold: 50 });

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

For me its simple solution (Mac User)

_x000D_
_x000D_
  run in terminal -->   alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`;java -version"

then run -->          j8

thats it !!(now run your mvn commands)
_x000D_
_x000D_
_x000D_

Or you can set above in your .bash_profile

How to style the option of an html "select" element?

It's 2017 and it IS possible to target specific select options. In my project I have a table with a class="variations", and the select options are in the table cell td="value", and the select has an ID select#pa_color. The option element also has a class option="attached" (among other class tags). If a user is logged in as a wholesale customer, they can see all of the color options. But retail customers are not allowed to purchase 2 color options, so I've disabled them

<option class="attached" disabled>color 1</option>
<option class="attached" disabled>color 2</option>

It took a little logic, but here is how I targeted the disabled select options.

CSS

table.variations td.value select#pa_color option.attached:disabled {
display: none !important;
}

With that, my color options are only visible to wholesale customers.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Ok, I had the same problem just today and started googling it, when I came across this thread. I haven't finished reading the question when the answer struck my mind: I declared a class with an empty constructor

class MyClass{
    MyClass();

    void func_one(){
    // code
    }

    void func_two(){
    // code
    }

    ~MyClass(){
        cout << "Deleting object" << endl;
     }
};

Then I thought why not terminating (not sure if I'm correct with word selection here, but who cares) the constructor of my class with curly braces ({}). So I did:

class MyClass{
    MyClass(){}

    void func_one(){
    // code
    }

    void func_two(){
    // code
    }

    ~MyClass(){
        cout << "Deleting object" << endl;
     }
};

The problem eliminated, my code started working perfectly.

I know, the good practice is to investigate the issue and find the real cause, but this worked for me.

Pass table as parameter into sql server UDF

you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO

/*CREATE FUNCTION WHICH TAKES TABLE AS A PARAMETER */

CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO

/*CREATE STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER */

CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst 
  SELECT * FROM @TmpTable
END
GO


BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html

How to get a jqGrid selected row cells value

yo have to declarate de vars...

var selectedRowId = $('#list').jqGrid ('getGridParam', 'selrow');
var columnName = $('#list').jqGrid('getCell', selectedRowId, 'columnName');

var nombre_img_articulo = $('#list').jqGrid('getCell', selectedRowId, 'img_articulo');

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

We had a similar situation and we tried out given at the top of the answers ini_set('memory_limit', '-1'); and everything worked fine, compressed images files greater than 1MB to KBs.

Please initialize the log4j system properly. While running web service

If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:

yourproject/javaresoures/src/log4j.properties (Put inside src folder)

Integer value comparison

well i might be late on this but i would like to share something:

Given the input: System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true So i think in yourcase 'compareTo' will be more accurate.

Change CSS class properties with jQuery

Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.

function changeCss(className, classValue) {
    var cssMainContainer = $('#css-modifier-container');

    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<style id="css-modifier-container"></style>');
        cssMainContainer.appendTo($('head'));
    }

    cssMainContainer.append(className + " {" + classValue + "}\n");
}

About .bash_profile, .bashrc, and where should alias be written in?

The reason you separate the login and non-login shell is because the .bashrc file is reloaded every time you start a new copy of Bash. The .profile file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.

Personally,

  • I put my PATH setup into a .profile file (because I sometimes use other shells);
  • I put my Bash aliases and functions into my .bashrc file;
  • I put this

    #!/bin/bash
    #
    # CRM .bash_profile Time-stamp: "2008-12-07 19:42"
    #
    # echo "Loading ${HOME}/.bash_profile"
    source ~/.profile # get my PATH setup
    source ~/.bashrc  # get my Bash aliases
    

    in my .bash_profile file.

Oh, and the reason you need to type bash again to get the new alias is that Bash loads your .bashrc file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc file (and not need a second shell) by typing

source ~/.bashrc

which loads the .bashrc file as if you had typed the commands directly to Bash.

How to split a string between letters and digits (or between digits and letters)?

Didn't use Java for ages, so just some pseudo code, that should help get you started (faster for me than looking up everything :) ).

 string a = "123abc345def";
 string[] result;
 while(a.Length > 0)
 {
      string part;
      if((part = a.Match(/\d+/)).Length) // match digits
           ;
      else if((part = a.Match(/\a+/)).Length) // match letters
           ;
      else
           break; // something invalid - neither digit nor letter
      result.append(part);
      a = a.SubStr(part.Length - 1); // remove the part we've found
 }

Static methods in Python?

I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.

(Note that this answer refers to Python 3.x. In Python 2.x you'll get a TypeError for calling the method on the class itself.)

For example:

class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    def rollCall(n): #this is implicitly a class method (see comments below)
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)

In this code, the "rollCall" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as "rollCall" is called from the class rather than an instance, the code will work fine. If we try to call "rollCall" from an instance, e.g.:

rex.rollCall(-1)

however, it would cause an exception to be raised because it would send two arguments: itself and -1, and "rollCall" is only defined to accept one argument.

Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.

This is where the decoration comes in: If we precede the "rollCall" method with

@staticmethod

then, by explicitly stating that the method is static, we can even call it from an instance. Now,

rex.rollCall(-1)

would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.

You can verify this by trying the following code with and without the @staticmethod line commented out.

class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    @staticmethod
    def rollCall(n):
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))


fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)

How does inline Javascript (in HTML) work?

It looks suspicious because there is no apparent function that is being returned from!

It is an anonymous function that has been attached to the click event of the object.

why are you doing this, Steve?

Why on earth are you doi.....Ah nevermind, as you've mentioned, it really is widely adopted bad practice :)

Regular Expressions and negating a whole character group

Use negative lookahead:

^(?!.*ab).*$

UPDATE: In the comments below, I stated that this approach is slower than the one given in Peter's answer. I've run some tests since then, and found that it's really slightly faster. However, the reason to prefer this technique over the other is not speed, but simplicity.

The other technique, described here as a tempered greedy token, is suitable for more complex problems, like matching delimited text where the delimiters consist of multiple characters (like HTML, as Luke commented below). For the problem described in the question, it's overkill.

For anyone who's interested, I tested with a large chunk of Lorem Ipsum text, counting the number of lines that don't contain the word "quo". These are the regexes I used:

(?m)^(?!.*\bquo\b).+$

(?m)^(?:(?!\bquo\b).)+$

Whether I search for matches in the whole text, or break it up into lines and match them individually, the anchored lookahead consistently outperforms the floating one.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

How to resolve "local edit, incoming delete upon update" message

If you haven't made any changes inside the conflicted directory, you can also rm -rf conflicts_in_here/ and then svn up. This worked for me at least.

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

I've solved my problem by this way: Edit the php.ini file:

  1. change extension_dir = "ext" into extension_dir = "D:\php\ext" (please write ur own path)
  2. change ;extension=php_mbstring.dll into extension=php_mbstring.dll (delete the ";")
  3. Then just save your php.ini file and copy it to ur Windows directory?(“C:\Windows“)
  4. restart the apache server?

The above is my solution,Hope it will work for u.

How to disable all div content

Here is a quick comment for people who don't need a div but just a blockelement. In HTML5 <fieldset disabled="disabled"></fieldset> got the disabled attribute. Every form element in a disabled fieldset is disabled.

open failed: EACCES (Permission denied)

in my case i forgot to add / in front of file name after i added i got rid of from it

bitmap.compress(Bitmap.CompressFormat.PNG,100,new FileOutputStream(Environment.getExternalStorageDirectory()+"/arjunreddy.png"));

npm install won't install devDependencies

Got a similar error after running npm-check-updates -u. Solved it by removing node_modules folder and package-lock.json. After that a new npm install and everything worked.

My exception:

Failed to load parser '@typescript-eslint/parser' declared in 'package.json » eslint-config-react-app#overrides[0]': Cannot find module '@typescript-eslint/parser'

How to get the focused element with jQuery?

How is it noone has mentioned..

document.activeElement.id

I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

Tomcat Server not starting with in 45 seconds

try clean Tomcat working directory,it works for me

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

How do I obtain the frequencies of each value in an FFT?

The first bin in the FFT is DC (0 Hz), the second bin is Fs / N, where Fs is the sample rate and N is the size of the FFT. The next bin is 2 * Fs / N. To express this in general terms, the nth bin is n * Fs / N.

So if your sample rate, Fs is say 44.1 kHz and your FFT size, N is 1024, then the FFT output bins are at:

  0:   0 * 44100 / 1024 =     0.0 Hz
  1:   1 * 44100 / 1024 =    43.1 Hz
  2:   2 * 44100 / 1024 =    86.1 Hz
  3:   3 * 44100 / 1024 =   129.2 Hz
  4: ...
  5: ...
     ...
511: 511 * 44100 / 1024 = 22006.9 Hz

Note that for a real input signal (imaginary parts all zero) the second half of the FFT (bins from N / 2 + 1 to N - 1) contain no useful additional information (they have complex conjugate symmetry with the first N / 2 - 1 bins). The last useful bin (for practical aplications) is at N / 2 - 1, which corresponds to 22006.9 Hz in the above example. The bin at N / 2 represents energy at the Nyquist frequency, i.e. Fs / 2 ( = 22050 Hz in this example), but this is in general not of any practical use, since anti-aliasing filters will typically attenuate any signals at and above Fs / 2.

Which MySQL data type to use for storing boolean values

I use TINYINT(1) in order to store boolean values in Mysql.

I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)

http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html

PHP AES encrypt / decrypt

This is a working solution of AES encryption - implemented using openssl. It uses the Cipher Block Chaining Mode (CBC-Mode). Thus, alongside data and key, you can specify iv and block size

 <?php
      class AESEncryption {

            protected $key;
            protected $data;
            protected $method;
            protected $iv;

            /**
             * Available OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
             *
             * @var type $options
             */
            protected $options = 0;

            /**
             * 
             * @param type $data
             * @param type $key
             * @param type $iv
             * @param type $blockSize
             * @param type $mode
             */
            public function __construct($data = null, $key = null, $iv = null, $blockSize = null, $mode = 'CBC') {
                $this->setData($data);
                $this->setKey($key);
                $this->setInitializationVector($iv);
                $this->setMethod($blockSize, $mode);
            }

            /**
             * 
             * @param type $data
             */
            public function setData($data) {
                $this->data = $data;
            }

            /**
             * 
             * @param type $key
             */
            public function setKey($key) {
                $this->key = $key;
            }

            /**
             * CBC 128 192 256 
              CBC-HMAC-SHA1 128 256
              CBC-HMAC-SHA256 128 256
              CFB 128 192 256
              CFB1 128 192 256
              CFB8 128 192 256
              CTR 128 192 256
              ECB 128 192 256
              OFB 128 192 256
              XTS 128 256
             * @param type $blockSize
             * @param type $mode
             */
            public function setMethod($blockSize, $mode = 'CBC') {
                if($blockSize==192 && in_array('', array('CBC-HMAC-SHA1','CBC-HMAC-SHA256','XTS'))){
                    $this->method=null;
                    throw new Exception('Invalid block size and mode combination!');
                }
                $this->method = 'AES-' . $blockSize . '-' . $mode;
            }

            /**
             * 
             * @param type $data
             */
            public function setInitializationVector($iv) {
                $this->iv = $iv;
            }

            /**
             * 
             * @return boolean
             */
            public function validateParams() {
                if ($this->data != null &&
                        $this->method != null ) {
                    return true;
                } else {
                    return FALSE;
                }
            }

            //it must be the same when you encrypt and decrypt
            protected function getIV() { 
                return $this->iv;
            }

             /**
             * @return type
             * @throws Exception
             */
            public function encrypt() {
                if ($this->validateParams()) { 
                    return trim(openssl_encrypt($this->data, $this->method, $this->key, $this->options,$this->getIV()));
                } else {
                    throw new Exception('Invalid params!');
                }
            }

            /**
             * 
             * @return type
             * @throws Exception
             */
            public function decrypt() {
                if ($this->validateParams()) {
                   $ret=openssl_decrypt($this->data, $this->method, $this->key, $this->options,$this->getIV());

                   return   trim($ret); 
                } else {
                    throw new Exception('Invalid params!');
                }
            }

        }

Sample usage:

<?php
        $data = json_encode(['first_name'=>'Dunsin','last_name'=>'Olubobokun','country'=>'Nigeria']);
        $inputKey = "W92ZB837943A711B98D35E799DFE3Z18";
        $iv = "tuqZQhKP48e8Piuc";
        $blockSize = 256;
        $aes = new AESEncryption($data, $inputKey, $iv, $blockSize);
        $enc = $aes->encrypt();
        $aes->setData($enc);
        $dec=$aes->decrypt();
        echo "After encryption: ".$enc."<br/>";
        echo "After decryption: ".$dec."<br/>";

How to give spacing between buttons using bootstrap

Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.

Remove characters after specific character in string, then remove substring?

To remove everything before the first /

input = input.Substring(input.IndexOf("/"));

To remove everything after the first /

input = input.Substring(0, input.IndexOf("/") + 1);

To remove everything before the last /

input = input.Substring(input.LastIndexOf("/"));

To remove everything after the last /

input = input.Substring(0, input.LastIndexOf("/") + 1);

An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:

To remove everything after the first /

input = input.Remove(input.IndexOf("/") + 1);

To remove everything after the last /

input = input.Remove(input.LastIndexOf("/") + 1);

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

adding x and y axis labels in ggplot2

since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

In my answer,I have stored the plot in mygraph variable and then I have used

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

And the work is done. Below is the complete answer.

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

Also, you can change the labels title from the same formula used above -

mygraph$labels$size= "N2" #size contains the nitrogen level 

What is the correct way to read a serial port using .NET framework?

    using System;
    using System.IO.Ports;
    using System.Threading;

    namespace SerialReadTest
    {
        class SerialRead
        {
            static void Main(string[] args)
            {
        Console.WriteLine("Serial read init");
        SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
        port.Open();
        while(true){
          Console.WriteLine(port.ReadLine());
        }

    }
}
}

Python object deleting itself

This is something I have done in the past. Create a list of objects, and you can then have objects delete themselves with the list.remove() method.

bullet_list = []

class Bullet:
    def kill_self(self):
        bullet_list.remove(self)

bullet_list += [Bullet()]

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

console.writeline and System.out.println

First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example I have just implemented.

import java.io.Console;


public class TestConsole {
    public static void main(String[] args) {
        Console console = System.console();
        System.out.println("console=" + console);
        console.writer().println("hello from console");
    }
}

When I ran the application from command prompt I got the following:

$ java TestConsole
console=java.io.Console@93dcd
hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
        at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null

I hope my explanations help.

Java: Instanceof and Generics

Or you could catch a failed attempt to cast into E eg.

public int indexOf(Object arg0){
  try{
    E test=(E)arg0;
    return doStuff(test);
  }catch(ClassCastException e){
    return -1;
  }
}

How to clear input buffer in C?

unsigned char a=0;
if(kbhit()){
    a=getch();
    while(kbhit())
        getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;

-or-

use maybe use _getch_nolock() ..???

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Strip HTML from strings in Python

The solutions with HTML-Parser are all breakable, if they run only once:

html_to_text('<<b>script>alert("hacked")<</b>/script>

results in:

<script>alert("hacked")</script>

what you intend to prevent. if you use a HTML-Parser, count the Tags until zero are replaced:

from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
        self.containstags = False

    def handle_starttag(self, tag, attrs):
       self.containstags = True

    def handle_data(self, d):
        self.fed.append(d)

    def has_tags(self):
        return self.containstags

    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    must_filtered = True
    while ( must_filtered ):
        s = MLStripper()
        s.feed(html)
        html = s.get_data()
        must_filtered = s.has_tags()
    return html

Center fixed div with dynamic width (CSS)

This works regardless of the size of its contents

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

How to put scroll bar only for modal-body?

Adding on to Carlos Calla's great answer.

The height of .modal-body must be set, BUT you can use media queries to make sure it's appropriate for the screen size.

.modal-body{
    height: 250px;
    overflow-y: auto;
}

@media (min-height: 500px) {
    .modal-body { height: 400px; }
}

@media (min-height: 800px) {
    .modal-body { height: 600px; }
}

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

Cannot set some HTTP headers when using System.Net.WebRequest

WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?

ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.

Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

connecting to MySQL from the command line

See here http://dev.mysql.com/doc/refman/5.0/en/connecting.html

mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME 

The options above means:

-u: username
-p: password (**no space between -p and the password text**)
-h: host
last one is name of the database that you wanted to connect. 

Look into the link, it's detailed there!


As already mentioned by Rick, you can avoid passing the password as the part of the command by not passing the password like this:

mysql -u USERNAME -h HOSTNAMEORIP DATABASENAME -p

People editing this answer: PLEASE DONOT ADD A SPACE between -p and PASSWORD

Bootstrap 3 modal vertical position center

I came up with a pure css solution! It's css3 though, which means ie8 or lower is not supported, but other than this it's tested and working on ios, android, ie9+, chrome, firefox, desktop safari..

I am using the following css:

.modal-dialog {
  position:absolute;
  top:50% !important;
  transform: translate(0, -50%) !important;
  -ms-transform: translate(0, -50%) !important;
  -webkit-transform: translate(0, -50%) !important;
  margin:auto 5%;
  width:90%;
  height:80%;
}
.modal-content {
  min-height:100%;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0; 
}
.modal-body {
  position:absolute;
  top:45px; /** height of header **/
  bottom:45px;  /** height of footer **/
  left:0;
  right:0;
  overflow-y:auto;
}
.modal-footer {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
}

Here is a fiddle. http://codepen.io/anon/pen/Hiskj

..selecting this as the correct answer since there's no extra heavy javascript that brings the browser to its knees in case of more than one modals.

CSS Background image not loading

The path to the image should be relative, that means if css file is in css folder than you should start path with ../ such as

_x000D_
_x000D_
body{_x000D_
   background-image: url(../images/logo.jpg);_x000D_
}
_x000D_
_x000D_
_x000D_

this is because you have to get back to home dir by ../ path and then /images/logo.jpg path to the image file. If you are including css file in html itself

_x000D_
_x000D_
body{_x000D_
   background-image: url(images/logo.jpg);_x000D_
}
_x000D_
_x000D_
_x000D_ this code will work just fine.

How do I rename a local Git branch?

To rename your current branch:

git branch -m <newname>

Node/Express file upload

If you are using Node.js Express and Typescript here is a working example, this works with javascript also, just change the let to var and the import to includes etc...

first import the following make sure you install formidable by running the following command:

npm install formidable

than import the following:

  import * as formidable from 'formidable';
  import * as fs from 'fs';

then your function like bellow:

    uploadFile(req, res) {
    let form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        let oldpath = files.file.path;
        let newpath = 'C:/test/' + files.file.name;
        fs.rename(oldpath, newpath, function (err) {
            if (err) throw err;
            res.write('File uploaded and moved!');
            res.end();
        });
    });
}

Webdriver and proxy server for firefox

Firefox Proxy: JAVA

String PROXY = "localhost:8080";

org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();

proxy.setHttpProxy(PROXY)setFtpProxy(PROXY).setSslProxy(PROXY);

DesiredCapabilities cap = new DesiredCapabilities();

cap.setCapability(CapabilityType.PROXY, proxy); 

WebDriver driver = new FirefoxDriver(cap);

Parsing jQuery AJAX response

calling

var parsed_data = JSON.parse(data);

should result in the ability to access the data like you want.

console.log(parsed_data.success);

should now show '1'

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

jQuery $.cookie is not a function

I had this problem as well. I found out that having a $(document).ready function that included a $.cookie in a script tag inside body while having cookie js load in the head BELOW jquery as intended resulted in $(document).ready beeing processed before the cookie plugin could finish loading.

I moved the cookie plugin load script in the body before the $(document).ready script and the error disappeared :D

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Here's a solution which will work even when JavaScript is disabled:

<form action="login.html">
    <button type="submit">Login</button>
</form>

The trick is to surround the button with its own <form> tag.

I personally prefer the <button> tag, but you can do it with <input> as well:

<form action="login.html">
    <input type="submit" value="Login"/>
</form>