Programs & Examples On #Nscalendar

NSCalendar is an Apple MacOS and iOS class to deal with calendrical computation.

Get day of week using NSDate

extension Date {

var weekdayName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "E"
    return formatter.string(from: self as Date)
}

var weekdayNameFull: String {
    let formatter = DateFormatter(); formatter.dateFormat = "EEEE"
    return formatter.string(from: self as Date)
}
var monthName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "MMM"
    return formatter.string(from: self as Date)
}
var OnlyYear: String {
    let formatter = DateFormatter(); formatter.dateFormat = "YYYY"
    return formatter.string(from: self as Date)
}
var period: String {
    let formatter = DateFormatter(); formatter.dateFormat = "a"
    return formatter.string(from: self as Date)
}
var timeOnly: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm"
    return formatter.string(from: self as Date)
}
var timeWithPeriod: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm a"
    return formatter.string(from: self as Date)
}

var DatewithMonth: String {
    let formatter = DateFormatter(); formatter.dateStyle = .medium ;        return formatter.string(from: self as Date)
}
}

usage let weekday = Date().weekdayName

NSDate get year/month/day

If you wish to get the individual NSDateComponents from NSDate, you would definitely need the solution suggested by Itai Ferber. But if you want to go from NSDate directly to an NSString, you can use NSDateFormatter.

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

What is username and password when starting Spring Boot with Tomcat?

If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to

Using generated security password: <some UUID>

How to create an executable .exe file from a .m file

The Matlab Compiler is the standard way to do this. mcc is the command. The Matlab Runtime is required to run the programs; I'm not sure if it can be directly integrated with the executable or not.

Fastest way to get the first n elements of a List into an Array

It mostly depends on how big n is.

If n==0, nothing beats option#1 :)

If n is very large, toArray(new String[n]) is faster.

How can I put CSS and HTML code in the same file?

<html>
<head>
    <style type="text/css">
    .title {
        color: blue;
        text-decoration: bold;
        text-size: 1em;
    }

    .author {
        color: gray;
    }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

On a side note, it would have been much easier to just do this.

jQuery Validate Required Select

You only need to put validate[required] as class of this select and then put a option with value=""

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

orderBy multiple fields in Angular

Please see this:

http://jsfiddle.net/JSWorld/Hp4W7/32/

<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>

wait() or sleep() function in jquery?

I found a function called sleep function on the internet and don't know who made it. Here it is.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(2000);

Cocoa Autolayout: content hugging vs content compression resistance priority

The Content hugging priority is like a Rubber band that is placed around a view. The higher the priority value, the stronger the rubber band and the more it wants to hug to its content size. The priority value can be imagined like the "strength" of the rubber band

And the Content Compression Resistance is, how much a view "resists" getting smaller The View with higher resistance priority value is the one that will resist compression.

Check for special characters in string

Check if a string contains at least one password special character:

For reference: ASCII Table -- Printable Characters

