Programs & Examples On #Pdksh

pdksh is the public domain clone of the AT&T Bell Labs Korn shell.

Tesseract OCR simple example

I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

Why am I not getting a java.util.ConcurrentModificationException in this example?

I had that same problem but in case that I was adding en element into iterated list. I made it this way

public static void remove(Integer remove) {
    for(int i=0; i<integerList.size(); i++) {
        //here is maybe fine to deal with integerList.get(i)==null
        if(integerList.get(i).equals(remove)) {                
            integerList.remove(i);
        }
    }
}

Now everything goes fine because you don't create any iterator over your list, you iterate over it "manually". And condition i < integerList.size() will never fool you because when you remove/add something into List size of the List decrement/increment..

Hope it helps, for me that was solution.

How can I make a countdown with NSTimer?

Swift 5 with Closure:

class ViewController: UIViewController {
    
var secondsRemaining = 30
    
@IBAction func startTimer(_ sender: UIButton) {
        
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
        if self.secondsRemaining > 0 {
            print ("\(self.secondsRemaining) seconds")
            self.secondsRemaining -= 1
        } else {
            Timer.invalidate()
        }
    }
            
}

How do you run a crontab in Cygwin on Windows?

Applied the instructions from this answer and it worked Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:

 cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
 set package_name=cygrunsrv cron
 setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%

Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...

Now in cmd promt:

 C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D   

or whatever full file path you might have to the cygrunsrv.exe and start the cron as windows service in the cmd prompt

 net start cron

Now in bash terminal run crontab -e

set up you cron entry an example bellow:

        #sync my gdrive each 10th minute
    */10 * * * * /home/Yordan/sync_gdrive.sh

    # * * * * * command to be executed
    # - - - - -
    # | | | | |
    # | | | | +- - - - day of week (0 - 6) (Sunday=0)
    # | | | +- - - - - month (1 - 12)
    # | | +- - - - - - day of month (1 - 31)
    # | +- - - - - - - hour (0 - 23)
    # +--------------- minute

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

You misspelled permission

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

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList). When I tried to add the receiver content through MessageListener (separate thread), application quits with above error. I solved this by adding the content to my arraylist & setListviewadapater through runOnUiThread method which is part of Activity class. This solved my problem.

How do I change a TCP socket to be non-blocking?

The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:

long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
    printf("ioctl FIONBIO call failed\n");
}

Show Error on the tip of the Edit Text Android

It seems all you can't get is to show the error at the end of editText. Set your editText width to match that of the parent layout enveloping. Will work just fine.

How to find the day, month and year with moment.js

Just try with:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle

How can I set my Cygwin PATH to find javac?

If you are still finding that the default wrong Java version (1.7) is being used instead of your Java home directory, then all you need to do is simply change the order of your PATH variable to set JAVA_HOME\bin before your Windows directory in your PATH variable, save it and restart cygwin. Test it out to make sure everything will work fine. It should not have any adverse effect because you want your own Java version to override the default which comes with Windows. Good luck!

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

.htaccess mod_rewrite - how to exclude directory from rewrite rule

If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]

The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .

To exclude all existent directries, you will need to use the following condition above your rule :

RewriteCond %{REQUEST_FILENAME} !-d

the following rule

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]

rewrites everything (except directries) to /index.php .

Export a graph to .eps file with R

Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to setEPS()

cairo_ps("image.eps")
plot(1, 10)
dev.off()

SQL to add column and comment in table in single command

Add comments for two different columns of the EMPLOYEE table :

COMMENT ON EMPLOYEE
     (WORKDEPT IS 'see DEPARTMENT table for names',
     EDLEVEL IS 'highest grade level passed in school' )

How to prevent errno 32 broken pipe?

The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.

Python: finding lowest integer

Or no float conversion at all by just specifying floats in the list.

l = [-1.2, 0.0, 1]
x = min(l)

or

l = min([-1.2, 0.0, 1])

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

How do I convert a number to a numeric, comma-separated formatted string?

I looked at several of the options. Here are my two favorites, because I needed to round the value.

,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2   = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy --------- 
--- Hank Freeman : [email protected] 
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
   SELECT
   FileGroupName = DS.name
   ,FileGroupType =
      CASE DS.[type]
        WHEN 'FG' THEN 'Filegroup'
        WHEN 'FD' THEN 'Filestream'
        WHEN 'FX' THEN 'Memory-optimized'
        WHEN 'PS' THEN 'Partition Scheme'
        ELSE 'Unknown'
      END
   ,SchemaName = SCH.name
   ,TableName = OBJ.name
   ,IndexType =
      CASE IDX.[type]
        WHEN 0 THEN 'Heap'
        WHEN 1 THEN 'Clustered'
        WHEN 2 THEN 'Nonclustered'
        WHEN 3 THEN 'XML'
        WHEN 4 THEN 'Spatial'
        WHEN 5 THEN 'Clustered columnstore'
        WHEN 6 THEN 'Nonclustered columnstore'
        WHEN 7 THEN 'Nonclustered hash'
      END
   ,IndexName = IDX.name
   ,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','')  --- MUST show for all types when no Primary key
   --,( Case WHEN IDX.[type] IN (2,6,7) then 0  else  p.rows  end )as Rowcounts_T
   ,AllocationDesc = AU.type_desc
/*
   ,RowCounts = p.rows  --- MUST show for all types when no Primary key
   ,TotalSizeKB2  = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
   ,UsedSizeKB    = Cast(Round(SUM(AU.used_pages / 0.128),0)as int) 
   ,DataSizeKB    = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
    --replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
   ,TotalSizeKB   = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
   ,UsedSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','') 
   ,DataSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
   ,DataSizeKB2   = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
   ,DataSizeKB3   = format(SUM(AU.data_pages / 0.128),'##,##0')
   --SELECT Format(1234567.8, '##,##0.00')
   ---
   ,is_default    = CONVERT(INT,DS.is_default)
   ,is_read_only = CONVERT(INT,DS.is_read_only)
  FROM
   sys.filegroups DS -- you could also use sys.data_spaces
    LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
    LEFT JOIN sys.partitions PA
      ON (AU.[type] IN (1,3) AND
          AU.container_id = PA.hobt_id) OR
         (AU.[type] = 2 AND
          AU.container_id = PA.[partition_id])
    LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
    LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
    LEFT JOIN sys.indexes IDX
      ON PA.[object_id] = IDX.[object_id] AND
         PA.index_id = IDX.index_id
    -----
    INNER JOIN 
      sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
  WHERE
    OBJ.type_desc = 'USER_TABLE' -- only include user tables
    OR
    DS.[type] = 'FD' -- or the filestream filegroup
  GROUP BY
    DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type]  ,DS.is_default   ,DS.is_read_only -- discard different allocation units
   ,p.rows  ,AU.type_desc  --- 
  ORDER BY
    DS.name ,SCH.name ,OBJ.name ,IDX.name
   ---
   ;

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

SQL left join vs multiple tables on FROM line?

The old syntax, with just listing the tables, and using the WHERE clause to specify the join criteria, is being deprecated in most modern databases.

It's not just for show, the old syntax has the possibility of being ambiguous when you use both INNER and OUTER joins in the same query.

Let me give you an example.

Let's suppose you have 3 tables in your system:

Company
Department
Employee

Each table contain numerous rows, linked together. You got multiple companies, and each company can have multiple departments, and each department can have multiple employees.

Ok, so now you want to do the following:

List all the companies, and include all their departments, and all their employees. Note that some companies don't have any departments yet, but make sure you include them as well. Make sure you only retrieve departments that have employees, but always list all companies.

So you do this:

SELECT * -- for simplicity
FROM Company, Department, Employee
WHERE Company.ID *= Department.CompanyID
  AND Department.ID = Employee.DepartmentID

Note that the last one there is an inner join, in order to fulfill the criteria that you only want departments with people.

Ok, so what happens now. Well, the problem is, it depends on the database engine, the query optimizer, indexes, and table statistics. Let me explain.

If the query optimizer determines that the way to do this is to first take a company, then find the departments, and then do an inner join with employees, you're not going to get any companies that don't have departments.

The reason for this is that the WHERE clause determines which rows end up in the final result, not individual parts of the rows.

And in this case, due to the left join, the Department.ID column will be NULL, and thus when it comes to the INNER JOIN to Employee, there's no way to fulfill that constraint for the Employee row, and so it won't appear.

On the other hand, if the query optimizer decides to tackle the department-employee join first, and then do a left join with the companies, you will see them.

So the old syntax is ambiguous. There's no way to specify what you want, without dealing with query hints, and some databases have no way at all.

Enter the new syntax, with this you can choose.

For instance, if you want all companies, as the problem description stated, this is what you would write:

SELECT *
FROM Company
     LEFT JOIN (
         Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
     ) ON Company.ID = Department.CompanyID

Here you specify that you want the department-employee join to be done as one join, and then left join the results of that with the companies.

Additionally, let's say you only want departments that contains the letter X in their name. Again, with old style joins, you risk losing the company as well, if it doesn't have any departments with an X in its name, but with the new syntax, you can do this:

SELECT *
FROM Company
     LEFT JOIN (
         Department INNER JOIN Employee ON Department.ID = Employee.DepartmentID
     ) ON Company.ID = Department.CompanyID AND Department.Name LIKE '%X%'

This extra clause is used for the joining, but is not a filter for the entire row. So the row might appear with company information, but might have NULLs in all the department and employee columns for that row, because there is no department with an X in its name for that company. This is hard with the old syntax.

This is why, amongst other vendors, Microsoft has deprecated the old outer join syntax, but not the old inner join syntax, since SQL Server 2005 and upwards. The only way to talk to a database running on Microsoft SQL Server 2005 or 2008, using the old style outer join syntax, is to set that database in 8.0 compatibility mode (aka SQL Server 2000).

Additionally, the old way, by throwing a bunch of tables at the query optimizer, with a bunch of WHERE clauses, was akin to saying "here you are, do the best you can". With the new syntax, the query optimizer has less work to do in order to figure out what parts goes together.

So there you have it.

LEFT and INNER JOIN is the wave of the future.

Difference between two lists

var list3 = list1.Where(x => !list2.Any(z => z.Id == x.Id)).ToList();

Note: list3 will contain the items or objects that are not in both lists. Note: Its ToList() not toList()

Ruby class instance variable vs. class variable

For those with a C++ background, you may be interested in a comparison with the C++ equivalent:

class S
{
private: // this is not quite true, in Ruby you can still access these
  static int    k = 23;
  int           s = 15;

public:
  int get_s() { return s; }
  static int get_k() { return k; }

};

std::cerr << S::k() << "\n";

S instance;
std::cerr << instance.s() << "\n";
std::cerr << instance.k() << "\n";

As we can see, k is a static like variable. This is 100% like a global variable, except that it's owned by the class (scoped to be correct). This makes it easier to avoid clashes between similarly named variables. Like any global variable, there is just one instance of that variable and modifying it is always visible by all.

On the other hand, s is an object specific value. Each object has its own instance of the value. In C++, you must create an instance to have access to that variable. In Ruby, the class definition is itself an instance of the class (in JavaScript, this is called a prototype), therefore you can access s from the class without additional instantiation. The class instance can be modified, but modification of s is going to be specific to each instance (each object of type S). So modifying one will not change the value in another.

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

CSS selector for first element with class

Try this solution:

_x000D_
_x000D_
 .home p:first-of-type {_x000D_
  border:5px solid red;_x000D_
  width:100%;_x000D_
  display:block;_x000D_
}
_x000D_
<div class="home">_x000D_
  <span>blah</span>_x000D_
  <p class="red">first</p>_x000D_
  <p class="red">second</p>_x000D_
  <p class="red">third</p>_x000D_
  <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CodePen link

How do I pass a datetime value as a URI parameter in asp.net mvc?

i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/

Cropping images in the browser BEFORE the upload

If you will still use JCrop, you will need only this php functions to crop the file:

$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);

client side:

jQuery(function($){

    $('#target').Jcrop({
    onChange:   showCoords,
    onSelect:   showCoords,
    onRelease:  clearCoords
    });

});

var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
    x = c.x;
    y = c.y;
    w = c.w;
    h = c.h;
};
function clearCoords()
{
    x=y=w=h=0;
}

See last changes in svn

You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.

How to maintain aspect ratio using HTML IMG tag

Try this:

<img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">

Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.

Resetting a form in Angular 2 after submit

if anybody wants to clear out only a particular form control one can use

formSubmit(){
this.formName.patchValue({
         formControlName:''
          //or if one wants to change formControl to a different value on submit
          formControlName:'form value after submission'     
    });
}

Windows command for file size only

Use a function to get rid off some limitation in the ~z operator. It is especially useful with a for loop:

@echo off
set size=0
call :filesize "C:\backup\20120714-0035\error.log"
echo file size is %size%
goto :eof

:: Set filesize of first argument in %size% variable, and return
:filesize
  set size=%~z1
  exit /b 0

how to open an URL in Swift3

I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:

//
//  ViewController.swift
//  UIWebViewExample
//
//  Created by Scott Maretick on 1/2/17.
//  Copyright © 2017 Scott Maretick. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    //added this code
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Your webView code goes here
        let url = URL(string: "https://www.google.com")
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
            //If you want handle the completion block than
            UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
                print("Open url : \(success)")
            })
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


};

Set initial value in datepicker with jquery?

From jQuery:

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Code examples

Initialize a datepicker with the defaultDate option specified.

$(".selector").datepicker({ defaultDate: +7 });

Get or set the defaultDate option, after init.

//getter
var defaultDate = $(".selector").datepicker("option", "defaultDate");
//setter
$(".selector").datepicker("option", "defaultDate", +7);

After the datepicker is intialized you should also be able to set the date with:

$(/*selector*/).datepicker("setDate" , date)

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:

lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