Special character ranges in the ASCII table are:

  • Space to /
  • : to @
  • [ to `
  • { to ~

Therefore, use this:

/[ -/:-@[-`{-~]/.test(string)

HTML Script tag: type or language (or omit both)?

The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.

The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

How to get Selected Text from select2 when using <input>

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

Conditional formatting, entire row based

Use the "indirect" function on conditional formatting.

  1. Select Conditional Formatting
  2. Select New Rule
  3. Select "Use a Formula to determine which cells to format"
  4. Enter the Formula, =INDIRECT("g"&ROW())="X"
  5. Enter the Format you want (text color, fill color, etc).
  6. Select OK to save the new format
  7. Open "Manage Rules" in Conditional Formatting
  8. Select "This Worksheet" if you can't see your new rule.
  9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

How to set time to midnight for current day?

I believe you are looking for DateTime.Today. The documentation states:

An object that is set to today's date, with the time component set to 00:00:00.

http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

Your code would be

DateTime _Begin = DateTime.Today;

Force a screen update in Excel VBA

Text boxes in worksheets are sometimes not updated when their text or formatting is changed, and even the DoEvent command does not help.

As there is no command in Excel to refresh a worksheet in the way a user form can be refreshed, it is necessary to use a trick to force Excel to update the screen.

The following commands seem to do the trick:

- ActiveSheet.Calculate    
- ActiveWindow.SmallScroll    
- Application.WindowState = Application.WindowState

One line if-condition-assignment

Another way num1 = (20*boolVar)+(num1*(not boolVar))

Should MySQL have its timezone set to UTC?

PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.

Read this tutorial: How To Synchronize Your PHP and MySQL Timezones

git status shows fatal: bad object HEAD

This is unlikely to be the source of your problem - but if you happen to be working in .NET you'll end up with a bunch of obj/ folders. Sometimes it is helpful to delete all of these obj/ folders in order to resolve a pesky build issue.

I received the same fatal: bad object HEAD on my current branch (master) and was unable to run git status or to checkout any other branch (I always got an error refs/remote/[branch] does not point to a valid object).

If you want to delete all of your obj folders, don't get lazy and allow .git/objects into the mix. That folder is where all of the actual contents of your git commits go.

After being close to giving up I decided to look at which files were in my recycle bin, and there it was. Restored the file and my local repository was like new.

Max value of Xmx and Xms in Eclipse?

I have tried the following config for eclipse.ini:

org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms128m
-Xmx2048m

Now eclipse performance is about 2 times faster then before.

You can also find a good help ref here: http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html

How to store phone numbers on MySQL databases?

Suggest that you store the number as an extended alphanumeric made up of characters that you wish to accept and store it in a varchar(32) or something like that. Strip out all the spaces , dashes, etc. Put the FORMATTING of the phone number into a separate field (possibly gleaned from the locale preferences) If you wish to support extensions, you should add them in a separate field;

How to convert .pfx file to keystore with private key?

Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.

Edit

Further information:

  • Download OpenSSL for Windows here.
  • Export private key: openssl pkcs12 -in filename.pfx -nocerts -out key.pem
  • Export certificate: openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
  • Import private key and certificate into Java keystore using keytool.

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

SQL left join vs multiple tables on FROM line?

To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.

How can I see the raw SQL queries Django is running?

If you make sure your settings.py file has:

  1. django.core.context_processors.debug listed in CONTEXT_PROCESSORS
  2. DEBUG=True
  3. your IP in the INTERNAL_IPS tuple

Then you should have access to the sql_queries variable. I append a footer to each page that looks like this:

{%if sql_queries %}
  <div class="footNav">
    <h2>Queries</h2>
    <p>
      {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}, {{sql_time_sum}} Time
    {% ifnotequal sql_queries|length 0 %}
      (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.disp\
lay=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
    {% endifnotequal %}
    </p>
    <table id="debugQueryTable" style="display: none;">
      <col width="1"></col>
      <col></col>
      <col width="1"></col>
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">SQL</th>
          <th scope="col">Time</th>
        </tr>
      </thead>
      <tbody>
        {% for query in sql_queries %}
          <tr class="{% cycle odd,even %}">
            <td>{{ forloop.counter }}</td>
            <td>{{ query.sql|escape }}</td>
            <td>{{ query.time }}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
{% endif %}

I got the variable sql_time_sum by adding the line

context_extras['sql_time_sum'] = sum([float(q['time']) for q in connection.queries])

to the debug function in django_src/django/core/context_processors.py.

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

MySQL Error: : 'Access denied for user 'root'@'localhost'

Fix for Mac OS

  1. Install MySQL from https://downloads.mysql.com/archives/community/ (8.x is latest as on date but ensure that the version is compatible with the Mac OS version)

  2. Give password for root (let <root-password> be the password) during installation (Don't forget to remember the password!)

  3. Select Use Legacy Password Encryption option (that is what I had used and did not try for Use Strong Password Encryption option)

  4. Search and open MySQL.prefPane (use search tool)

    1. Select Configuration tab
    2. Click Select option of Configuration File
      1. Select /private/etc/my.cnf
  5. From terminal open a new or existing file with name /etc/my.cnf (vi /etc/my.cnf) add the following content:

     [mysqld]
     skip-grant-tables
    
  6. Restart mysqld as follows:

    1. ps aux | grep mysql
    2. kill -9 <pid1> <pid2> ... (grab pids of all mysql related processes)
  7. mysqld gets restarted automatically

  8. Verify that the option is set by running the following from terminal:

     ps aux | grep mysql
    
     > mysql/bin/mysqld ... --defaults-file=/private/etc/my.cnf ... (output)
    
  9. Run the following command to connect (let mysql-<version>-macos<version>-x86_64 be the folder where mysql is installed. To grab the actual folder, run ls /usr/local/ and copy the folder name):

     /usr/local/mysql-<version>-macos<version>-x86_64/bin/mysql -uroot -p<root-password>
    

how to convert from int to char*?

See this answer https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").

What is setBounds and how do I use it?

There is an answer by @hexafraction , He had specified the x and y to be top right corner which is wrong, those are top left corner .

I have also provided the source please check it.

public void setBounds(int x,
             int y,
             int width,
             int height)

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. This method changes layout-related information, and therefore, invalidates the component hierarchy.

Parameters:

x - the new x-coordinate of this component

y - the new y-coordinate of this component

width - the new width of this component

height - the new height of this component

source:- setBounds

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

Postgres could not connect to server

I faced the same problem for psql (PostgreSQL) 9.6.11.

what worked for me -

remove postmaster.pid -- rm /usr/local/var/[email protected]/postmaster.pid

restart postgres -- brew services restart [email protected]

If this also doesn't work then run -- sudo chmod 700 /usr/local/var/[email protected]

How to determine if a list of polygon points are in clockwise order?

Here's a simple Python 3 implementation based on this answer (which, in turn, is based on the solution proposed in the accepted answer)

def is_clockwise(points):
    # points is your list (or array) of 2d points.
    assert len(points) > 0
    s = 0.0
    for p1, p2 in zip(points, points[1:] + [points[0]]):
        s += (p2[0] - p1[0]) * (p2[1] + p1[1])
    return s > 0.0

iPhone viewWillAppear not firing

As no answer is accepted and people (like I did) land here I give my variation. Though I am not sure that was the original problem. When the navigation controller is added as a subview to a another view you must call the viewWillAppear/Dissappear etc. methods yourself like this:

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [subNavCntlr viewWillAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [subNavCntlr viewWillDisappear:animated];
}

Just to make the example complete. This code appears in my ViewController where I created and added the the navigation controller into a view that I placed on the view.

- (void)viewDidLoad {

    // This is the root View Controller
    rootTable *rootTableController = [[rootTable alloc]
                 initWithStyle:UITableViewStyleGrouped];

    subNavCntlr = [[UINavigationController alloc]   
                  initWithRootViewController:rootTableController];

    [rootTableController release];

    subNavCntlr.view.frame = subNavContainer.bounds;

    [subNavContainer addSubview:subNavCntlr.view];

    [super viewDidLoad];
}

the .h looks like this

@interface navTestViewController : UIViewController <UINavigationControllerDelegate> {
    IBOutlet UIView *subNavContainer;
    UINavigationController *subNavCntlr;
}

@end

In the nib file I have the view and below this view I have a label a image and the container (another view) where i put the controller in. Here is how it looks. I had to scramble some things as this was work for a client.

alt text

Standard concise way to copy a file in Java?

A little late to the party, but here is a comparison of the time taken to copy a file using various file copy methods. I looped in through the methods for 10 times and took an average. File transfer using IO streams seem to be the worst candidate:

Comparison of file transfer using various methods

Here are the methods:

private static long fileCopyUsingFileStreams(File fileToCopy, File newFile) throws IOException {
    FileInputStream input = new FileInputStream(fileToCopy);
    FileOutputStream output = new FileOutputStream(newFile);
    byte[] buf = new byte[1024];
    int bytesRead;
    long start = System.currentTimeMillis();
    while ((bytesRead = input.read(buf)) > 0)
    {
        output.write(buf, 0, bytesRead);
    }
    long end = System.currentTimeMillis();

    input.close();
    output.close();

    return (end-start);
}

private static long fileCopyUsingNIOChannelClass(File fileToCopy, File newFile) throws IOException
{
    FileInputStream inputStream = new FileInputStream(fileToCopy);
    FileChannel inChannel = inputStream.getChannel();

    FileOutputStream outputStream = new FileOutputStream(newFile);
    FileChannel outChannel = outputStream.getChannel();

    long start = System.currentTimeMillis();
    inChannel.transferTo(0, fileToCopy.length(), outChannel);
    long end = System.currentTimeMillis();

    inputStream.close();
    outputStream.close();

    return (end-start);
}

private static long fileCopyUsingApacheCommons(File fileToCopy, File newFile) throws IOException
{
    long start = System.currentTimeMillis();
    FileUtils.copyFile(fileToCopy, newFile);
    long end = System.currentTimeMillis();
    return (end-start);
}

private static long fileCopyUsingNIOFilesClass(File fileToCopy, File newFile) throws IOException
{
    Path source = Paths.get(fileToCopy.getPath());
    Path destination = Paths.get(newFile.getPath());
    long start = System.currentTimeMillis();
    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
    long end = System.currentTimeMillis();

    return (end-start);
}

The only drawback what I can see while using NIO channel class is that I still can't seem to find a way to show intermediate file copy progress.

Disable browser's back button

You should be using posts with proper expires and caching headers.

Remove legend ggplot 2.2

If your chart uses both fill and color aesthetics, you can remove the legend with:

+ guides(fill=FALSE, color=FALSE)

redistributable offline .NET Framework 3.5 installer for Windows 8

Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

There's a guide on MSDN.

Oracle Differences between NVL and Coalesce

NVL and COALESCE are used to achieve the same functionality of providing a default value in case the column returns a NULL.

The differences are:

  1. NVL accepts only 2 arguments whereas COALESCE can take multiple arguments
  2. NVL evaluates both the arguments and COALESCE stops at first occurrence of a non-Null value.
  3. NVL does a implicit datatype conversion based on the first argument given to it. COALESCE expects all arguments to be of same datatype.
  4. COALESCE gives issues in queries which use UNION clauses. Example below
  5. COALESCE is ANSI standard where as NVL is Oracle specific.

Examples for the third case. Other cases are simple.

select nvl('abc',10) from dual; would work as NVL will do an implicit conversion of numeric 10 to string.

select coalesce('abc',10) from dual; will fail with Error - inconsistent datatypes: expected CHAR got NUMBER

Example for UNION use-case

SELECT COALESCE(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      );

fails with ORA-00932: inconsistent datatypes: expected CHAR got DATE

SELECT NVL(a, sysdate) 
from (select null as a from dual 
      union 
      select null as a from dual
      ) ;

succeeds.

More information : http://www.plsqlinformation.com/2016/04/difference-between-nvl-and-coalesce-in-oracle.html

Postman: sending nested JSON object

Select the body tab and select application/json in the Content-Type drop-down and add a body like this:

{
  "Username":"ABC",
  "Password":"ABC"
}

enter image description here

What is the difference between concurrency and parallelism?

Concurrency: If two or more problems are solved by a single processor. alt text

Parallelism: If one problem is solved by multiple processors.

alt text

PowerShell: Store Entire Text File Contents in Variable

Get-Content grabs data and dumps it into an array, line by line. Assuming there aren't other special requirements than you listed, you could just save your content into a variable?

$file = Get-Content c:\file\whatever.txt

Running just $file will return the full contents. Then you can just do $file.Count (because arrays already have a count method built in) to get the total # of lines.

Hope this helps! I'm not a scripting wiz, but this seemed easier to me than a lot of the stuff above.

How to check if one of the following items is in a list?

Ah, Tobias you beat me to it. I was thinking of this slight variation on your solution:

>>> a = [1,2,3,4]
>>> b = [2,7]
>>> any(x in a for x in b)
True

Usage of \b and \r in C

The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).

It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.

Difference between Spring MVC and Spring Boot

  • Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs.
  • Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on).

So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. You might find useful visiting the Spring MVC tag wiki as well as the Spring Boot tag wiki in SO.

Questions every good .NET developer should be able to answer?

This might not be what you want to hear, but I would recommend not focusing on narrow technologies, but on general programming and problem solving skills. Solid developers can learn whatever you want them to do quickly.

I, for instance, am not a Compact Framework guy, so I might fail your interview if you went that direction. But if I needed to use it I could do some research and jump right in.

Joel's book, Smart and Gets Things Done, has great advice for hiring devs and there are large juicy sections about the kinds of questions to ask. I highly recommend it.

Including dependencies in a jar with Maven

If you (like me) dont particularly like the jar-with-dependencies approach described above, the maven-solution I prefer is to simply build a WAR-project, even if it is only a stand-alone java application you are building:

  1. Make a normal maven jar-project, that will build your jar-file (without the dependencies).

  2. Also, setup a maven war-project (with only an empty src/main/webapp/WEB-INF/web.xml file, which will avoid a warning/error in the maven-build), that only has your jar-project as a dependency, and make your jar-project a <module> under your war-project. (This war-project is only a simple trick to wrap all your jar-file dependencies into a zip-file.)

  3. Build the war-project to produce the war-file.

  4. In the deployment-step, simply rename your .war-file to *.zip and unzip it.

You should now have a lib-directory (which you can move where you want it) with your jar and all the dependencies you need to run your application:

java -cp 'path/lib/*' MainClass

(The wildcard in classpath works in Java-6 or higher)

I think this is both simpler to setup in maven (no need to mess around with the assembly plugin) and also gives you a clearer view of the application-structure (you will see the version-numbers of all dependent jars in plain view, and avoid clogging everything into a single jar-file).

How to use opencv in using Gradle?

If you don't want to use JavaCV this works for me...

Step 1- Download the Resources

Download OpenCV Android SDK from http://opencv.org/downloads.html

Step 2 - Copying the OpenCV binaries into your APK

Copy libopencv_info.so & libopencv_java.so from

OpenCV-2.?.?-android-sdk -> sdk -> native -> libs -> armeabi-v7a

to

Project Root -> Your Project -> lib - > armeabi-v7a

Zip the lib folder up and rename that zip to whatever-v7a.jar.

Copy this .jar file and place it in here in your project

Project Root -> Your Project -> libs

Add this line to your projects build.gradle in the dependencies section

compile files('libs/whatever-v7a.jar')

When you compile now you will probably see your .apk is about 4mb bigger.

(Repeat for "armeabi" if you want to support ARMv6 too, likely not needed anymore.)

Step 3 - Adding the java sdk to your project

Copy the java folder from here

OpenCV-2.?.?-android-sdk -> sdk

to

Project Root -> Your Project -> libs (Same place as your .jar file);

(You can rename the 'java' folder name to 'OpenCV')

In this freshly copied folder add a typical build.gradle file; I used this:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}

apply plugin: 'android-library'

repositories {
    mavenCentral();
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

In your Project Root settings.gradle file change it too look something like this:

include ':Project Name:libs:OpenCV', ':Project Name'

In your Project Root -> Project Name -> build.gradle file in the dependencies section add this line:

compile project(':Project Name:libs:OpenCV')

Step 4 - Using OpenCV in your project

Rebuild and you should be able to import and start using OpenCV in your project.

import org.opencv.android.OpenCVLoader;
...
if (!OpenCVLoader.initDebug()) {}

I know this if a bit of hack but I figured I would post it anyway.

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

What's the difference between & and && in MATLAB?

As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:

  • & (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
  • && and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.

Linux bash: Multiple variable assignment

Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign

MYVAR="something"

The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).

This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.

SQLite - UPSERT *not* INSERT or REPLACE

Eric B’s answer is OK if you want to preserve just one or maybe two columns from the existing row. If you want to preserve a lot of columns, it gets too cumbersome fast.

Here’s an approach that will scale well to any amount of columns on either side. To illustrate it I will assume the following schema:

 CREATE TABLE page (
     id      INTEGER PRIMARY KEY,
     name    TEXT UNIQUE,
     title   TEXT,
     content TEXT,
     author  INTEGER NOT NULL REFERENCES user (id),
     ts      TIMESTAMP DEFAULT CURRENT_TIMESTAMP
 );

Note in particular that name is the natural key of the row – id is used only for foreign keys, so the point is for SQLite to pick the ID value itself when inserting a new row. But when updating an existing row based on its name, I want it to continue to have the old ID value (obviously!).

I achieve a true UPSERT with the following construct:

 WITH new (name, title, author) AS ( VALUES('about', 'About this site', 42) )
 INSERT OR REPLACE INTO page (id, name, title, content, author)
 SELECT old.id, new.name, new.title, old.content, new.author
 FROM new LEFT JOIN page AS old ON new.name = old.name;

The exact form of this query can vary a bit. The key is the use of INSERT SELECT with a left outer join, to join an existing row to the new values.

Here, if a row did not previously exist, old.id will be NULL and SQLite will then assign an ID automatically, but if there already was such a row, old.id will have an actual value and this will be reused. Which is exactly what I wanted.

In fact this is very flexible. Note how the ts column is completely missing on all sides – because it has a DEFAULT value, SQLite will just do the right thing in any case, so I don’t have to take care of it myself.

You can also include a column on both the new and old sides and then use e.g. COALESCE(new.content, old.content) in the outer SELECT to say “insert the new content if there was any, otherwise keep the old content” – e.g. if you are using a fixed query and are binding the new values with placeholders.

CSS background image to fit height, width should auto-scale in proportion

body.bg {
    background-size: cover;
    background-repeat: no-repeat;
    min-height: 100vh;
    background: white url(../images/bg-404.jpg) center center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}   
Try This
_x000D_
_x000D_
    body.bg {_x000D_
     background-size: cover;_x000D_
     background-repeat: no-repeat;_x000D_
     min-height: 100vh;_x000D_
     background: white url(http://lorempixel.com/output/city-q-c-1920-1080-7.jpg) center center no-repeat;_x000D_
     -webkit-background-size: cover;_x000D_
     -moz-background-size: cover;_x000D_
     -o-background-size: cover;_x000D_
    } 
_x000D_
    <body class="bg">_x000D_
_x000D_
_x000D_
     _x000D_
    </body>
_x000D_
_x000D_
_x000D_

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

What is the difference between UTF-8 and Unicode?

1. Unicode

There're lots of characters around the world,like "$,&,h,a,t,?,?,1,=,+...".

Then there comes an organization who's dedicated to these characters,

They made a standard called "Unicode".

The standard is like follows:

  • create a form in which each position is called "code point",or"code position".
  • The whole positions are from U+0000 to U+10FFFF;
  • Up until now,some positions are filled with characters,and other positions are saved or empty.
  • For example,the position "U+0024" is filled with the character "$".

PS:Of course there's another organization called ISO maintaining another standard --"ISO 10646",nearly the same.

2. UTF-8

As above,U+0024 is just a position,so we can't save "U+0024" in computer for the character "$".

There must be an encoding method.

Then there come encoding methods,such as UTF-8,UTF-16,UTF-32,UCS-2....

Under UTF-8,the code point "U+0024" is encoded into 00100100.

00100100 is the value we save in computer for "$".

Serialize JavaScript object into JSON string

This might be useful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.

Semi-transparent color layer over background-image?

Try this. Works for me.

.background {
    background-image: url(images/images.jpg);
    display: block;
    position: relative;
}

.background::after {
    content: "";
    background: rgba(45, 88, 35, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
}

.background > * {
    z-index: 10;
}

How do you change Background for a Button MouseOver in WPF?

A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)

In your resource dictionary define a control template for your button like this one:

<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
    <Border Name="RootElement">
        <Border.Background>
            <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
        </Border.Background>

        <Grid Margin="4" >
            <Grid.Background>
                <SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
            </Grid.Background>
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
        </Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Border>
</ControlTemplate>

in your XAML you can use the template above for your button as below:

Define your button

<Button Template="{StaticResource testButtonTemplate2}" 
HorizontalAlignment="Center" VerticalAlignment="Center" 
Foreground="White">My button</Button>

Hope it helps

C# DLL config file

I've found what seems like a good solution to this issue. I am using VS 2008 C#. My solution involves the use of distinct namespaces between multiple configuration files. I've posted the solution on my blog: http://tommiecarter.blogspot.com/2011/02/how-to-access-multiple-config-files-in.html.

For example:

This namespace read/writes dll settings:

var x = company.dlllibrary.Properties.Settings.Default.SettingName;
company.dlllibrary.Properties.Settings.Default.SettingName = value;

This namespace read/writes the exe settings:

company.exeservice.Properties.Settings.Default.SettingName = value;
var x = company.exeservice.Properties.Settings.Default.SettingName;

There are some caveats mentioned in the article. HTH

How to crop an image using C#?

There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping

Register the control

<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>

Resizing

<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1" 
     X="10" Y="10" X2="50" Y2="50" />

Cropping in code behind - Call Crop method when button clicked for example;

wci1.Crop(Server.MapPath("images/sample1.jpg"));

How to find whether or not a variable is empty in Bash?

if [ ${foo:+1} ]
then
    echo "yes"
fi

prints yes if the variable is set. ${foo:+1} will return 1 when the variable is set, otherwise it will return empty string.

Easy way to password-protect php page

Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.

Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.

They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.

If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.

<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

if($user == "admin"
&& $pass == "admin")
{
        include("secure.html");
}
else
{
    if(isset($_POST))
    {?>

            <form method="POST" action="secure.php">
            User <input type="text" name="user"></input><br/>
            Pass <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Go"></input>
            </form>
    <?}
}
?>

How to limit google autocomplete results to City and Country only

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var options = {_x000D_
        types: ['geocode'] //this should work !_x000D_
      };_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

Github: error cloning my private repository

The following command

git clone git://github.com/username/projectname.git

worked for my needs, but I assume you want more than read-only access, right?

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Simply i have import in appmodule.ts

import { HttpClientModule } from '@angular/common/http';
  imports: [
     BrowserModule,
     FormsModule,
     HttpClientModule  <<<this 
  ],

My problem resolved

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

This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.

Download the jar, comment your previous entry for ojdbc6, and give a new local entry like so:

Previous Entry:

<!-- OJDBC6 Dependency -->
        <!-- <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>1.0</version>
            <scope>runtime</scope>
        </dependency> -->

New Entry:

<dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
        </dependency> 

Get Android API level of phone currently running my application

Check android.os.Build.VERSION, which is a static class that holds various pieces of information about the Android OS a system is running.

If you care about all versions possible (back to original Android version), as in minSdkVersion is set to anything less than 4, then you will have to use android.os.Build.VERSION.SDK, which is a String that can be converted to the integer of the release.

If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of android.os.Build.VERSION.SDK_INT, which is an integer.

In either case, the integer you get maps to an enum value from all those defined in android.os.Build.VERSION_CODES:

SDK_INT value        Build.VERSION_CODES        Human Version Name       
    1                  BASE                      Android 1.0 (no codename)
    2                  BASE_1_1                  Android 1.1 Petit Four
    3                  CUPCAKE                   Android 1.5 Cupcake
    4                  DONUT                     Android 1.6 Donut
    5                  ECLAIR                    Android 2.0 Eclair
    6                  ECLAIR_0_1                Android 2.0.1 Eclair                  
    7                  ECLAIR_MR1                Android 2.1 Eclair
    8                  FROYO                     Android 2.2 Froyo
    9                  GINGERBREAD               Android 2.3 Gingerbread
   10                  GINGERBREAD_MR1           Android 2.3.3 Gingerbread
   11                  HONEYCOMB                 Android 3.0 Honeycomb
   12                  HONEYCOMB_MR1             Android 3.1 Honeycomb
   13                  HONEYCOMB_MR2             Android 3.2 Honeycomb
   14                  ICE_CREAM_SANDWICH        Android 4.0 Ice Cream Sandwich
   15                  ICE_CREAM_SANDWICH_MR1    Android 4.0.3 Ice Cream Sandwich
   16                  JELLY_BEAN                Android 4.1 Jellybean
   17                  JELLY_BEAN_MR1            Android 4.2 Jellybean
   18                  JELLY_BEAN_MR2            Android 4.3 Jellybean
   19                  KITKAT                    Android 4.4 KitKat
   20                  KITKAT_WATCH              Android 4.4 KitKat Watch
   21                  LOLLIPOP                  Android 5.0 Lollipop
   22                  LOLLIPOP_MR1              Android 5.1 Lollipop
   23                  M                         Android 6.0 Marshmallow
   24                  N                         Android 7.0 Nougat
   25                  N_MR1                     Android 7.1.1 Nougat
   26                  O                         Android 8.0 Oreo
   27                  O_MR1                     Android 8 Oreo MR1
   28                  P                         Android 9 Pie
   29                  Q                         Android 10
  10000                CUR_DEVELOPMENT           Current Development Version

Note that some time between Android N and O, the Android SDK began aliasing CUR_DEVELOPMENT and the developer preview of the next major Android version to be the same SDK_INT value (10000).

How to properly use jsPDF library

According to the latest version (1.5.3) there is no fromHTML() method anymore. Instead you should utilize jsPDF HTML plugin, see: https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html

You also need to add html2canvas library in order for it to work properly: https://github.com/niklasvh/html2canvas

JS (from API docs):

var doc = new jsPDF();   

doc.html(document.body, {
   callback: function (doc) {
     doc.save();
   }
});

You can provide HTML string instead of reference to the DOM element as well.

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

How do I properly clean up Excel interop objects?

Common developers, none of your solutions worked for me, so I decide to implement a new trick.

First let specify "What is our goal?" => "Not to see excel object after our job in task manager"

Ok. Let no to challenge and start destroying it, but consider not to destroy other instance os Excel which are running in parallel.

So , get the list of current processors and fetch PID of EXCEL processes , then once your job is done, we have a new guest in processes list with a unique PID ,find and destroy just that one.

< keep in mind any new excel process during your excel job will be detected as new and destroyed > < A better solution is to capture PID of new created excel object and just destroy that>

Process[] prs = Process.GetProcesses();
List<int> excelPID = new List<int>();
foreach (Process p in prs)
   if (p.ProcessName == "EXCEL")
       excelPID.Add(p.Id);

.... // your job 

prs = Process.GetProcesses();
foreach (Process p in prs)
   if (p.ProcessName == "EXCEL" && !excelPID.Contains(p.Id))
       p.Kill();

This resolves my issue, hope yours too.

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

How to get file size in Java

Try this:

long length = f.length();

How to convert byte array to string and vice versa?

This works fine for me:

String cd="Holding some value";

Converting from string to byte[]:

byte[] cookie = new sun.misc.BASE64Decoder().decodeBuffer(cd);

Converting from byte[] to string:

cd = new sun.misc.BASE64Encoder().encode(cookie);

Remove a prefix from a string

regex solution (The best way is the solution by @Elazar this is just for fun)

import re
def remove_prefix(text, prefix):
    return re.sub(r'^{0}'.format(re.escape(prefix)), '', text)

>>> print remove_prefix('template.extensions', 'template.')
extensions

Partial Dependency (Databases)

Partial dependency means that a nonprime attribute is functionally dependent on part of a candidate key. (A nonprime attribute is an attribute that's not part of any candidate key.)

For example, let's start with R{ABCD}, and the functional dependencies AB->CD and A->C.

The only candidate key for R is AB. C and D are a nonprime attributes. C is functionally dependent on A. A is part of a candidate key. That's a partial dependency.

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

jQuery UI Datepicker - Multiple Date Selections

I needed to do the same thing, so have written some JavaScript to enable this, using the onSelect and beforeShowDay events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.
I used this code as a basis.

<script type="text/javascript">
// Maintain array of dates
var dates = new Array();

function addDate(date) {
    if (jQuery.inArray(date, dates) < 0) 
        dates.push(date);
}

function removeDate(index) {
    dates.splice(index, 1);
}

// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
    var index = jQuery.inArray(date, dates);
    if (index >= 0) 
        removeDate(index);
    else 
        addDate(date);
}

// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
    var ret = new String(number);
    if (ret.length == 1) 
        ret = "0" + ret;
    return ret;
}

jQuery(function () {
    jQuery("#datepicker").datepicker({
        onSelect: function (dateText, inst) {
            addOrRemoveDate(dateText);
        },
        beforeShowDay: function (date) {
            var year = date.getFullYear();
            // months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"
            var month = padNumber(date.getMonth() + 1);
            var day = padNumber(date.getDate());
            // This depends on the datepicker's date format
            var dateString = month + "/" + day + "/" + year;

            var gotDate = jQuery.inArray(dateString, dates);
            if (gotDate >= 0) {
                // Enable date so it can be deselected. Set style to be highlighted
                return [true, "ui-state-highlight"];
            }
            // Dates not in the array are left enabled, but with no extra style
            return [true, ""];
        }
    });
});
</script>

What is the naming convention in Python for variable and function names?

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"

Open files in 'rt' and 'wt' modes

The 'r' is for reading, 'w' for writing and 'a' is for appending.

The 't' represents text mode as apposed to binary mode.

Several times here on SO I've seen people using rt and wt modes for reading and writing files.

Edit: Are you sure you saw rt and not rb?

These functions generally wrap the fopen function which is described here:

http://www.cplusplus.com/reference/cstdio/fopen/

As you can see it mentions the use of b to open the file in binary mode.

The document link you provided also makes reference to this b mode:

Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.

How to read request body in an asp.net core webapi controller?

A quick way to add response buffering in .NET Core 3.1 is

    app.Use((context, next) =>
    {
        context.Request.EnableBuffering();
        return next();
    });

in Startup.cs. I found this also guarantees that buffering will be enabled before the stream has been read, which was a problem for .Net Core 3.1 with some of the other middleware/authorization filter answers I've seen.

Then you can read your request body via HttpContext.Request.Body in your handler as several others have suggested.

Also worth considering is that EnableBuffering has overloads that allow you to limit how much it will buffer in memory before it uses a temporary file, and also an overall limit to you buffer. NB if a request exceeds this limit an exception will be thrown and the request will never reach your handler.

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

How do I capitalize first letter of first name and last name in C#?

Hope this helps you.

String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);