Draw Circle using css alone

yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity

Tomcat is web server or application server?

Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies.

Since Tomcat does not implement the full Java EE specification for an application server, it can be considered as a web server.

Source: http://tomcat.apache.org

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

  1. Go to your React-native Project -> Android
  2. Create a file local.properties

  3. Open the file

  4. paste your Android SDK path like below

     in Windows sdk.dir = C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk
    
     in macOS sdk.dir = /Users/USERNAME/Library/Android/sdk
    
     in linux sdk.dir = /home/USERNAME/Android/Sdk
    
  5. Replace USERNAME with your user name

  6. Now, Run the react-native run-android in your terminal

or

Sometimes project might be missing a settings.gradle file. Make sure that file exists from the project you are importing. If not add the settings.gradle file with the following :

    include ':app'

Save the file and put it at the top level folder in your project.

Ruby: How to turn a hash into HTTP parameters?

For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query.

>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"

http://api.rubyonrails.org/classes/Object.html#method-i-to_query

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Linux bash script to extract IP address

In my opinion the simplest and most elegant way to achieve what you need is this:

ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7

ip route get [host] - gives you the gateway used to reach a remote host e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3  src 192.168.0.109

tr -s ' ' - removes any extra spaces, now you have uniformity e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109

cut -d' ' -f7 - truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:

192.168.0.109

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

symfony 2 No route found for "GET /"

The problem is that you don't have a route for /. Change your definition to this:

ShopMyShopBundle_homepage:
    pattern:  /
    defaults: { _controller: ShopMyShopBundle:Main:index }
    requirements:
        _method:  GET

In Java, what is the best way to determine the size of an object?

If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory."

laravel collection to array

Try collect function in array like:

$comments_collection = collect($post->comments()->get()->toArray());

this methods can help you

toArray() with collect()

What is the C# equivalent of friend?

The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:

class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

or if you prefer to put the Inner class in another file:

Outer.cs
partial class Outer
{
}


Inner.cs
partial class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

Setting width to wrap_content for TextView through code

TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

For different layouts like ConstraintLayout and others, they have their own LayoutParams, like so:

pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

or

parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.

From one commenter:

... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.

Read more

The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.

For more information and updates, see this SO question. Here's the official issue.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

How to fix "The ConnectionString property has not been initialized"

I found that when I create Sqlconnection = new SqlConnection(), I forgot to pass my connectionString variable. So that is why I changed the way I initialize my connectionString (and nothing changed).

And if you like me just don't forget to pass your string connection into SqlConnection parameters.

Sqlconnection = new SqlConnection("ConnString")

how to compare two string dates in javascript?

Parse the dates and compare them as you would numbers:

function isLater(str1, str2)
{
    return new Date(str1) > new Date(str2);
}

If you need to support other date format consider a library such as date.js.

Bash script - variable content as a command to run

Your are probably looking for eval $var.

How to set a Timer in Java?

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

How can I use UIColorFromRGB in Swift?

This is worked for me in swift. Try this

bottomBorder.borderColor = UIColor (red: 255.0/255.0, green: 215.0/255.0, blue: 60/255.0, alpha: 1.0).CGColor

Where is my .vimrc file?

on unix vim --version tells you the various locations of the vim config files :

   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/share/vim"

How to increase memory limit for PHP over 2GB?

I had the same problem with commandline php even when ini_set("memory_limit", "-1"); was set, so the limit is in php not from apache.

You should check if you are using the 64bit version of php.

Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.

I think your php is compiled in 32 bit.

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

How to create a GUID in Excel?

Ken Thompson is right! - for me also this way works (excel 2016), but type definition GUID_TYPE is skipped, so full scripting is:

Private Type GUID_TYPE
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
End Type

Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr

Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr

Function CreateGuidString(Optional IncludeHyphens As Boolean = True, Optional IncludeBraces As Boolean = False)
    Dim Guid As GUID_TYPE
    Dim strGuid As String
    Dim retValue As LongPtr

    Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

    retValue = CoCreateGuid(Guid)

    If retValue = 0 Then
        strGuid = String$(guidLength, vbNullChar)
        retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)

        If retValue = guidLength Then
            '   valid GUID as a string
            '   remove them from the GUID
            If Not IncludeHyphens Then
                strGuid = Replace(strGuid, "-", vbNullString, Compare:=vbTextCompare)
            End If

            '   If IncludeBraces is switched from the default False to True,
            '   leave those curly braces be!
            If Not IncludeBraces Then
                strGuid = Replace(strGuid, "{", vbNullString, Compare:=vbTextCompare)
                strGuid = Replace(strGuid, "}", vbNullString, Compare:=vbTextCompare)
            End If


            CreateGuidString = strGuid
        End If
    End If

End Function

Remove all the children DOM elements in div

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

How do I select an entire row which has the largest ID in the table?

You can not give order by because order by does a "full scan" on a table.

The following query is better:

SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);

PDOException SQLSTATE[HY000] [2002] No such file or directory

I had this problems when I was running my application using docker containers.

The solution was put the name of the MySQL service container I was using in docker_compose.yml on DB_HOST. In my case, it was db :

DB_HOST=db

Hope it helps.

How do I find the time difference between two datetime objects in python?

New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds

>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds

Adding days to a date in Java

Simple, without any other API:

To add 8 days:

Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);

How can I retrieve the remote git address of a repo?

If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

Prevent div from moving while resizing the page

hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body> in a fixed width <div style="margin: 0 auto; width: 900px> to achieve what you have done with the body {margin: 0 10% 0 10%}

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

Something else to consider when this type of error is encountered:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__() where there was object inheritance.

The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).

Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.

In the case of the sytax error: The fix is simple, just edit the custom init statement:

def __init__(self, name):
    self.name = name

Check for internet connection with Swift