mysql_config not found when installing mysqldb python interface

I had the same problem. I solved it by following this tutorial to install Python with python3-dev on Ubuntu 16.04:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

And now you can set up your virtual environment:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

Oracle Sql get only month and year in date datatype

"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.

You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.

If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...

Example..

Month varchar2(3) --Month code in Alpha..
Year  NUMBER      -- Year in number

or

Month number(2)    --Month Number in Year.
Year  NUMBER      -- Year in number

grep exclude multiple strings

Two examples of filtering out multiple lines with grep:

Put this in filename.txt:

abc
def
ghi
jkl

grep command using -E option with a pipe between tokens in a string:

grep -Ev 'def|jkl' filename.txt

prints:

abc
ghi

Command using -v option with pipe between tokens surrounded by parens:

egrep -v '(def|jkl)' filename.txt

prints:

abc
ghi

Find an item in List by LINQ?

This will help you in getting the first or default value in your Linq List search

var results = _List.Where(item => item == search).FirstOrDefault();

This search will find the first or default value it will return.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

It may well be that you're running WordPress core tests, and have recently upgraded your PhpUnit to version 6. If that's the case, then the recent change to namespacing in PhpUnit will have broken your code.

Fortunately, there's a patch to the core tests at https://core.trac.wordpress.org/changeset/40547 which will work around the problem. It also includes changes to travis.yml, which you may not have in your setup; if that's the case then you'll need to edit the .diff file to ignore the Travis patch.

  1. Download the "Unified Diff" patch from the bottom of https://core.trac.wordpress.org/changeset/40547
  2. Edit the patch file to remove the Travis part of the patch if you don't need that. Delete from the top of the file to just above this line:

    Index: /branches/4.7/tests/phpunit/includes/bootstrap.php
    
  3. Save the diff in the directory above your /includes/ directory - in my case this was the Wordpress directory itself

  4. Use the Unix patch tool to patch the files. You'll also need to strip the first few slashes to move from an absolute to a relative directory structure. As you can see from point 3 above, there are five slashes before the include directory, which a -p5 flag will get rid of for you.

    $ cd [WORDPRESS DIRECTORY]
    $ patch -p5 < changeset_40547.diff 
    