While it may not directly determine whether the phone is connected to a network, the simplest(, cleanest?) solution would be to 'ping' Google, or some other server, (which isn't possible unless the phone is connected to a network):

private var urlSession:URLSession = {
    var newConfiguration:URLSessionConfiguration = .default
    newConfiguration.waitsForConnectivity = false
    newConfiguration.allowsCellularAccess = true
    return URLSession(configuration: newConfiguration)
}()

public func canReachGoogle() -> Bool
{
    let url = URL(string: "https://8.8.8.8")
    let semaphore = DispatchSemaphore(value: 0)
    var success = false
    let task = urlSession.dataTask(with: url!)
    { data, response, error in
        if error != nil
        {
            success = false
        }
        else
        {
            success = true
        }
        semaphore.signal()
    }

    task.resume()
    semaphore.wait()

    return success
}

If you're concerned that the server may be down or may block your IP, you can always ping multiple servers in a similar fashion and return whether any of them are reachable. Or have someone set up a dedicated server just for this purpose.

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

Assign an initial value to radio button as checked

You can just use:

<input type="radio" checked />

Using just the attribute checked without stating a value is the same as checked="checked".

Get difference between 2 dates in JavaScript?

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Java heap size descriptions (xms, xmx, xmn)

-Xms size in bytes

Example : java -Xms32m

Sets the initial size of the Java heap. The default size is 2097152 (2MB). The values must be a multiple of, and greater than, 1024 bytes (1KB). (The -server flag increases the default size to 32M.)

-Xmn size in bytes

Example : java -Xmx2m

Sets the initial Java heap size for the Eden generation. The default value is 640K. (The -server flag increases the default size to 2M.)

-Xmx size in bytes

Example : java -Xmx2048m

Sets the maximum size to which the Java heap can grow. The default size is 64M. (The -server flag increases the default size to 128M.) The maximum heap limit is about 2 GB (2048MB).

Java memory arguments (xms, xmx, xmn) formatting

When setting the Java heap size, you should specify your memory argument using one of the letters “m” or “M” for MB, or “g” or “G” for GB. Your setting won’t work if you specify “MB” or “GB.” Valid arguments look like this:

-Xms64m or -Xms64M -Xmx1g or -Xmx1G Can also use 2048MB to specify 2GB Also, make sure you just use whole numbers when specifying your arguments. Using -Xmx512m is a valid option, but -Xmx0.5g will cause an error.

This reference can be helpful for someone.

Best programming based games

Core Wars is the classic, of course. But Rocky's Boots is another one. Imagine! There was a time (1982) when you could sell a commercial game based on logic gates!

How to beautifully update a JPA entity in Spring Data?

Simple JPA update..

Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);

Find the host name and port using PSQL commands

SELECT CURRENT_USER usr, :'HOST' host, inet_server_port() port;

This uses psql's built in HOST variable, documented here

And postgres System Information Functions, documented here

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

Efficient way to insert a number into a sorted array of numbers?

Here are a few thoughts: Firstly, if you're genuinely concerned about the runtime of your code, be sure to know what happens when you call the built-in functions! I don't know up from down in javascript, but a quick google of the splice function returned this, which seems to indicate that you're creating a whole new array each call! I don't know if it actually matters, but it is certainly related to efficiency. I see that Breton, in the comments, has already pointed this out, but it certainly holds for whatever array-manipulating function you choose.

Anyways, onto actually solving the problem.

When I read that you wanted to sort, my first thought is to use insertion sort!. It is handy because it runs in linear time on sorted, or nearly-sorted lists. As your arrays will have only 1 element out of order, that counts as nearly-sorted (except for, well, arrays of size 2 or 3 or whatever, but at that point, c'mon). Now, implementing the sort isn't too too bad, but it is a hassle you may not want to deal with, and again, I don't know a thing about javascript and if it will be easy or hard or whatnot. This removes the need for your lookup function, and you just push (as Breton suggested).

Secondly, your "quicksort-esque" lookup function seems to be a binary search algorithm! It is a very nice algorithm, intuitive and fast, but with one catch: it is notoriously difficult to implement correctly. I won't dare say if yours is correct or not (I hope it is, of course! :)), but be wary if you want to use it.

Anyways, summary: using "push" with insertion sort will work in linear time (assuming the rest of the array is sorted), and avoid any messy binary search algorithm requirements. I don't know if this is the best way (underlying implementation of arrays, maybe a crazy built-in function does it better, who knows), but it seems reasonable to me. :) - Agor.

How can I post an array of string to ASP.NET MVC Controller without a form?

You can setup global parameter with

jQuery.ajaxSettings.traditional = true;

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

I'll also prefer ALTER LOGIN Command as in accepted answer and described here

But for GUI lover

  1. Go to [SERVER INSTANCE] --> Security --> Logins --> [YOUR LOGIN]
  2. Right Click on [YOUR LOGIN]
  3. Update the Default Database Option at the bottom of the page

Tired of reading!!! just look at following

enter image description here

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

convert HTML ( having Javascript ) to PDF using JavaScript

Copy and paste this in your site to provide a link which will convert the page to a PDF page.

<a href="javascript:void(window.open('http://www.htmltopdfconverter.net/?convert='+window.location))">Convert To PDF</a>

No appenders could be found for logger(log4j)?

I ran into this issue when trying to build an executable jar with maven in intellij 12. It turned out that because the java manifest file didn't include a class path the log4j properties file couldn't be found at the root level (where the jar file was executed from.)

FYI I was getting the logger like this:

Logger log = LogManager.getLogger(MyClassIWantedToLogFrom.class);

And I was able to get it to work with a pom file that included this:

         <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-5</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath> 
                        <mainClass>com.mycompany.mainPackage.mainClass</mainClass>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path> <!-- need to add current directory to classpath properties files can be found -->
                    </manifestEntries>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

How to fix: Error device not found with ADB.exe

Try changing USB port. Try restarting adb server.

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

SQL Server String Concatenation with Null

Use

SET CONCAT_NULL_YIELDS_NULL  OFF 

and concatenation of null values to a string will not result in null.

Please note that this is a deprecated option, avoid using. See the documentation for more details.

PHP Fatal error: Cannot access empty property

First, don't declare variables using var, but

public $my_value;

Then you can access it using

$this->my_value;

and not

$this->$my_value;

How to ORDER BY a SUM() in MySQL?

Without a GROUP BY clause, any summation will roll all rows up into a single row, so your query will indeed not work. If you grouped by, say, name, and ordered by sum(c_counts+f_counts), then you might get some useful results. But you would have to group by something.

return in for loop or outside loop

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;

Having services in React application

The issue becomes extremely simple when you realize that an Angular service is just an object which delivers a set of context-independent methods. It's just the Angular DI mechanism which makes it look more complicated. The DI is useful as it takes care of creating and maintaining instances for you but you don't really need it.

Consider a popular AJAX library named axios (which you've probably heard of):

import axios from "axios";
axios.post(...);

Doesn't it behave as a service? It provides a set of methods responsible for some specific logic and is independent from the main code.

Your example case was about creating an isolated set of methods for validating your inputs (e.g. checking the password strength). Some suggested to put these methods inside the components which for me is clearly an anti-pattern. What if the validation involves making and processing XHR backend calls or doing complex calculations? Would you mix this logic with mouse click handlers and other UI specific stuff? Nonsense. The same with the container/HOC approach. Wrapping your component just for adding a method which will check whether the value has a digit in it? Come on.

I would just create a new file named say 'ValidationService.js' and organize it as follows:

const ValidationService = {
    firstValidationMethod: function(value) {
        //inspect the value
    },

    secondValidationMethod: function(value) {
        //inspect the value
    }
};

export default ValidationService;

Then in your component:

import ValidationService from "./services/ValidationService.js";

...

//inside the component
yourInputChangeHandler(event) {

    if(!ValidationService.firstValidationMethod(event.target.value) {
        //show a validation warning
        return false;
    }
    //proceed
}

Use this service from anywhere you want. If the validation rules change you need to focus on the ValidationService.js file only.

You may need a more complicated service which depends on other services. In this case your service file may return a class constructor instead of a static object so you can create an instance of the object by yourself in the component. You may also consider implementing a simple singleton for making sure that there is always only one instance of the service object in use across the entire application.

Pythonic way to check if a file exists?

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

If you want to avoid this sort of thing, I would suggest something like the following (untested):

import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

Symfony 2 EntityManager injection in service

For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

And then they would be available in the order they were listed via the arguments (if there are more than 1).

public function __construct(EntityManager $entityManager) {
    $this->em = $entityManager;
}

Using jQuery to compare two arrays of Javascript objects

I was also looking for this today and found: http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD

Don't know if that's a good solution though they do mention some performance considerations taken into account.

I like the idea of a jQuery helper method. @David I'd rather see your compare method to work like:

jQuery.compare(a, b)

I doesn't make sense to me to be doing:

$(a).compare(b)

where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.

Also regarding sorting and 'caching' the sorted arrays:

  • I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
  • for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
  • More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.

It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)

In which case I think the code for it would be:

jQuery.extend({
    compare: function (arrayA, arrayB) {
        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        var a = jQuery.extend(true, [], arrayA);
        var b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] !== b[i]) { 
                return false;
            }
        }
        return true;
    }
});

var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];

jQuery.compare(a, b);
// false

jQuery.compare(b, c);
// true

// c is still unsorted [3, 4, 2]

SeekBar and media player in android

check this, you should give arguments in msecs, Dont just send progress to seekTo(int)

and also check this getCurrentPostion() and getDuration().

You can do some calcuations, ie., convert progress in msec like msce = (progress/100)*getDuration() then do seekTo(msec)

Or else i have an easy idea, you don't need to change any code anywer else just add seekBar.setMax(mPlayer.getDuration()) once your media player is prepared.

and here is link exactly what you want seek bar update

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

Can you get a Windows (AD) username in PHP?

Referencing trying to also figure out if AUTH_USER is part of a particular domain group; a clever way to do this is t create a locked down folder with text files (can be blank). Set security to only having the security/distro group you want to validate. Once you run a @file_get_contents (<---will toss a warning)...if the user does not have group access they will not be able to get the file contents and hence, will not have that particular AD group access. This is simple and works wonderfully.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Delete newline in Vim

set backspace=indent,eol,start

in your .vimrc will allow you to use backspace and delete on \n (newline) in insert mode.

set whichwrap+=<,>,h,l,[,]

will allow you to delete the previous LF in normal mode with X (when in col 1).

How to determine if OpenSSL and mod_ssl are installed on Apache2

Create a test.php file with the following code in a www folder:

<?php echo phpinfo();?>

When you navigate to that page/URL in the browser. You will see something similar if you have openssl enabled:

enter image description here

How to check the version of GitLab?

For omnibus versions:\

sudo gitlab-rake gitlab:env:info

Example:

System information
System:     Ubuntu 12.04
Current User:   git
Using RVM:  no
Ruby Version:   2.1.7p400
Gem Version:    2.2.5
Bundler Version:1.10.6
Rake Version:   10.4.2
Sidekiq Version:3.3.0

GitLab information
Version:    8.2.2
Revision:   08fae2f
Directory:  /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: postgresql
URL:        https://your.hostname
HTTP Clone URL: https://your.hostname/some-group/some-project.git
SSH Clone URL:  [email protected]:some-group/some-project.git
Using LDAP: yes
Using Omniauth: no

GitLab Shell
Version:    2.6.8
Repositories:   /var/opt/gitlab/git-data/repositories
Hooks:      /opt/gitlab/embedded/service/gitlab-shell/hooks/
Git:        /opt/gitlab/embedded/bin/git

SQL Server: Extract Table Meta-Data (description, fields and their data types)

To get the description data, you unfortunately have to use sysobjects/syscolumns to get the ids:

SELECT      u.name + '.' + t.name AS [table],
            td.value AS [table_desc],
            c.name AS [column],
            cd.value AS [column_desc]
FROM        sysobjects t
INNER JOIN  sysusers u
    ON      u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
    ON      td.major_id = t.id
    AND     td.minor_id = 0
    AND     td.name = 'MS_Description'
INNER JOIN  syscolumns c
    ON      c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
    ON      cd.major_id = c.id
    AND     cd.minor_id = c.colid
    AND     cd.name = 'MS_Description'
WHERE t.type = 'u'
ORDER BY    t.name, c.colorder

You can do it with info-schema, but you'd have to concatenate etc to call OBJECT_ID() - so what would be the point?

Issue with adding common code as git submodule: "already exists in the index"

In your git dir, suppose you have sync all changes.

rm -rf .git 

rm -rf .gitmodules

Then do:

git init
git submodule add url_to_repo projectfolder

applying css to specific li class

You are defining the color: #C1C1C1; for all the a elements with #sub-nav-container a.

Doing it again in li.sub-navigation-home-news won't do anything, as it is a parent of the a element.

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

In my case I faced this issue in my simulator because my computer's date was behind of current date. So do check this case too when you face SSL error.

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

Python nonlocal statement

Compare this, without using nonlocal:

x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 0

To this, using nonlocal, where inner()'s x is now also outer()'s x:

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 2
# global: 0

If we were to use global, it would bind x to the properly "global" value:

x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 2

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

UIView Infinite 360 degree rotation animation?

David Rysanek's awesome answer updated to Swift 4:

import UIKit

extension UIView {

        func startRotating(duration: CFTimeInterval = 3, repeatCount: Float = Float.infinity, clockwise: Bool = true) {

            if self.layer.animation(forKey: "transform.rotation.z") != nil {
                return
            }

            let animation = CABasicAnimation(keyPath: "transform.rotation.z")
            let direction = clockwise ? 1.0 : -1.0
            animation.toValue = NSNumber(value: .pi * 2 * direction)
            animation.duration = duration
            animation.isCumulative = true
            animation.repeatCount = repeatCount
            self.layer.add(animation, forKey:"transform.rotation.z")
        }

        func stopRotating() {

            self.layer.removeAnimation(forKey: "transform.rotation.z")

        }   

    }
}

How to search for occurrences of more than one space between words in a line

This regex selects all spaces, you can use this and replace it with a single space

\s+

example in python

result = re.sub('\s+',' ', data))

Get request URL in JSP which is forwarded by Servlet

If you use RequestDispatcher.forward() to route the request from controller to the view, then request URI is exposed as a request attribute named javax.servlet.forward.request_uri. So, you can use

request.getAttribute("javax.servlet.forward.request_uri")

or

${requestScope['javax.servlet.forward.request_uri']}

javascript - Create Simple Dynamic Array

var arr = [];
while(mynumber--) {
    arr[mynumber] = String(mynumber+1);
}

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

Is there a list of Pytz Timezones?

The timezone name is the only reliable way to specify the timezone.

You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones Note that this list contains a lot of alias names, such as US/Eastern for the timezone that is properly called America/New_York.

If you programatically want to create this list from the zoneinfo database you can compile it from the zone.tab file in the zoneinfo database. I don't think pytz has an API to get them, and I also don't think it would be very useful.