After I did this my tests ran correctly again.

How to find out if an item is present in a std::vector?

Use the STL find function.

Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if would give you an iterator that points to the first such element).

CentOS: Copy directory to another directory

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

denied: requested access to the resource is denied : docker

Docker also has a limit on the number of private repositories you can have. If you're creating a private repository by pushing from your local machine, it will create the repository but nothing further can be pushed to it or pulled from it, and you'll get the "requested access to the resource is denied" error.

What is difference between sleep() method and yield() method of multi threading?

Yield: It is a hint (not guaranteed) to the scheduler that you have done enough and that some other thread of same priority might run and use the CPU.

Thread.sleep();

Sleep: It blocks the execution of that particular thread for a given time.

TimeUnit.MILLISECONDS.sleep(1000);

jQuery get content between <div> tags

This is probably what you need:

$('div').html();

demo

This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/

If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so

$('#whatever').html();

where whatever is the id

EDIT

Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:

var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);

Demo Here

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.

React proptype array with shape

There's a ES6 shorthand import, you can reference. More readable and easy to type.

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

html cellpadding the left side of a cell

I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.

It is not hard to understand...

Anyway, I just put something like this inside my tag:

style='padding:5px 10px 5px 5px'

Where the order represents top, right, bottom and left.

How to change the buttons text using javascript

I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.

1- innerHTML

document.getElementById("ShowButton").innerHTML = 'Show Filter';

You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.

2- innerText

document.getElementById("ShowButton").innerText = 'Show Filter';

This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here

3- textContent

document.getElementById("ShowButton").textContent = 'Show Filter';

This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.

So if a text has to be added like above, then its better to use textContent.

How to clear an EditText on click?

Code for clearing up the text field when clicked

<EditText android:onClick="TextFieldClicked"/>

public void TextFieldClicked(View view){      
      if(view.getId()==R.id.editText1);
           text.setText("");    
}

Ruby, Difference between exec, system and %x() or Backticks

system

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

As of Ruby 2.6, passing exception: true will raise an exception instead of returning false or nil:

>> system('invalid')
=> nil

>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013   

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

%x()

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

exec

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Open3.popen3

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

Is it possible to animate scrollTop with jQuery?

If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:

$('body').animate({ scrollTop: $(document).height() });

Create a tag in a GitHub repository

In case you want to tag a specific commit like i do

Here's a command to do that :-

Example:

git tag -a v1.0 7cceb02 -m "Your message here"

Where 7cceb02 is the beginning part of the commit id.

You can then push the tag using git push origin v1.0.

You can do git log to show all the commit id's in your current branch.

How do I extract Month and Year in a MySQL date and compare them?

If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use

SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
 FROM Table Where Condition = 'Condition';

Java ArrayList how to add elements at the beginning

What you are describing, is an appropriate situation to use Queue.

Since you want to add new element, and remove the old one. You can add at the end, and remove from the beginning. That will not make much of a difference.

Queue has methods add(e) and remove() which adds at the end the new element, and removes from the beginning the old element, respectively.

Queue<Integer> queue = new LinkedList<Integer>();
queue.add(5);
queue.add(6);
queue.remove();  // Remove 5

So, every time you add an element to the queue you can back it up with a remove method call.


UPDATE: -

And if you want to fix the size of the Queue, then you can take a look at: - ApacheCommons#CircularFifoBuffer

From the documentation: -

CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.

Buffer queue = new CircularFifoBuffer(2); // Max size

queue.add(5);
queue.add(6);
queue.add(7);  // Automatically removes the first element `5`

As you can see, when the maximum size is reached, then adding new element automatically removes the first element inserted.

Disabling Strict Standards in PHP 5.4

Heads up, you might need to restart LAMP, Apache or whatever your using to make this take affect. Racked our brains for a while on this one, seemed to make no affect until services were restarted, presumably because the website was caching.

Is it possible to hide/encode/encrypt php source code and let others have the system?

https://toolki.com/en/php-decoder/

Decode hidden PHP eval(), gzinflate(), str_rot13(), str_replace() and base64_decode()

Getting the 'external' IP address in Java

If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.

Keep the order of the JSON keys during JSON conversion to CSV

You can use the following code to do custom ORDERED serialization and deserialization of JSON Array (This example assumes you are ordering Strings but can be applied to all types):

Serialization

JSONArray params = new JSONArray();
int paramIndex = 0;

for (String currParam : mParams)
{
    JSONObject paramObject = new JSONObject();
    paramObject.put("index", paramIndex);
    paramObject.put("value", currParam);

    params.put(paramObject);
    ++paramIndex;
}

json.put("orderedArray", params);

Deserialization

JSONArray paramsJsonArray = json.optJSONArray("orderedArray");
if (null != paramsJsonArray)
{
    ArrayList<String> paramsArr = new ArrayList<>();
    for (int i = 0; i < paramsJsonArray.length(); i++)
    {
        JSONObject param = paramsJsonArray.optJSONObject(i);
        if (null != param)
        {
            int paramIndex = param.optInt("index", -1);
            String paramValue = param.optString("value", null);

            if (paramIndex > -1 && null != paramValue)
            {
                paramsArr.add(paramIndex, paramValue);
            }
        }
    }
}

Cannot install packages using node package manager in Ubuntu

On Linux Mint 17, I tried both solutions (creating a symlink or using the nodejs-legacy package) without success.

The only thing that finally worked for me was using the ppa from Chris Lea:

sudo apt-get purge node-*
sudo apt-get autoremove 
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

This installed node version 10.37 and npm 1.4.28. After that, I could install packages globally.

Join String list elements with a delimiter in one step

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

Inconsistent Accessibility: Parameter type is less accessible than method

You can get Parameter (class that have less accessibility) as object then convert it to your class by as keyword.

How to read and write to a text file in C++?

Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.

Some things to keep in mind, use single quotes ' when dealing with single characters, and double " for strings. Also it is a bad habit to use global variables when not necessary.

Have fun!

CSS media queries: max-width OR max-height

Use a comma to specify two (or more) different rules:

@media screen and (max-width: 995px), 
       screen and (max-height: 700px) {
  ...
}

From https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Commas are used to combine multiple media queries into a single rule. Each query in a comma-separated list is treated separately from the others. Thus, if any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like a logical or operator.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

using if else with eval in aspx page

 <%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
                        &nbsp;[<%=System.Environment.MachineName%>]
                        <%}%>

jQuery fade out then fade in

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}

ng-if, not equal to?

Try this:

ng-if="details.Payment[0].Status != '6'".

Sorry about that, but I think you can use ng-show or ng-hide.

Check if a variable is between two numbers with Java

<<= is like +=, but for a left shift. x <<= 1 means x = x << 1. That's why 90 >>= angle doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1), and you're stuck writing it out the long way.

How to select unique records by SQL

just use inner join because group by won't work with multiple columns saying not contained in either an aggregate function.

SELECT a.*
FROM yourtable a
INNER JOIN 
  (SELECT yourcolumn,
    MIN(id) as id
  FROM yourtable 
  GROUP BY yourcolumn
) AS b
  ON a.yourcolumn= b.yourcolumn
  AND a.id = b.id;

Detecting an undefined object property

A simple way to check if a key exists is to use in:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

Calculate the center point of multiple latitude/longitude coordinate pairs

Here is the python Version for finding center point. The lat1 and lon1 are latitude and longitude lists. it will retuen the latitude and longitude of center point.

def GetCenterFromDegrees(lat1,lon1):    
    if (len(lat1) <= 0):
    return false;

num_coords = len(lat1)

X = 0.0
Y = 0.0
Z = 0.0

for i in range (len(lat1)):
    lat = lat1[i] * np.pi / 180
    lon = lon1[i] * np.pi / 180

    a = np.cos(lat) * np.cos(lon)
    b = np.cos(lat) * np.sin(lon)
    c = np.sin(lat);

    X += a
    Y += b
    Z += c


X /= num_coords
Y /= num_coords
Z /= num_coords

lon = np.arctan2(Y, X)
hyp = np.sqrt(X * X + Y * Y)
lat = np.arctan2(Z, hyp)

newX = (lat * 180 / np.pi)
newY = (lon * 180 / np.pi)
return newX, newY

Convert an image to grayscale in HTML/CSS

One terrible but workable solution: render the image using a Flash object, which then gives you all the transformations possible in Flash.