C# Form.Close vs Form.Dispose

If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

All I know is a Clean does not do what "make clean" used to do - if I Clean a solution I would expect it delete obj and bin files/folders such that it builds like is was a fresh checkout of the source. In my experience though I often find times where a Clean and Build or Rebuild still produces strange errors on source that is known to compile and what is required is a manual deletion of the bin/obj folders, then it will build.

How To Check If A Key in **kwargs Exists?

if kwarg.__len__() != 0:
    print(kwarg)

How to copy a directory structure but only include certain files (using windows batch files)

You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

ROBOCOPY C:\Source C:\Destination data.zip info.txt /E

EDIT: Changed the /S parameter to /E to include empty folders.

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

How to encode text to base64 in python

1) This works without imports in Python 2:

>>>
>>> 'Some text'.encode('base64')
'U29tZSB0ZXh0\n'
>>>
>>> 'U29tZSB0ZXh0\n'.decode('base64')
'Some text'
>>>
>>> 'U29tZSB0ZXh0'.decode('base64')
'Some text'
>>>

(although this doesn't work in Python3 )

2) In Python 3 you'd have to import base64 and do base64.b64decode('...') - will work in Python 2 too.

How to check if text fields are empty on form submit using jQuery?

var save_val = $("form").serializeArray();
$(save_val).each(function( index, element ) {
    alert(element.name);
    alert(element.val);
});

How do I tell Maven to use the latest version of a dependency?

NOTE:

The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution.


If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.

When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.

See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where:

  • A square bracket ( [ & ] ) means "closed" (inclusive).
  • A parenthesis ( ( & ) ) means "open" (exclusive).

Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:

<?xml version="1.0" encoding="UTF-8"?><metadata>
  <groupId>com.foo</groupId>
  <artifactId>my-foo</artifactId>
  <version>2.0.0</version>
  <versioning>
    <release>1.1.1</release>
    <versions>
      <version>1.0</version>
      <version>1.0.1</version>
      <version>1.1</version>
      <version>1.1.1</version>
      <version>2.0.0</version>
    </versions>
    <lastUpdated>20090722140000</lastUpdated>
  </versioning>
</metadata>

If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here):

Declare an exact version (will always resolve to 1.0.1):

<version>[1.0.1]</version>

Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):

<version>1.0.1</version>

Declare a version range for all 1.x (will currently resolve to 1.1.1):

<version>[1.0.0,2.0.0)</version>

Declare an open-ended version range (will resolve to 2.0.0):

<version>[1.0.0,)</version>

Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)

<version>LATEST</version>

Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):

<version>RELEASE</version>

Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true"


It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).

It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.

Equivalent of typedef in C#

I think there is no typedef. You could only define a specific delegate type instead of the generic one in the GenericClass, i.e.

public delegate GenericHandler EventHandler<EventData>

This would make it shorter. But what about the following suggestion:

Use Visual Studio. This way, when you typed

gcInt.MyEvent += 

it already provides the complete event handler signature from Intellisense. Press TAB and it's there. Accept the generated handler name or change it, and then press TAB again to auto-generate the handler stub.

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Is there an Eclipse plugin to run system shell in the Console?

I recommend EasyShell, which features 'open' (console), 'run', 'explore', and 'copy path'.

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.

How do I keep CSS floats in one line?

Are you sure that floated block-level elements are the best solution to this problem?

Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

How to use forEach in vueJs?

In VueJS you can use forEach like below.

let list=[];
$.each(response.data.message, function(key, value) {
     list.push(key);
   });

So, now you can have all arrays into list . use for loop to get values or keys

<Django object > is not JSON serializable

The easiest way is to use a JsonResponse.

For a queryset, you should pass a list of the the values for that queryset, like so:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

How do I log errors and warnings into a file?

In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)

compare two list and return not matching items using linq

List<Person> persons1 = new List<Person>
           {
                    new Person {Id = 1, Name = "Person 1"},
                    new Person {Id = 2, Name = "Person 2"},
                    new Person {Id = 3, Name = "Person 3"},
                    new Person {Id = 4, Name = "Person 4"}
           };


        List<Person> persons2 = new List<Person>
           {
                    new Person {Id = 1, Name = "Person 1"},
                    new Person {Id = 2, Name = "Person 2"},
                    new Person {Id = 3, Name = "Person 3"},
                    new Person {Id = 4, Name = "Person 4"},
                    new Person {Id = 5, Name = "Person 5"},
                    new Person {Id = 6, Name = "Person 6"},
                    new Person {Id = 7, Name = "Person 7"}
           };
        var output = (from ps1 in persons1
                      from ps2 in persons2
                      where ps1.Id == ps2.Id
                      select ps2.Name).ToList();

Person class

public class Person
{        
    public int Id { get; set; }       

    public string Name { get; set; }
}

Creation timestamp and last update timestamp with Hibernate and MySQL

A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.

For the creation date, you simply keep a java.util.Date property. Be sure, to always initialize it with new Date().

For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).

write a shell script to ssh to a remote machine and execute commands

This worked for me. I made a function. Put this in your shell script:

sshcmd(){
    ssh $1@$2 $3
}

sshcmd USER HOST COMMAND

If you have multiple machines that you want to do the same command on you would repeat that line with a semi colon. For example, if you have two machines you would do this:

sshcmd USER HOST COMMAND ; sshcmd USER HOST COMMAND

Replace USER with the user of the computer. Replace HOST with the name of the computer. Replace COMMAND with the command you want to do on the computer.

Hope this helps!

Delete forked repo from GitHub

There are multiple answers pointing out, that editing/deleting the fork doesn't affect the original repository. Those answers are correct. I will try to add something to that answer and explain why in my answer.

A fork is just a copy of a repository with a fork relationship.

As you can copy a file or a directory locally to another place and delete the copy, it won't affect the original.

Fork relationship means, that you can easily tell github that it should send a pull request (with your changes) from your fork to the original repository because github knows that your repository is a copy of the original repository(with a few changes on both sides).

Just for anybodies information, a pull request(or merge request) contains code that has been changed in the fork and is submitted to the original repository. Users with push/write access(may be different in other git servers) on the original repository are allowed to merge the changes of the pull request into the original repository(copy the changes of the PR to the original repository).

Safe width in pixels for printing web pages?

I doubt there is one... It depends on browser, on printer (physical max dpi) and its driver, on paper size as you point out (and I might want to print on B5 paper too...), on settings (landscape or portrait?), plus you often can change the scale (percentage), etc.
Let the users tweak their settings...

What does this thread join code mean?

From oracle documentation page on Joins

The join method allows one thread to wait for the completion of another.

If t1 is a Thread object whose thread is currently executing,

t1.join() : causes the current thread to pause execution until t1's thread terminates.

If t2 is a Thread object whose thread is currently executing,

t2.join(); causes the current thread to pause execution until t2's thread terminates.

join API is low level API, which has been introduced in earlier versions of java. Lot of things have been changed over a period of time (especially with jdk 1.5 release) on concurrency front.