If your users are using bleeding-edge browsers and if Firefox 3.5 and Safari 4 support it (I don't know that either do/will), you could adjust the CSS color-profile attribute of the image, setting it to a grayscale ICC profile URL. But that's a lot of if's!

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

Removing address bar from browser (to view on Android)

The problem with most of these is that the user can still scroll up and see the addressbar. To make a permanent solution, you need to add this as well.

//WHENEVER the user scrolls
$(window).scroll(function(){
    //if you reach the top
    if ($(window).scrollTop() == 0)   
    //scroll back down  
    {window.scrollTo(1,1)}
})

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

How to trap on UIViewAlertForUnsatisfiableConstraints?

You'll want to add a Symbolic Breakpoint. Apple provides an excellent guide on how to do this.

  1. Open the Breakpoint Navigator cmd+7 (cmd+8 in Xcode 9)
  2. Click the Add button in the lower left
  3. Select Add Symbolic Breakpoint...
  4. Where it says Symbol just type in UIViewAlertForUnsatisfiableConstraints

You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.

Emulator error: This AVD's configuration is missing a kernel file

Make sure that you also have configured properly an emulated device. Android Studio may come with one that shows up in the list of emulated devices but that is not set to work with the SDK version you are using.

Try creating a new emulated device in the AVD Manager (Tools->Android>AVD Manager) and selecting that as the target.

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

How do I kill a VMware virtual machine that won't die?

If you're on linux then you can grab the guest processes with

ps axuw | grep vmware-vmx

As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD

minimum double value in C/C++

If you do not have float exceptions enabled (which you shouldn't imho), you can simply say:

double neg_inf = -1/0.0;

This yields negative infinity. If you need a float, you can either cast the result

float neg_inf = (float)-1/0.0;

or use single precision arithmetic

float neg_inf = -1.0f/0.0f;

The result is always the same, there is exactly one representation of negative infinity in both single and double precision, and they convert to each other as you would expect.

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

How to debug Ruby scripts

To easily debug Ruby shell script, just change its first line from:

#!/usr/bin/env ruby

to:

#!/usr/bin/env ruby -rdebug

Then every time when debugger console is shown, you can choose:

  • c for Continue (to the next Exception, breakpoint or line with: debugger),
  • n for Next line,
  • w/where to Display frame/call stack,
  • l to Show the current code,
  • cat to show catchpoints.
  • h for more Help.

See also: Debugging with ruby-debug, Key shortcuts for ruby-debug gem.


In case the script just hangs and you need a backtrace, try using lldb/gdb like:

echo 'call (void)rb_backtrace()' | lldb -p $(pgrep -nf ruby)

and then check your process foreground.

Replace lldb with gdb if works better. Prefix with sudo to debug non-owned process.

node.js execute system command synchronously

I get used to implement "synchronous" stuff at the end of the callback function. Not very nice, but it works. If you need to implement a sequence of command line executions you need to wrap exec into some named function and recursively call it. This pattern seem to be usable for me:

SeqOfExec(someParam);

function SeqOfExec(somepParam) {
    // some stuff
    // .....
    // .....

    var execStr = "yourExecString";
    child_proc.exec(execStr, function (error, stdout, stderr) {
        if (error != null) {
            if (stdout) {
                throw Error("Smth goes wrong" + error);
            } else {
                // consider that empty stdout causes
                // creation of error object
            }
        }
        // some stuff
        // .....
        // .....

        // you also need some flag which will signal that you 
        // need to end loop
        if (someFlag ) {
            // your synch stuff after all execs
            // here
            // .....
        } else {
            SeqOfExec(someAnotherParam);
        }
    });
};

logout and redirecting session in php

<?php

session_start();

session_unset();

session_destroy();

header("location:home.php");

exit();

?>

Case insensitive 'in'

You could do

matcher = re.compile('MICHAEL89', re.IGNORECASE)
filter(matcher.match, USERNAMES) 

Update: played around a bit and am thinking you could get a better short-circuit type approach using

matcher = re.compile('MICHAEL89', re.IGNORECASE)
if any( ifilter( matcher.match, USERNAMES ) ):
    #your code here

The ifilter function is from itertools, one of my favorite modules within Python. It's faster than a generator but only creates the next item of the list when called upon.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

Also make sure that the following property is set in your hibernate bean configuration:

<property name="packagesToScan" value="yourpackage" />

This tells spring and hibernate where to find your domain classes annotated as entities.

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

Using a SELECT statement within a WHERE clause

This is a correlated sub-query.

(It is a "nested" query - this is very non-technical term though)

The inner query takes values from the outer-query (WHERE st.Date = ScoresTable.Date) thus it is evaluated once for each row in the outer query.

There is also a non-correlated form in which the inner query is independent as as such is only executed once.

e.g.

 SELECT * FROM ScoresTable WHERE Score = 
   (SELECT MAX(Score) FROM Scores)

There is nothing wrong with using subqueries, except where they are not needed :)

Your statement may be rewritable as an aggregate function depending on what columns you require in your select statement.

SELECT Max(score), Date FROM ScoresTable 
Group By Date

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

typedef struct vs struct definitions

The common idiom is using both:

typedef struct S { 
    int x; 
} S;

They are different definitions. To make the discussion clearer I will split the sentence:

struct S { 
    int x; 
};

typedef struct S S;

In the first line you are defining the identifier S within the struct name space (not in the C++ sense). You can use it and define variables or function arguments of the newly defined type by defining the type of the argument as struct S:

void f( struct S argument ); // struct is required here

The second line adds a type alias S in the global name space and thus allows you to just write:

void f( S argument ); // struct keyword no longer needed

Note that since both identifier name spaces are different, defining S both in the structs and global spaces is not an error, as it is not redefining the same identifier, but rather creating a different identifier in a different place.

To make the difference clearer:

typedef struct S { 
    int x; 
} T;

void S() { } // correct

//void T() {} // error: symbol T already defined as an alias to 'struct S'

You can define a function with the same name of the struct as the identifiers are kept in different spaces, but you cannot define a function with the same name as a typedef as those identifiers collide.

In C++, it is slightly different as the rules to locate a symbol have changed subtly. C++ still keeps the two different identifier spaces, but unlike in C, when you only define the symbol within the class identifier space, you are not required to provide the struct/class keyword:

 // C++
struct S { 
    int x; 
}; // S defined as a class

void f( S a ); // correct: struct is optional

What changes are the search rules, not where the identifiers are defined. The compiler will search the global identifier table and after S has not been found it will search for S within the class identifiers.

The code presented before behaves in the same way:

typedef struct S { 
    int x; 
} T;

void S() {} // correct [*]

//void T() {} // error: symbol T already defined as an alias to 'struct S'

After the definition of the S function in the second line, the struct S cannot be resolved automatically by the compiler, and to create an object or define an argument of that type you must fall back to including the struct keyword:

// previous code here...
int main() {
    S(); 
    struct S s;
}

I don't understand -Wl,-rpath -Wl,

The man page makes it pretty clear. If you want to pass two arguments (-rpath and .) to the linker you can write

-Wl,-rpath,.

or alternatively

-Wl,-rpath -Wl,.

The arguments -Wl,-rpath . you suggested do NOT make sense to my mind. How is gcc supposed to know that your second argument (.) is supposed to be passed to the linker instead of being interpreted normally? The only way it would be able to know that is if it had insider knowledge of all possible linker arguments so it knew that -rpath required an argument after it.

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

Python Serial: How to use the read or readline function to read more than 1 character at a time

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n indicating one line.

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

EDIT

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Modular multiplicative inverse function in Python

Well, I don't have a function in python but I have a function in C which you can easily convert to python, in the below c function extended euclidian algorithm is used to calculate inverse mod.

int imod(int a,int n){
int c,i=1;
while(1){
    c = n * i + 1;
    if(c%a==0){
        c = c/a;
        break;
    }
    i++;
}
return c;}

Python Function

def imod(a,n):
  i=1
  while True:
    c = n * i + 1;
    if(c%a==0):
      c = c/a
      break;
    i = i+1

  return c

Reference to the above C function is taken from the following link C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers

org.hibernate.MappingException: Unknown entity

My issue was resolved After adding
sessionFactory.setPackagesToScan( new String[] { "com.springhibernate.model" }); Tested this Functionality in spring boot latest version 2.1.2.

Full Method:

 @Bean( name="sessionFactoryConfig")
    public LocalSessionFactoryBean sessionFactoryConfig() {

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        sessionFactory.setDataSource(dataSourceConfig());
        sessionFactory.setPackagesToScan(
                new String[] { "com.springhibernate.model" });

        sessionFactory.setHibernateProperties(hibernatePropertiesConfig());

        return sessionFactory;
    }

What is the difference between "is None" and "== None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

MySQL: What's the difference between float and double?

Doubles are just like floats, except for the fact that they are twice as large. This allows for a greater accuracy.

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

Increase days to php current Date()

a day is 86400 seconds.

$tomorrow = date('y:m:d', time() + 86400);

Python: importing a sub-package or sub-module

You seem to be misunderstanding how import searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:

import package.subpackage.module
from package.subpackage import module
from module import attribute1

The second line looks for a package called package.subpackage and imports module from that package. This line has no effect on the third line. The third line just looks for a module called module and doesn't find one. It doesn't "re-use" the object called module that you got from the line above.

In other words from someModule import ... doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.

It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1 and be done with it. You need never worry about the long package.subpackage.module once you've imported the name you want from it.

If you do want to have access to the module to access other names later, then you can do from package.subpackage import module and, as you've seen you can then do module.attribute1 and so on as much as you like.

If you want both --- that is, if you want attribute1 directly accessible and you want module accessible, just do both of the above:

from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works

If you don't like typing package.subpackage even twice, you can just manually create a local reference to attribute1:

from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works

AppCompat v7 r21 returning error in values.xml?

I was facing this problem when I imported google-services.json file to implement Analytics. I already had global_tracker.xml file in the xml folder. During build, while merging contents from google-services.json file, the error was started occurring. For time being, the error is resolved after removing the goolgle-services.json file. And using the older Analytics solution.

Check the last XML or Json file that you edited/imported and maybe you will file error there. That's what helped in my case.

How can I force clients to refresh JavaScript files?

Simplest solution? Don't let the browser cache at all. Append the current time (in ms) as a query.

(You are still in beta, so you could make a reasonable case for not optimizing for performance. But YMMV here.)

How to run a shell script in OS X by double-clicking?

  • First in terminal make the script executable by typing the following command:

      chmod a+x yourscriptname
    
  • Then, in Finder, right-click your file and select "Open with" and then "Other...".

  • Here you select the application you want the file to execute into, in this case it would be Terminal. To be able to select terminal you need to switch from "Recommended Applications" to "All Applications". (The Terminal.app application can be found in the Utilities folder)

  • NOTE that unless you don't want to associate all files with this extension to be run in terminal you should not have "Always Open With" checked.

  • After clicking OK you should be able to execute you script by simply double-clicking it.

How to put php inside JavaScript?

The only proper way to put server side data into generated javascript code:

<?php $jsString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">      
      var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
      alert(jsStringFromPhp);
    </script>
  </body>
</html>

With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...

For similar reasons I recommend to use document.createTextNode() instead of setting the innerHTML. Ofc. it is slower, but more secure...

Java equivalent to C# extension methods

Bit late to the party on this question, but in case anyone finds it useful I just created a subclass:

public class ArrayList2<T> extends ArrayList<T> 
{
    private static final long serialVersionUID = 1L;

    public T getLast()
    {
        if (this.isEmpty())
        {
            return null;
        }
        else
        {       
            return this.get(this.size() - 1);
        }
    }
}

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Precision String Format Specifier In Swift

The answers given so far that have received the most votes are relying on NSString methods and are going to require that you have imported Foundation.

Having done that, though, you still have access to NSLog.

So I think the answer to the question, if you are asking how to continue using NSLog in Swift, is simply:

import Foundation

CKEditor, Image Upload (filebrowserUploadUrl)

The URL should point to your own custom filebrowser url you might have.

I have already done this in one of my projects, and I have posted a tutorial on this topic on my blog

http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/

The tutorial gives a step by step instructions about how to integrate the inbuilt FileBrowser of FCKEditor in CKEditor, if you don't want to make our own. Its pretty simple.

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I encountered the same error and got stalled with a pyspark dataframe for few days, I was able to resolve it successfully by filling na values with 0 since I was comparing integer values from 2 fields.

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Download and open PDF file using Ajax

The following code worked for me

//Parameter to be passed
var data = 'reportid=R3823&isSQL=1&filter=[]';
var xhr = new XMLHttpRequest();
xhr.open("POST", "Reporting.jsp"); //url.It can pdf file path
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response]);
        const url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'myFile.pdf';
        a.click();
        setTimeout(function () {
            // For Firefox it is necessary to delay revoking the ObjectURL
            window.URL.revokeObjectURL(data)
                , 100
        })
    }
};
xhr.send(data);

scrollable div inside container

If you put overflow: scroll on a fixed height div, the div will scroll if the contents take up too much space.

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

How to display 3 buttons on the same line in css

The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:

<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc. 

The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.

deny directory listing with htaccess

Try adding this to the .htaccess file in that directory.

Options -Indexes

This has more information.

Dropping a connected user from an Oracle 10g database schema

Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do

ALTER SCHEMA KILL SESSION sid,serial#;

Disable Input fields in reactive form

I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

Factorial in numpy and scipy

The answer for Ashwini is great, in pointing out that scipy.math.factorial, numpy.math.factorial, math.factorial are the same functions. However, I'd recommend use the one that Janne mentioned, that scipy.special.factorial is different. The one from scipy can take np.ndarray as an input, while the others can't.

In [12]: import scipy.special

In [13]: temp = np.arange(10) # temp is an np.ndarray

In [14]: math.factorial(temp) # This won't work
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-039ec0734458> in <module>()
----> 1 math.factorial(temp)

TypeError: only length-1 arrays can be converted to Python scalars

In [15]: scipy.special.factorial(temp) # This works!
Out[15]: 
array([  1.00000000e+00,   1.00000000e+00,   2.00000000e+00,
         6.00000000e+00,   2.40000000e+01,   1.20000000e+02,
         7.20000000e+02,   5.04000000e+03,   4.03200000e+04,
         3.62880000e+05])

So, if you are doing factorial to a np.ndarray, the one from scipy will be easier to code and faster than doing the for-loops.

Convert a String to int?

So basically you want to convert a String into an Integer right! here is what I mostly use and that is also mentioned in official documentation..

fn main() {

    let char = "23";
    let char : i32 = char.trim().parse().unwrap();
    println!("{}", char + 1);

}

This works for both String and &str Hope this will help too.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

Here is my approach, clunky as it is and available in github:

Put in the very first notebook cell, the import cell:

from IPythonTOC import IPythonTOC

toc = IPythonTOC()

Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:

''' if you called toc.genTOCMarkdownCell before running this cell, 
the title has been set in the class '''

print toc.genTOCEntry()