You can achieve the same with java.util.concurrent API. Some of the examples are

  1. Using invokeAll on ExecutorService
  2. Using CountDownLatch
  3. Using ForkJoinPool or newWorkStealingPool of Executors(since java 8)

Refer to related SE questions:

wait until all threads finish their work in java

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

For those who work with AX 2012 AIF services and try to call there C# or VB project inside AX (x++) and suffer from such errors of "could not find default endpoint"... or "no contract found" ... go back to your visual studio (c#) project and add these lines before defining your service client, then deploy the project and restart AX client and retry: Note, the example is for NetTcp adapter, you could easily use any other adapter instead according to your need.

 Uri Address = new Uri("net.tcp://your-server:Port>/DynamicsAx/Services/your-port-name");
 NetTcpBinding Binding = new NetTcpBinding();
 EndpointAddress EndPointAddr = new EndpointAddress(Address);
 SalesOrderServiceClient Client = new SalesOrderServiceClient(Binding, EndPointAddr);

height style property doesn't work in div elements

I'm told that it's bad practice to overuse it, but you can always add !important after your code to prioritize the css properties value.

.p{height:400px!important;}

Working with Enums in android

public enum Gender {
    MALE,
    FEMALE
}

Difference between return and exit in Bash functions

If you convert a Bash script into a function, you typically replace exit N with return N. The code that calls the function will treat the return value the same as it would an exit code from a subprocess.

Using exit inside the function will force the entire script to end.

Number prime test in JavaScript

function isPrime(num) {
    var prime = num != 1;
    for(var i=2; i<num; i++) {
        if(num % i == 0) {
            prime = false;
            break;
        }
    }
    return prime;
}

DEMO

mongodb how to get max value from collections

The performance of the suggested answer is fine. According to the MongoDB documentation:

When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.

Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

jquery - return value using ajax result on success

Hi try async:false in your ajax call..

Simple JavaScript login form validation

  1. The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this:

    <form name="loginform" onsubmit="validateForm()" method="post">

    Here are some useful links:

  2. For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.

    You can read more about the differences here.

UPDATE:

You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:

<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
    <label>User name</label>
    <input type="text" name="usr" placeholder="username"> 
    <label>Password</label>
    <input type="password" name="pword" placeholder="password">
    <input type="submit" value="Login"/>
</form>

<script>
    function validateForm() {
        var un = document.loginform.usr.value;
        var pw = document.loginform.pword.value;
        var username = "username"; 
        var password = "password";
        if ((un == username) && (pw == password)) {
            return true;
        }
        else {
            alert ("Login was unsuccessful, please check your username and password");
            return false;
        }
  }
</script>

How can I get the current class of a div with jQuery?

var className=$('selector').attr('class');

or

var className=$(this).attr('class');

the classname of the current element

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

With Spring Boot, I'm not entirely sure why this was necessary (I got the /error fallback even though @ResponseBody was defined on an @ExceptionHandler), but the following in itself did not work:

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

It still threw an exception, apparently because no producible media types were defined as a request attribute:

// AbstractMessageConverterMethodProcessor
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType,
        ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
        throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

    Class<?> valueType = getReturnValueType(value, returnType);
    Type declaredType = getGenericType(returnType);
    HttpServletRequest request = inputMessage.getServletRequest();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
if (value != null && producibleMediaTypes.isEmpty()) {
        throw new IllegalArgumentException("No converter found for return value of type: " + valueType);   // <-- throws
    }

// ....

@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, Type declaredType) {
    Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (!CollectionUtils.isEmpty(mediaTypes)) {
        return new ArrayList<MediaType>(mediaTypes);

So I added them.

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    Set<MediaType> mediaTypes = new HashSet<>();
    mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    httpServletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

And this got me through to have a "supported compatible media type", but then it still didn't work, because my ErrorMessage was faulty:

public class ErrorMessage {
    int code;

    String message;
}

JacksonMapper did not handle it as "convertable", so I had to add getters/setters, and I also added @JsonProperty annotation

public class ErrorMessage {
    @JsonProperty("code")
    private int code;

    @JsonProperty("message")
    private String message;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Then I received my message as intended

{"code":400,"message":"An \"url\" parameter must be defined."}

Defining TypeScript callback type

To go one step further, you could declare a type pointer to a function signature like:

interface myCallbackType { (myArgument: string): void }

and use it like this:

public myCallback : myCallbackType;

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

Lightbox to show videos from Youtube and Vimeo?

I've had a LOT of trouble with pretty photo and IE9. I also had issues with fancybox in IE.

For youtube.com, I'm having a lot of luck with CeeBox.

http://catcubed.com/2008/12/23/ceebox-a-thickboxvideobox-mashup/

Error sending json in POST to web API service

In the HTTP request you need to set Content-Type to: Content-Type: application/json

So if you're using fiddler client add Content-Type: application/json to the request header

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

Bash script processing limited number of commands in parallel

In fact, xargs can run commands in parallel for you. There is a special -P max_procs command-line option for that. See man xargs.

What's the environment variable for the path to the desktop?

@Dave Webb's answer is probably the way to go. The only other thing I can think of are the CSIDLs:

CSIDL_DESKTOPDIRECTORY

The file system directory used to physically store file objects on the desktop (which should not be confused with the desktop folder itself). A typical path is C:\Documents and Settings\username\Desktop.

I have no idea how to get hold of those from the command line, though.

Android Studio Gradle Already disposed Module

works for me: File -> Invalidate Caches / Restart... -> Invalidate and Restart

How do I get unique elements in this array?

This should work for you:

Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.

#An array of multiple data entries
@table1 = Table1.find(:all) 

#extracts **activity** for each entry in the array @table1, and returns only the ones which are unique 

@unique_activities = @table1.map{|t| t.activity}.uniq 

Unable to open debugger port in IntelliJ

I'm hoping your problem has been solved by now. If not, try this... It looks like you have server=y for both your app and IDEA. IDEA should probably be server=n. Also, the (IDEA) client should have an address that includes both the host name and the port, e.g., address=127.0.0.1:9009.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

open terminal and type the below command and hit enter

sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE dbo.<tablename> ADD CONSTRAINT
            <namingconventionconstraint> UNIQUE NONCLUSTERED
    (
                <columnname>
    ) ON [PRIMARY]

Set selected radio from radio group with a value

When you change attribute value like mentioned above the change event is not triggered so if needed for some reasons you can trigger it like so

$('input[name=video_radio][value="' + r.data.video_radio + '"]')
       .prop('checked', true)
       .trigger('change');

What can cause a “Resource temporarily unavailable” on sock send() command

"Resource temporarily unavailable" is the error message corresponding to EAGAIN, which means that the operation would have blocked but nonblocking operation was requested. For send(), that could be due to any of:

  • explicitly marking the file descriptor as nonblocking with fcntl(); or
  • passing the MSG_DONTWAIT flag to send(); or
  • setting a send timeout with the SO_SNDTIMEO socket option.

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

How to run Spyder in virtual environment?

What worked for me :

  1. run spyder from the environment (after source activate)
  2. go to Tools --> preferences --> python Interpreter and select the python file from the env you want to link to spyder ex : /home/you/anaconda3/envs/your_env/bin/python

Worked on ubuntu 16, spyder3, python3.6.

What is the difference between encrypting and signing in asymmetric encryption?

In your scenario, you do not encrypt in the meaning of asymmetric encryption; I'd rather call it "encode".

So you encode your data into some binary representation, then you sign with your private key. If you cannot verify the signature via your public key, you know that the signed data is not generated with your private key. ("verification" meaning that the unsigned data is not meaningful)

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Another solution is the following:

ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)

Using LIMIT within GROUP BY to get N results per group?

The following post: sql: selcting top N record per group describes the complicated way of achieving this without subqueries.

It improves on other solutions offered here by:

  • Doing everything in a single query
  • Being able to properly utilize indexes
  • Avoiding subqueries, notoriously known to produce bad execution plans in MySQL

It is however not pretty. A good solution would be achievable were Window Functions (aka Analytic Functions) enabled in MySQL -- but they are not. The trick used in said post utilizes GROUP_CONCAT, which is sometimes described as "poor man's Window Functions for MySQL".

Cross-reference (named anchor) in markdown

For most common markdown generators. You have a simple self generated anchor in each header. For instance with pandoc, the generated anchor will be a kebab case slug of your header.

 echo "# Hello, world\!" | pandoc
 # => <h1 id="hello-world">Hello, world!</h1>

Depending on which markdown parser you use, the anchor can change (take the exemple of symbolrush and La muerte Peluda answers, they are different!). See this babelmark where you can see generated anchors depending on your markdown implementation.

C/C++ include header file order

I recommend:

  1. The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
  2. C system files.
  3. C++ system files.
  4. Platform / OS / other header files (e.g. win32, gtk, openGL).
  5. Other header files from your project.

And of course, alphabetical order within each section, where possible.

Always use forward declarations to avoid unnecessary #includes in your header files.

Using group by on multiple columns

Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.

The GROUP BY clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:

-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

-- GROUP BY with two parameters:
SELECT
    column_name1,
    column_name2,
    AGGREGATE_FUNCTION(column_name3)
FROM
    table_name
GROUP BY
    column_name1,
    column_name2;

Remember this order:

  1. SELECT (is used to select data from a database)

  2. FROM (clause is used to list the tables)

  3. WHERE (clause is used to filter records)

  4. GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)

  5. HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)

  6. ORDER BY (keyword is used to sort the result-set)

You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.

Aggregate Functions are:

MIN() returns the smallest value in a given column

MAX() returns the maximum value in a given column.

SUM() returns the sum of the numeric values in a given column

AVG() returns the average value of a given column

COUNT() returns the total number of values in a given column

COUNT(*) returns the number of rows in a table

SQL script examples about using aggregate functions:

Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING clause and the GROUP BY clause to accomplish this:

SELECT 
    orderId, SUM(unitPrice * qty) Total
FROM
    OrderDetails
GROUP BY orderId
HAVING Total > 950;

Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT function and the GROUP BY, ORDER BY clauses and ASC:

SELECT 
    customerId, COUNT(*)
FROM
    Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;

Retrieve the category that has an average Unit Price greater than $10, using AVG function combine with GROUP BY and HAVING clauses:

SELECT 
    categoryName, AVG(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;

Getting the less expensive product by each category, using the MIN function in a subquery:

SELECT categoryId,
       productId,
       productName,
       unitPrice
FROM Products p1
WHERE unitPrice = (
                SELECT MIN(unitPrice)
                FROM Products p2
                WHERE p2.categoryId = p1.categoryId)

The following statement groups rows with the same values in both categoryId and productId columns:

SELECT 
    categoryId, categoryName, productId, SUM(unitPrice)
FROM
    Products p
INNER JOIN
    Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId

How do you remove Subversion control for a folder?

From a Windows command line:

rmdir .svn /s /q

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

Disable back button in android

If you want to disable your app while logging out, you can pop up a non-cancellable dialog.

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

How can I completely remove TFS Bindings

The other option is

Delete the workspace

re-map when needed

Make sure to check, rollback (Undo Pending changes)

before you remove workspace

This is quickest and surest one

Good Luck

Spring Boot Rest Controller how to return different HTTP status codes?

Try this code:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

What's the difference between 'git merge' and 'git rebase'?

I really love this excerpt from 10 Things I hate about git (it gives a short explanation for rebase in its second example):

3. Crappy documentation

The man pages are one almighty “f*** you”1. They describe the commands from the perspective of a computer scientist, not a user. Case in point:

git-push – Update remote refs along with associated objects

Here’s a description for humans:

git-push – Upload changes from your local repository into a remote repository

Update, another example: (thanks cgd)

git-rebase – Forward-port local commits to the updated upstream head

Translation:

git-rebase – Sequentially regenerate a series of commits so they can be 
             applied directly to the head node

And then we have

git-merge - Join two or more development histories together

which is a good description.


1. uncensored in the original

Spark: subtract two DataFrames

For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

Generating random integer from a range

I recommend the Boost.Random library, it's super detailed and well-documented, lets you explicitly specify what distribution you want, and in non-cryptographic scenarios can actually outperform a typical C library rand implementation.

Vue.js - How to properly watch for nested data

I've found it works this way too:

watch: {
    "details.position"(newValue, oldValue) {
        console.log("changes here")
    }
},
data() {
    return {
      details: {
          position: ""
      }
    }
}

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

I'm also having the exact same problem with both /usr/local/bin and /etc/sudoers on OSX Snow lepard.Even when i logged in as admin and tried to change the permissions via the terminal, it still says "Operation not permitted". And i did the following to get the permission of these folders.

From the terminal, I accessed /etc/sudoers file and using pico editor i added the following code: username ALL=(ALL) ALL Replace "username" with your MAC OS account name

How to unescape HTML character entities in Java?

The following library can also be used for HTML escaping in Java: unbescape.

HTML can be unescaped this way:

final String unescapedText = HtmlEscape.unescapeHtml(escapedText); 

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

How can I get the Google cache age of any URL or web page?

its too simple, you can just type "cache:" before the URL of the page. for example if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page

this will show you the last webcache of the page.see here:

enter image description here

But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.

How to remove all options from a dropdown using jQuery / JavaScript

Other approach for Vanilla JavaScript:

for(var o of document.querySelectorAll('#models > option')) {
  o.remove()
}

sql like operator to get the numbers only

With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

Copy existing project with a new name in Android Studio

The purpose of this is so I can have a second version of my app which is ad supported in the app store.

Currently the best way to do it is without copying the project.
You can do it using diffent flavors in your build.gradle file.

 productFlavors {
        flavor1 {
            applicationId = "com.example.my.pkg.flavor1"
        }
        flavorAdSUpport {
            applicationId = "com.example.my.pkg.flavor2"
        }
  }

In this way you have only a copy of the files and you can handle the difference easily.