Below the genTOCEntry cell`, make a TOC cell as a markdown cell:

<a id='TOC'></a>

#TOC

As the notebook is developed, put this genTOCMarkdownCell before starting a new section:

with open('TOCMarkdownCell.txt', 'w') as outfile:

    outfile.write(toc.genTOCMarkdownCell('Introduction'))

!cat TOCMarkdownCell.txt

!rm TOCMarkdownCell.txt

Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:

<a id='Introduction'></a>

###Introduction

Then when you go to the top of your notebook and run genTocEntry, you get the output:

[Introduction](#Introduction)

Copy this link string and paste it into the TOC markdown cell as follows:

<a id='TOC'></a>

#TOC

[Introduction](#Introduction)

After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.

One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

in_array() and multidimensional array

Please try:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

Im not sure about the need, but this might work for your requirement

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

If you have this problem when you pull a react-native project, you just need to open the android project with Android Studio. Everything you need will be automatically created.

  • Open Android Studio
  • File -> Open
  • Choose the android folder under your react-native project folder
  • Wait for AndroidStudio to complete setup
  • You can now close Android Studio

OR

If you have installed the AndroidStudio command line launcher:

  • Run this in your react-native root folder
studio android/
  • Wait for AndroidStudio to complete setup
  • You can now close Android Studio

get current date and time in groovy?

Date has the time as well, just add HH:mm:ss to the date format:

import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)

In case you are using JRE 8 you can use LoaclDateTime:

import java.time.*

LocalDateTime t = LocalDateTime.now();
return t as String

Cut Corners using CSS

With a small edit to Joseph's code, the element does not require a solid background:

div {
    height: 300px;
    background: url('http://images2.layoutsparks.com/1/190037/serene-nature-scenery-blue.jpg');
    position: relative;
}

div:before {
    content: '';
    position: absolute;
    top: 0; right: 0;
    border-top: 80px solid white;
    border-left: 80px solid rgba(0,0,0,0);
    width: 0;
}

http://jsfiddle.net/2bZAW/1921/

This use of 'rgba(0,0,0,0)' allows the inner 'corner' to be invisible .

You can also edit the 4th parameter 'a', where 0 < a < 1, to have a shadow for more of a 'folded-corner' effect:

http://jsfiddle.net/2bZAW/1922/ (with shadow)


NOTE: RGBA color values are supported in IE9+, Firefox 3+, Chrome, Safari, and in Opera 10+.

How to generate a simple popup using jQuery

I use a jQuery plugin called ColorBox, it is

  1. Very easy to use
  2. lightweight
  3. customizable
  4. the nicest popup dialog I have seen for jQuery yet

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

Do a force Maven Update which will bring the compatible 1.8 Jar Versions and then while building, update the JRE Versions in Execute environment to 1.8 from Run Configurations and hit RUN

How to parse JSON data with jQuery / JavaScript?

Json data

data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}

When retrieve

$.ajax({
  //type
  //url
  //data
  dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});

How to parse JSON in Java

There are many JSON libraries available in Java.

The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.

There are typically three things one should look at for choosing any library:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. For mobile apps: dependency/jar size

Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.

For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...

Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.

For your particular example, the following code decodes your json with jackson:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

Let me know if you have any questions.

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

Convert date time string to epoch in Bash

What you're looking for is date --date='06/12/2012 07:21:22' +"%s". Keep in mind that this assumes you're using GNU coreutils, as both --date and the %s format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.

Consult the appropriate manual page for other versions of date.

Note: bash --date and -d option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy or yyyy-mm-dd, not in UK, EU, or any other format.

How do I vertically center text with CSS?

<!DOCTYPE html>
<html>
  <head>
    <style>
      .main{
        height:450px;
        background:#f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        -webkit-box-align: center;
        align-items: center;
        justify-content: center;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="main">
      <h1>Hello</h1>
    </div>
  </body>
</html>

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

What is the copy-and-swap idiom?

Overview

Why do we need the copy-and-swap idiom?

Any class that manages a resource (a wrapper, like a smart pointer) needs to implement The Big Three. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls need to be avoided?

The copy-and-swap idiom is the solution, and elegantly assists the assignment operator in achieving two things: avoiding code duplication, and providing a strong exception guarantee.

How does it work?

Conceptually, it works by using the copy-constructor's functionality to create a local copy of the data, then takes the copied data with a swap function, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.

In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a swap function.

A swap function is a non-throwing function that swaps two objects of a class, member for member. We might be tempted to use std::swap instead of providing our own, but this would be impossible; std::swap uses the copy-constructor and copy-assignment operator within its implementation, and we'd ultimately be trying to define the assignment operator in terms of itself!

(Not only that, but unqualified calls to swap will use our custom swap operator, skipping over the unnecessary construction and destruction of our class that std::swap would entail.)


An in-depth explanation

The goal

Let's consider a concrete case. We want to manage, in an otherwise useless class, a dynamic array. We start with a working constructor, copy-constructor, and destructor:

#include <algorithm> // std::copy
#include <cstddef> // std::size_t

class dumb_array
{
public:
    // (default) constructor
    dumb_array(std::size_t size = 0)
        : mSize(size),
          mArray(mSize ? new int[mSize]() : nullptr)
    {
    }

    // copy-constructor
    dumb_array(const dumb_array& other)
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : nullptr),
    {
        // note that this is non-throwing, because of the data
        // types being used; more attention to detail with regards
        // to exceptions must be given in a more general case, however
        std::copy(other.mArray, other.mArray + mSize, mArray);
    }

    // destructor
    ~dumb_array()
    {
        delete [] mArray;
    }

private:
    std::size_t mSize;
    int* mArray;
};

This class almost manages the array successfully, but it needs operator= to work correctly.

A failed solution

Here's how a naive implementation might look:

// the hard part
dumb_array& operator=(const dumb_array& other)
{
    if (this != &other) // (1)
    {
        // get rid of the old data...
        delete [] mArray; // (2)
        mArray = nullptr; // (2) *(see footnote for rationale)

        // ...and put in the new
        mSize = other.mSize; // (3)
        mArray = mSize ? new int[mSize] : nullptr; // (3)
        std::copy(other.mArray, other.mArray + mSize, mArray); // (3)
    }

    return *this;
}

And we say we're finished; this now manages an array, without leaks. However, it suffers from three problems, marked sequentially in the code as (n).

  1. The first is the self-assignment test. This check serves two purposes: it's an easy way to prevent us from running needless code on self-assignment, and it protects us from subtle bugs (such as deleting the array only to try and copy it). But in all other cases it merely serves to slow the program down, and act as noise in the code; self-assignment rarely occurs, so most of the time this check is a waste. It would be better if the operator could work properly without it.

  2. The second is that it only provides a basic exception guarantee. If new int[mSize] fails, *this will have been modified. (Namely, the size is wrong and the data is gone!) For a strong exception guarantee, it would need to be something akin to:

    dumb_array& operator=(const dumb_array& other)
    {
        if (this != &other) // (1)
        {
            // get the new data ready before we replace the old
            std::size_t newSize = other.mSize;
            int* newArray = newSize ? new int[newSize]() : nullptr; // (3)
            std::copy(other.mArray, other.mArray + newSize, newArray); // (3)
    
            // replace the old data (all are non-throwing)
            delete [] mArray;
            mSize = newSize;
            mArray = newArray;
        }
    
        return *this;
    }
    
  3. The code has expanded! Which leads us to the third problem: code duplication. Our assignment operator effectively duplicates all the code we've already written elsewhere, and that's a terrible thing.

In our case, the core of it is only two lines (the allocation and the copy), but with more complex resources this code bloat can be quite a hassle. We should strive to never repeat ourselves.

(One might wonder: if this much code is needed to manage one resource correctly, what if my class manages more than one? While this may seem to be a valid concern, and indeed it requires non-trivial try/catch clauses, this is a non-issue. That's because a class should manage one resource only!)

A successful solution

As mentioned, the copy-and-swap idiom will fix all these issues. But right now, we have all the requirements except one: a swap function. While The Rule of Three successfully entails the existence of our copy-constructor, assignment operator, and destructor, it should really be called "The Big Three and A Half": any time your class manages a resource it also makes sense to provide a swap function.

We need to add swap functionality to our class, and we do that as follows†:

class dumb_array
{
public:
    // ...

    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        // enable ADL (not necessary in our case, but good practice)
        using std::swap;

        // by swapping the members of two objects,
        // the two objects are effectively swapped
        swap(first.mSize, second.mSize);
        swap(first.mArray, second.mArray);
    }

    // ...
};

(Here is the explanation why public friend swap.) Now not only can we swap our dumb_array's, but swaps in general can be more efficient; it merely swaps pointers and sizes, rather than allocating and copying entire arrays. Aside from this bonus in functionality and efficiency, we are now ready to implement the copy-and-swap idiom.

Without further ado, our assignment operator is:

dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}

And that's it! With one fell swoop, all three problems are elegantly tackled at once.

Why does it work?

We first notice an important choice: the parameter argument is taken by-value. While one could just as easily do the following (and indeed, many naive implementations of the idiom do):

dumb_array& operator=(const dumb_array& other)
{
    dumb_array temp(other);
    swap(*this, temp);

    return *this;
}

We lose an important optimization opportunity. Not only that, but this choice is critical in C++11, which is discussed later. (On a general note, a remarkably useful guideline is as follows: if you're going to make a copy of something in a function, let the compiler do it in the parameter list.‡)

Either way, this method of obtaining our resource is the key to eliminating code duplication: we get to use the code from the copy-constructor to make the copy, and never need to repeat any bit of it. Now that the copy is made, we are ready to swap.

Observe that upon entering the function that all the new data is already allocated, copied, and ready to be used. This is what gives us a strong exception guarantee for free: we won't even enter the function if construction of the copy fails, and it's therefore not possible to alter the state of *this. (What we did manually before for a strong exception guarantee, the compiler is doing for us now; how kind.)

At this point we are home-free, because swap is non-throwing. We swap our current data with the copied data, safely altering our state, and the old data gets put into the temporary. The old data is then released when the function returns. (Where upon the parameter's scope ends and its destructor is called.)

Because the idiom repeats no code, we cannot introduce bugs within the operator. Note that this means we are rid of the need for a self-assignment check, allowing a single uniform implementation of operator=. (Additionally, we no longer have a performance penalty on non-self-assignments.)

And that is the copy-and-swap idiom.

What about C++11?

The next version of C++, C++11, makes one very important change to how we manage resources: the Rule of Three is now The Rule of Four (and a half). Why? Because not only do we need to be able to copy-construct our resource, we need to move-construct it as well.

Luckily for us, this is easy:

class dumb_array
{
public:
    // ...

    // move constructor
    dumb_array(dumb_array&& other) noexcept ††
        : dumb_array() // initialize via default constructor, C++11 only
    {
        swap(*this, other);
    }

    // ...
};

What's going on here? Recall the goal of move-construction: to take the resources from another instance of the class, leaving it in a state guaranteed to be assignable and destructible.

So what we've done is simple: initialize via the default constructor (a C++11 feature), then swap with other; we know a default constructed instance of our class can safely be assigned and destructed, so we know other will be able to do the same, after swapping.

(Note that some compilers do not support constructor delegation; in this case, we have to manually default construct the class. This is an unfortunate but luckily trivial task.)

Why does that work?

That is the only change we need to make to our class, so why does it work? Remember the ever-important decision we made to make the parameter a value and not a reference:

dumb_array& operator=(dumb_array other); // (1)

Now, if other is being initialized with an rvalue, it will be move-constructed. Perfect. In the same way C++03 let us re-use our copy-constructor functionality by taking the argument by-value, C++11 will automatically pick the move-constructor when appropriate as well. (And, of course, as mentioned in previously linked article, the copying/moving of the value may simply be elided altogether.)

And so concludes the copy-and-swap idiom.


Footnotes

*Why do we set mArray to null? Because if any further code in the operator throws, the destructor of dumb_array might be called; and if that happens without setting it to null, we attempt to delete memory that's already been deleted! We avoid this by setting it to null, as deleting null is a no-operation.

†There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.

‡The reason is simple: once you have the resource to yourself, you may swap and/or move it (C++11) anywhere it needs to be. And by making the copy in the parameter list, you maximize optimization.

††The move constructor should generally be noexcept, otherwise some code (e.g. std::vector resizing logic) will use the copy constructor even when a move would make sense. Of course, only mark it noexcept if the code inside doesn't throw exceptions.