Programs & Examples On #Tao framework

Android: combining text & image on a Button or ImageButton

Just use a LinearLayout and pretend it's a Button - setting background and clickable is the key:

<LinearLayout
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/btn_default"
    android:clickable="true"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="5dp"
        android:src="@drawable/image" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="5dp"
        android:text="Do stuff" />
</LinearLayout>

Get keys of a Typescript interface as array of strings

The following requires you to list the keys on your own, but at least TypeScript will enforce IUserProfile and IUserProfileKeys have the exact same keys (Required<T> was added in TypeScript 2.8):

export interface IUserProfile  {
  id: string;
  name: string;
};
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const IUserProfileKeys: KeysEnum<IUserProfile> = {
  id: true,
  name: true,
};

How can I post data as form data instead of a request payload?

Use AngularJS $http service and use its post method or configure $http function.

What is a clean, Pythonic way to have multiple constructors in Python?

All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:

def __init__(self, num_holes):

  # do stuff with the number

@classmethod
def fromRandom(cls):

  return cls( # some-random-number )

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

Error: TypeError: $(...).dialog is not a function

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

How to configure port for a Spring Boot application

In Application properties just add 1 line

server.port = 8090

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to subtract days from a plain Date?

I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.

if(!Date.prototype.adjustDate){
    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

So, to use it i can simply write:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);

How to create local notifications?

Here is sample code for LocalNotification that worked for my project.

Objective-C:

This code block in AppDelegate file :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        // Override point for customization after application launch.
        return YES;
    }

    // This code block is invoked when application is in foreground (active-mode) 
 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification" 
        delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

        [notificationAlert show];
       // NSLog(@"didReceiveLocalNotification");
    }

This code block in .m file of any ViewController:

-(IBAction)startLocalNotification {  // Bind this method to UIButton action
    NSLog(@"startLocalNotification");

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
    notification.alertBody = @"This is local notification!";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber = 10;

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];    
}

The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification If application is in background then it displays BadgeNumber as 10 and with default notification sound.

This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:

Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts

This means you need register for local notification. This can be achieved using:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

You can also refer blog for local notification.

Swift:

You AppDelegate.swift file should look like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    
    // Override point for customization after application launch.
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))

    return true
}

The swift file (say ViewController.swift) in which you want to create local notification should contain below code:

//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
    println("buttonIsPressed function called \(UIButton.description())")

    var localNotification = UILocalNotification()
    localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
    localNotification.alertBody = "This is local notification from Swift 2.0"
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
    localNotification.userInfo = ["Important":"Data"];
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = 5
    localNotification.category = "Message"

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}


//MARK: - viewDidLoad

class ViewController: UIViewController {

    var objButton : UIButton!
    . . .

    override func viewDidLoad() {
        super.viewDidLoad()

        . . .

        objButton = UIButton.buttonWithType(.Custom) as? UIButton
        objButton.frame = CGRectMake(30, 100, 150, 40)
        objButton.setTitle("Click Me", forState: .Normal)
        objButton.setTitle("Button pressed", forState: .Highlighted)

        objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)

        . . .
    }

    . . .
}

The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.

Screenshot

You can refer apple reference document for UserNotification.

Below is code for local notification:

Objective-C:

  1. In App-delegate.h file use @import UserNotifications;

  2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

  3. In didFinishLaunchingOptions use below code:

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
           completionHandler:^(BOOL granted, NSError * _Nullable error) {
                  if (!error) {
                      NSLog(@"request authorization succeeded!");
                      [self showAlert];
                  }
    }];
    
    -(void)showAlert {
        UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
          style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"Ok clicked!");
        }];
    
        [objAlertController addAction:cancelAction];
    
    
        [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{            
        }];
    
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
    
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger =  [UNTimeIntervalNotificationTrigger                                             triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten”                                                                            content:objNotificationContent trigger:trigger];
    
    // 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        } else {
            NSLog(@“Local Notification failed“);
        }
    }];
    

Swift 3:

  1. In AppDelegate.swift file use import UserNotifications
  2. Appdelegate should conform to UNUserNotificationCenterDelegate protocol
  3. In didFinishLaunchingWithOptions use below code

    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
        if error != nil {
            print("Request authorization failed!")
        } else {
            print("Request authorization succeeded!")
            self.showAlert()
        }
    }
    
    
    func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
    
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
    
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notify-test"
    
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
    
    let center = UNUserNotificationCenter.current()
    center.add(request)
    

How to backup MySQL database in PHP?

for using Cron Job, below is the php function

public function runback() {

    $filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';

    /*
     *  db backup
     */

    $command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass yourdb_name > $filename";
    system($command);
    if ($command == '') {
        /* no output is good */
        echo 'not done';
    } else {
       /* we have something to log the output here */
        echo 'done';
    }
}

There should not be any space between -u and username also no space between -p and password. CRON JOB command to run this script every sunday 8.30 am:

>> crontab -e

30 8 * * 7 curl -k https://www.websitename.com/takebackup

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Delete all nodes and relationships in neo4j 1.8

It will do the trick..

Match (n)-[r]-()
Delete n,r;

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

How to retrieve GET parameters from JavaScript

window.location.search will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:

function getSearchParameters() {
    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}

function transformToAssocArray( prmstr ) {
    var params = {};
    var prmarr = prmstr.split("&");
    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }
    return params;
}

var params = getSearchParameters();

You can then get the test parameter from http://myurl.com/?test=1 by calling params.test.

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

Where is Maven's settings.xml located on Mac OS?

If you use brew to install maven, then the settings file should be in

/usr/local/Cellar/maven/<version>/libexec/conf

Android Center text on canvas

Your code is drawing the center of the baseline of the text, at the center of the view. In order to center the text at some point, x, y, you need to calculate the center of the text, and put that at the point.

This method will draw text centered at the point x, y. If you pass it the center of your view, it will draw the text centered.

private void drawTextCentered(String text, int x, int y, Paint paint, Canvas canvas) {
    int xPos = x - (int)(paint.measureText(text)/2);
    int yPos = (int) (y - ((textPaint.descent() + textPaint.ascent()) / 2)) ;

    canvas.drawText(text, xPos, yPos, textPaint);
}

How do I use a file grep comparison inside a bash if/else statement?

Note that, for PIPE being any command or sequence of commands, then:

if PIPE ; then
  # do one thing if PIPE returned with zero status ($?=0)
else 
  # do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi 

For the record, [ expr ] is a shell builtin shorthand for test expr.

Since grep returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:

if grep -lq '^MYSQL_ROLE=master' ; then 
  # do one thing 
else 
  # do another thing
fi 

Note the use of -l which only cares about the file having at least one match (so that grep returns as soon as it finds one match, without needlessly continuing to parse the input file.)

on some platforms [ expr ] is not a builtin, but an actual executable /bin/[ (whose last argument will be ]), which is why [ expr ] should contain blanks around the square brackets, and why it must be followed by one of the command list separators (;, &&, ||, |, &, newline)

Passing bash variable to jq

Jq now have better way to acces environment variables, you can use env.EMAILI:

projectID=$(cat file.json | jq -r ".resource[] | select(.username==env.EMAILID) | .id")

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

How can I tell how many objects I've stored in an S3 bucket?

Following is how you can do it using java client.

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;

public class AmazonS3Service {

    private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
    private static final String S3_SECRET_KEY = "SECRET_KEY";
    private static final String S3_ENDPOINT = "S3_URL";

    private AmazonS3 amazonS3;

    public AmazonS3Service() {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        clientConfiguration.setSignerOverride("S3SignerType");
        BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
        AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
        amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
                .withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
    }

    public int countObjects(String bucketName) {
        int count = 0;
        ObjectListing objectListing = amazonS3.listObjects(bucketName);
        int currentBatchCount = objectListing.getObjectSummaries().size();
        while (currentBatchCount != 0) {
            count += currentBatchCount;
            objectListing = amazonS3.listNextBatchOfObjects(objectListing);
            currentBatchCount = objectListing.getObjectSummaries().size();
        }
        return count;
    }
}

log4j:WARN No appenders could be found for logger in web.xml

Put these lines in the beginning of web.xml:

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:/main/resources/log4j.xml</param-value>
</context-param> 

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

If you're behind a proxy, you should use X-Forwarded-For: http://en.wikipedia.org/wiki/X-Forwarded-For

It is an IETF draft standard with wide support:

The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.

If not, here are a couple other common headers I've seen:

How to center the text in PHPExcel merged cell

<?php
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Europe/London');

    /** Include PHPExcel */
    require_once '../Classes/PHPExcel.php';

    $objPHPExcel = new PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValueByColumnAndRow(0, 1, "test");
    $sheet->mergeCells('A1:B1');
    $sheet->getActiveSheet()->getStyle('A1:B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("test.xlsx");
?>

How to add "active" class to Html.ActionLink in ASP.NET MVC

I have make combination of answers above and made my solution.

So..

First in razor block create one string variable which will contain name value of controller and action that is called by user.

    @{
        string controllerAction =  ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString(); 
    }

Then use combination of HTML and Razor code:

    <ul class="nav navbar-nav">
        <li class="@(controllerAction == "HomeIndex" ? "active" : "" )">@Html.ActionLink("Home", "Index", "Home")</li>
        <li class="@(controllerAction == "AboutIndex" ? "active" : "" )">@Html.ActionLink("About", "Index", "About")</li>
        <li class="@(controllerAction == "HomeContact" ? "active" : "" )">@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>

I think, that this is good because you don't need to access "ViewContext.RouteData.Values" each time to get controller name and action name.

Provide an image for WhatsApp link sharing

You need the following tags to get a WhatsApp image preview:

<meta property="og:title" content="Website name" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://url.com/" />
<meta property="og:description" content="Website description" />
<meta property="og:image" content="image.png" />
<meta property="og:image:width" content="600" />
<meta property="og:image:height" content="600" />

As Facebook docs says, if you specify the og:image size it will be fetched fastly instead of asynchronously otherwise.

PNG is recommended for image format. 600x600 pixels at least is recommended.

How to draw text using only OpenGL methods?

I think that the best solution for drawing text in OpenGL is texture fonts, I work with them for a long time. They are flexible, fast and nice looking (with some rear exceptions). I use special program for converting font files (.ttf for example) to texture, which is saved to file of some internal "font" format (I've developed format and program based on http://content.gpwiki.org/index.php/OpenGL:Tutorials:Font_System though my version went rather far from the original supporting Unicode and so on). When starting the main app, fonts are loaded from this "internal" format. Look link above for more information.

With such approach the main app doesn't use any special libraries like FreeType, which is undesirable for me also. Text is being drawn using standard OpenGL functions.

iPhone Navigation Bar Title text color

Use like this for Orientation support

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];

UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];

Remove icon/logo from action bar on android

If you've defined android:logo="..." in the <application> tag of your AndroidManifest.xml, then you need to use this stuff to hide the icon:

pre-v11 theme

<item name="logo">@android:color/transparent</item>

v11 and up theme

<item name="android:logo">@android:color/transparent</item>

The use of these two styles has properly hidden the action bar icon on a 2.3 and a 4.4 device for me (this app uses AppCompat).

Difference between $(this) and event.target?

http://api.jquery.com/on/ states:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

If we have

<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">

<div id="outer">
    <input type="button"  value ="OuterB" id ="OuterB">
    <div id="inner">
        <input type="button" class="btn" value ="InnerB" id ="InnerB">
    </div>
</div>

Check the below output:

<script>
    $(function(){
        $(".btn").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        });


        $("#outer").on("click",function(event){
            console.log($(this));
            console.log($(event.currentTarget));
            console.log($(event.target));
        })
    })
</script>

Note that I use $ to wrap the dom element in order to create a jQuery object, which is how we always do.

You would find that for the first case, this ,event.currentTarget,event.target are all referenced to the same element.

While in the second case, when the event delegate to some wrapped element are triggered, event.target would be referenced to the triggered element, while this and event.currentTarget are referenced to where the event is delivered.

For this and event.currentTarget, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/

How do I create a datetime in Python from milliseconds?

Bit heavy because of using pandas but works:

import pandas as pd
pd.to_datetime(msec_from_java, unit='ms').to_pydatetime()

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

This is example:

$.ajax({
  url: "test.html",
  async: false
}).done(function(data) {
   // Todo something..
}).fail(function(xhr)  {
   // Todo something..
});

File input 'accept' attribute - is it useful?

In 2015 the only way I found to make it work for both Chrome and Firefox is to put all possible extensions you want to support, including variants (including the dot in front !):

accept=".jpeg, .jpg, .jpe, .jfif, .jif"

Problem with Firefox: Using the image/jpeg mime type Firefox will only show .jpg files, very strange as if the common .jpeg was not ok...

Whatever you do, be sure to try with files having many different extensions. Maybe it even depends on the OS ... I suppose accept is case insensitive, but maybe not in every browser.

Here is the MDN docs about accept:

accept If the value of the type attribute is file, then this attribute will indicate the types of files that the server accepts, otherwise it will be ignored. The value must be a comma-separated list of unique content type specifiers:

    A file extension starting with the STOP character (U+002E). (e.g. .jpg, .png, .doc).
    A valid MIME type with no extensions.
    audio/* representing sound files. HTML5
    video/* representing video files. HTML5
    image/* representing image files. HTML5

How can I get color-int from color resource?

Found an easier way that works as well:

Color.parseColor(getString(R.color.idname);

Matplotlib connect scatterplot points with line - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

How to "flatten" a multi-dimensional array to simple one in PHP?

function flatten_array($array, $preserve_keys = 0, &$out = array()) {
    # Flatten a multidimensional array to one dimension, optionally preserving keys.
    #
    # $array - the array to flatten
    # $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
    # $out - internal use argument for recursion
    foreach($array as $key => $child)
        if(is_array($child))
            $out = flatten_array($child, $preserve_keys, $out);
        elseif($preserve_keys + is_string($key) > 1)
            $out[$key] = $child;
        else
            $out[] = $child;
    return $out;
}

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

What's the difference between identifying and non-identifying relationships?

Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.

Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.

Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.

http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships

How to link to apps on the app store

Simply change 'itunes' to 'phobos' in the app link.

http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=300136119&mt=8

Now it will open the App Store directly

How to count lines of Java code using IntelliJ IDEA?

To find all including empty lines of code try @Neil's solution:

Open Find in Path (Ctrl+Shift+F)

Search for the following regular expression: \n'

For lines with at least one character use following expression:

(.+)\n

For lines with at least one word character or digit use following expression:

`(.*)([\w\d]+)(.*)\n`

Notice: But the last line of file is just counted if you have a line break after it.

How to get a pixel's x,y coordinate color from an image?

The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

enter image description here

Console output:

(0,0): TRANSPARENT
(150,150): NOT_TRANSPARENT

_x000D_
_x000D_
image = new MarvinImage();_x000D_
image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);_x000D_
_x000D_
function imageLoaded(){_x000D_
  console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
  console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));_x000D_
}
_x000D_
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
_x000D_
_x000D_
_x000D_

What is the difference between logical data model and conceptual data model?

Most answers here are strictly related to notations and syntax of the data models at different levels of abstraction. The key difference has not been mentioned by anyone. Conceptual models surface concepts. Concepts relate to other concepts in a different way that an Entity relates to another Entity at the Logical level of abstraction. Concepts are closer to Types. Usually at Conceptual level you display Types of things (this does not mean you must use the term "type" in your naming convention) and relationships between such types. Therefore, the existence of many-to-many relationships is not the rule but rather the consequence of the relationships between type-wise elements. In Logical Models Entities represent one instance of that thing in the real world. In Conceptual models it is not expected the description of an instance of an Entity and their relationships but rather the description of the "type" or "class" of that particular Entity. Examples: - Vehicles have Wheels and Wheels are used in Vehicles. At Conceptual level this is a many-to-many relationship - A particular Vehicle (a car by instance), with one specific registration number have 5 wheels and each particular wheel, each one with a serial number is related to only that particular car. At Logical level this is a one-to-many relationship.

Conceptual covers "types/classes". Logical covers "instances".

I would add another comment about databases. I agree with one of the colleagues who commented above that Conceptual and Logical models have absolutely nothing about databases. Conceptual and Logical models describe the real world from a data perspective using notations such as ER or UML. Database vendors, smartly, designed their products to follow the same philosophy used to logically model the World and them created Relational Databases, making everyone's lifes easier. You can describe your organisation's data landscape at all the levels using Conceptual and Logical model and never use a relational database.

Well I guess this is my 2 cents...

Send attachments with PHP Mail()?

HTML Code:

<form enctype="multipart/form-data" method="POST" action=""> 
    <label>Your Name <input type="text" name="sender_name" /> </label> 
    <label>Your Email <input type="email" name="sender_email" /> </label> 
    <label>Your Contact Number <input type="tel" name="contactnumber" /> </label>
    <label>Subject <input type="text" name="subject" /> </label> 
    <label>Message <textarea name="description"></textarea> </label> 
    <label>Attachment <input type="file" name="attachment" /></label> 
    <label><input type="submit" name="button" value="Submit" /></label> 
</form> 

PHP Code:

<?php
if($_POST['button']){
{
    //Server Variables
    $server_name = "Your Name";
    $server_mail = "[email protected]";

    //Name Attributes of HTML FORM
    $sender_email = "sender_email";
    $sender_name = "sender_name";
    $contact = "contactnumber";
    $mail_subject = "subject";
    $input_file = "attachment";
    $message = "description";

    //Fetching HTML Values
    $sender_name = $_POST[$sender_name];
    $sender_mail = $_POST[$sender_email];
    $message = $_POST[$message];
    $contact= $_POST[$contact];
    $mail_subject = $_POST[$mail_subject];

    //Checking if File is uploaded
    if(isset($_FILES[$input_file])) 
    { 
        //Main Content
        $main_subject = "Subject seen on server's mail";
        $main_body = "Hello $server_name,<br><br> 
        $sender_name ,contacted you through your website and the details are as below: <br><br> 
        Name : $sender_name <br> 
        Contact Number : $contact <br> 
        Email : $sender_mail <br> 
        Subject : $mail_subject <br> 
        Message : $message.";

        //Reply Content
        $reply_subject = "Subject seen on sender's mail";
        $reply_body = "Hello $sender_name,<br> 
        \t Thank you for filling the contact form. We will revert back to you shortly.<br><br>
        This is an auto generated mail sent from our Mail Server.<br>
        Please do not reply to this mail.<br>
        Regards<br>
        $server_name";

//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
        $filename= $_FILES[$input_file]['name'];
        $file = chunk_split(base64_encode(file_get_contents($_FILES[$input_file]['tmp_name'])));
        $uid = md5(uniqid(time()));
        //Sending mail to Server
        $retval = mail($server_mail, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n $main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
        //Sending mail to Sender
        $retval = mail($sender_mail, $reply_subject, $reply_body , "From: $server_name<$server_mail>\r\nMIME-Version: 1.0\r\nContent-type: text/html\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################

        //Output
        if ($retval == true) {
            echo "Message sent successfully...";
            echo "<script>window.location.replace('index.html');</script>";
        } else {
            echo "Error<br>";
            echo "Message could not be sent...Try again later";
            echo "<script>window.location.replace('index.html');</script>";
        }
    }else{
        echo "Error<br>";
        echo "File Not Found";
    }
}else{
    echo "Error<br>";
    echo "Unauthorised Access";
}

What's HTML character code 8203?

If you're seeing these in a source be aware that it may be someone attempting to fingerprint text documents to reveal who is leaking information. It also may be an attempt to bypass a spam filter by making the same looking information different on a byte-by-byte level.

See my article on mitigating fingerprinting if you're interested in learning more.

Sleep/Wait command in Batch

timeout 5

to delay

timeout 5 >nul

to delay without asking you to press any key to cancel

fill an array in C#

public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
    if (fromIndex > toIndex)
        throw new ArgumentOutOfRangeException("fromIndex");

    for (var i = fromIndex; i <= toIndex; i++)
        col[i] = value;
}

Something that works for all IList<T>s.

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

Fastest way to serialize and deserialize .NET objects

The binary serializer included with .net should be faster that the XmlSerializer. Or another serializer for protobuf, json, ...

But for some of them you need to add Attributes, or some other way to add metadata. For example ProtoBuf uses numeric property IDs internally, and the mapping needs to be somehow conserved by a different mechanism. Versioning isn't trivial with any serializer.

Where is android studio building my .apk file?

You should Build your app instead of debugging process. Just follow this:

Build -> Build Bundles/APK(s) -> Build APK(s)

enter image description here

How do I convert a byte array to Base64 in Java?

Use:

byte[] data = Base64.encode(base64str);

Encoding converts to Base64

You would need to reference commons codec from your project in order for that code to work.

For java8:

import java.util.Base64

How can I read command line parameters from an R script?

Dirk's answer here is everything you need. Here's a minimal reproducible example.

I made two files: exmpl.bat and exmpl.R.

  • exmpl.bat:

    set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
    %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
    

    Alternatively, using Rterm.exe:

    set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
    %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
    
  • exmpl.R:

    options(echo=TRUE) # if you want see commands in output file
    args <- commandArgs(trailingOnly = TRUE)
    print(args)
    # trailingOnly=TRUE means that only your arguments are returned, check:
    # print(commandArgs(trailingOnly=FALSE))
    
    start_date <- as.Date(args[1])
    name <- args[2]
    n <- as.integer(args[3])
    rm(args)
    
    # Some computations:
    x <- rnorm(n)
    png(paste(name,".png",sep=""))
    plot(start_date+(1L:n), x)
    dev.off()
    
    summary(x)
    

Save both files in the same directory and start exmpl.bat. In the result you'll get:

  • example.png with some plot
  • exmpl.batch with all that was done

You could also add an environment variable %R_Script%:

"C:\Program Files\R-3.0.2\bin\RScript.exe"

and use it in your batch scripts as %R_Script% <filename.r> <arguments>

Differences between RScript and Rterm:

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
ON DUPLICATE KEY UPDATE col_1 = VALUES(col_1), col_2 = VALUES(col_2), col_3 = VALUES(col_3), col_4 = VALUES(col_4), col_5 = VALUES(col_5), col_6 = VALUES(col_6), unit = VALUES(unit), add_info = VALUES(add_info), fsar_lock = VALUES(fsar_lock)

Would work with tbl_id and row_nr having UNIQUE key.

This is the method DocJonas linked to with an example.

Cloning an array in Javascript/Typescript

you can use map function

 toArray= fromArray.map(x => x);

Increment a Integer's int value?

You can use IntHolder as mutable alternative to Integer. But does it worth?

How to update the value stored in Dictionary in C#?

Just point to the dictionary at given key and assign a new value:

myDictionary[myKey] = myNewValue;

Detecting superfluous #includes in C/C++?

There is a free tool Include File Dependencies Watcher which can be integrated in the visual studio. It shows superfluous #includes in red.

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

Rename multiple files in a folder, add a prefix (Windows)

The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude option:

Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }

This will prevent the process from renaming any one file more than once.

Disable ScrollView Programmatically?

As you can see in the documentation, you cannot set the visibility to false. In your case you should probably use:

scrollview.setVisibility(Visibility.GONE);

Regular Expression to get all characters before "-"

This is something like the regular expression you need:

([^-]*)-

Quick tests in JavaScript:

/([^-]*)-/.exec('text-1')[1] // 'text'

/([^-]*)-/.exec('foo-bar-1')[1] // 'foo'

/([^-]*)-/.exec('-1')[1] // ''

/([^-]*)-/.exec('quux')[1] // explodes

How to replace part of string by position?

string myString = "ABCDEFGHIJ";
string modifiedString = new StringBuilder(myString){[3]='Z', [4]='X'}.ToString();

Let me explain my solution.
Given the problem statement of altering a string in its two specific position (“position 4 to position 5”) with two character ‘Z’ and ‘X’ and the ask is to use the position index to alter the string and not string Replace() method(may be because of the possibility of repetition of some characters in the actual string), I would prefer to use minimalist approach to achieve the goal over using Substring() and string Concat() or string Remove() and Insert() approach. Though all those solutions will serve the purpose in attaining the same goal, but it just depends on personal choice and philosophy of settling with minimalist approach.
Coming back to my solution mention above, if we take a closer look of string and StringBuilder, both of them internally treats a given string as an array of characters. If we look at the implementation of StringBuilder it maintains an internal variable something like “internal char[] m_ChunkChars;” to capture the given string. Now since this is an internal variable, we cannot directly access the same. For external world, to be able to access and alter that character array, StringBuilder exposes them through indexer property which looks something like below

    [IndexerName("Chars")]
    public char this[int index]
    {
      get
      {
        StringBuilder stringBuilder = this;
        do
        {
          // … some code
            return stringBuilder.m_ChunkChars[index1];
          // … some more code
        }
      }
      set
      {
        StringBuilder stringBuilder = this;
        do
        {
            //… some code
            stringBuilder.m_ChunkChars[index1] = value;
            return;
            // …. Some more code
        }
      }
    }

My solution mentioned above leverage this indexer capability to directly alter the internally maintained character array which IMO is efficient and minimalist.

BTW; we can rewrite the above solution more elaborately something like below

 string myString = "ABCDEFGHIJ";
 StringBuilder tempString = new StringBuilder(myString);
 tempString[3] = 'Z';
 tempString[4] = 'X';
 string modifiedString = tempString.ToString();

In this context also would like to mention that in case of string it also have indexer property as a means to expose its internal character array, but in this case it only has Getter property (and no Setter) as string is immutable in nature. And that is why we need to use StringBuilder to alter the character array.

[IndexerName("Chars")]
public extern char this[int index] { [SecuritySafeCritical, __DynamicallyInvokable, MethodImpl(MethodImplOptions.InternalCall)] get; }

And last but not the least this solution is only best fit for this specific problem where the ask is to replace only few characters with a known position index upfront. It may not be the best fit when the requirement is to alter a fairly lengthy string i.e. number of characters to alter are large in numbers.

How to remove leading and trailing white spaces from a given html string?

01). If you need to remove only leading and trailing white space use this:

var address = "  No.255 Colombo  "
address.replace(/^[ ]+|[ ]+$/g,'');

this will return string "No.255 Colombo"

02). If you need to remove all the white space use this:

var address = "  No.255 Colombo  "
address.replace(/\s/g,"");

this will return string "No.255Colombo"

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

Why is the GETDATE() an invalid identifier

Use ORACLE equivalent of getdate() which is sysdate . Read about here. Getdate() belongs to SQL Server , will not work on Oracle.

Other option is current_date

What HTTP traffic monitor would you recommend for Windows?

I like TcpCatcher because it is very simple to use and has a modern interface. It is provided as a jar file, you just download it and run it (no installation process). Also, it comes with a very useful "on the fly" packets modification features (debug mode).

history.replaceState() example?

The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page

But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object

Reference: http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/

How do I check if file exists in jQuery or pure JavaScript?

I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:

checkFileExistence= function (file){
    result=false;
    jQuery.ajaxSetup({async:false});
    $.get(file)
        .done(function() {
           result=true;
        })
        .fail(function() {
           result=false;
        })
    jQuery.ajaxSetup({async:true});
    return(result);
},

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Tested on a Huawei P20:

  1. Uninstall (or disable) Play Store.
  2. Reinstall Google Play: (Source)

    1. Download the latest version of Google Play Store from APK Mirror.
    2. Install the app simply by opening the APK file.
  3. Restart device.

Note: before finding this solution, I followed the instructions from some of the other answers here: removed my Google account from my device and added it again, cleared data and cache from various google play apps. This may or may not be necessary; feedback is welcome.

Exit Shell Script Based on Process Exit Code

http://cfaj.freeshell.org/shell/cus-faq-2.html#11

  1. How do I get the exit code of cmd1 in cmd1|cmd2

    First, note that cmd1 exit code could be non-zero and still don't mean an error. This happens for instance in

    cmd | head -1
    

    You might observe a 141 (or 269 with ksh93) exit status of cmd1, but it's because cmd was interrupted by a SIGPIPE signal when head -1 terminated after having read one line.

    To know the exit status of the elements of a pipeline cmd1 | cmd2 | cmd3

    a. with Z shell (zsh):

    The exit codes are provided in the pipestatus special array. cmd1 exit code is in $pipestatus[1], cmd3 exit code in $pipestatus[3], so that $? is always the same as $pipestatus[-1].

    b. with Bash:

    The exit codes are provided in the PIPESTATUS special array. cmd1 exit code is in ${PIPESTATUS[0]}, cmd3 exit code in ${PIPESTATUS[2]}, so that $? is always the same as ${PIPESTATUS: -1}.

    ...

    For more details see Z shell.

Get width in pixels from element with style set with %?

You can use offsetWidth. Refer to this post and question for more.

_x000D_
_x000D_
console.log("width:" + document.getElementsByTagName("div")[0].offsetWidth + "px");
_x000D_
div {border: 1px solid #F00;}
_x000D_
<div style="width: 100%; height: 10px;"></div>
_x000D_
_x000D_
_x000D_

Is there a way to run Python on Android?

Yet another attempt: https://code.google.com/p/android-python27/

This one embed directly the Python interpretter in your app apk.

How to disable or enable viewpager swiping in android

For disabling swiping

mViewPager.beginFakeDrag();

For enable swiping

if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

How to assign an exec result to a sql variable?

This will work if you wish to simply return an integer:

DECLARE @ResultForPos INT 
EXEC @ResultForPos = storedprocedureName 'InputParameter'
SELECT @ResultForPos

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

How to stop a thread created by implementing runnable interface?

Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.

This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter

 i=0;
            w_h = 0;
            w_m = 0;


            textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
                        hl.removeCallbacksAndMessages(null);
                        Thread.currentThread().isInterrupted();


                        }


                    });


                }`

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How to bind a List to a ComboBox?

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

For 2) you will need a list of countries first

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

AngularJs ReferenceError: $http is not defined

Probably you haven't injected $http service to your controller. There are several ways of doing that.

Please read this reference about DI. Then it gets very simple:

function MyController($scope, $http) {
   // ... your code
}

How to add an element to Array and shift indexes?

org.apache.commons.lang3.ArrayUtils#add(T[], int, T) is deprecated in newest commons lang3, you can use org.apache.commons.lang3.ArrayUtils#insert(int, T[], T...) instead.

Deprecated this method has been superseded by insert(int, T[], T...) and may be removed in a future release. Please note the handling of null input arrays differs in the new method: inserting X into a null array results in null not X

Sample code:

    Assert.assertArrayEquals
            (org.apache.commons.lang3.ArrayUtils.insert
            (4, new int[]{1, 2, 3, 4, 5, 6}, 87), new int[]{1, 2, 3, 4, 87, 5, 6});

BackgroundWorker vs background Thread

From my understanding of your question, you are using a BackgroundWorker as a standard Thread.

The reason why BackgroundWorker is recommended for things that you don't want to tie up the UI thread is because it exposes some nice events when doing Win Forms development.

Events like RunWorkerCompleted to signal when the thread has completed what it needed to do, and the ProgressChanged event to update the GUI on the threads progress.

So if you aren't making use of these, I don't see any harm in using a standard Thread for what you need to do.

How may I reference the script tag that loaded the currently-executing script?

I have found the following code to be the most consistent, performant, and simple.

var scripts = document.getElementsByTagName('script');
var thisScript = null;
var i = scripts.length;
while (i--) {
  if (scripts[i].src && (scripts[i].src.indexOf('yourscript.js') !== -1)) {
    thisScript = scripts[i];
    break;
  }
}
console.log(thisScript);

What are the true benefits of ExpandoObject?

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you.

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

JSON post to Spring Controller

You need to include the getters and setters for all the fields that have been defined in the model Test class --

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Pythonic way to find maximum value and its index in a list?

sorry for reviving this thread, but thought my method was worth adding.

The list name in this example 'list'

list.sort()
print(list[-1])

That will print the highest value in the list easy as!

list.sort() sorts the list by the value of the item in the ASCII table, so effectively sorts the list lowest to highest. I then just print the last value in the list (which will be the greatest number) by using print(list[-1]).

Hope this helps!

Android Fragment onClick button Method

For Kotlin users:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?, 
    savedInstanceState: Bundle?) : View?
{
    // Inflate the layout for this fragment
    var myView = inflater.inflate(R.layout.fragment_home, container, false)
    var btn_test = myView.btn_test as Button
    btn_test.setOnClickListener {
        textView.text = "hunny home fragment"
    }

    return myView
}

How to set Spinner Default by its Value instead of Position?

If the list you use for the spinner is an object then you can find its position like this

private int selectSpinnerValue( List<Object> ListSpinner,String myString) 
{
    int index = 0;
    for(int i = 0; i < ListSpinner.size(); i++){
      if(ListSpinner.get(i).getValueEquals().equals(myString)){
          index=i;
          break;
      }
    }
    return index;
}

using:

 int index=selectSpinnerValue(ListOfSpinner,StringEquals);
    spinner.setSelection(index,true);

How to convert numpy arrays to standard TensorFlow format?

You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray into a Tensor:

import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()

UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.

Selecting default item from Combobox C#

first, go to the form load where your comboBox is located,

then try this code

comboBox1.SelectedValue = 0; //shows the 1st item in your collection

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

In my case I was using version 17.0.1 .It was showing error.

implementation "com.google.android.gms:play-services-location:17.0.1"

After changing version to 17.0.0, it worked

implementation "com.google.android.gms:play-services-location:17.0.0"

Reason might be I was using maps dependency of version 17.0.0 & location version as 17.0.1.It might have thrown error.So,try to maintain consistency in version numbers.

How to Convert unsigned char* to std::string in C++?

BYTE* is probably a typedef for unsigned char*, but I can't say for sure. It would help if you tell us what BYTE is.

If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.

const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);

That being said, are you sure this is a good idea? If BYTE is unsigned char it may contain non-ASCII characters, which can include NULLs. This will make strlen give an incorrect length.

Setting "checked" for a checkbox with jQuery

To check and uncheck

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.

instead of mvn clean package or mvn package you can try only package its work fine for me

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

MySQL Where DateTime is greater than today

SELECT * 
FROM customer 
WHERE joiningdate >= NOW();

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Coming from someone who has tried a number of "C# IDEs" on the Mac, your best bet is to install a virtual desktop with Windows and Visual Studio. It really is the best development IDE out there for .NET, nothing even comes close.

On a related note: I hate XCode.


Update: Use Xamarin Studio. It's solid.

How do I convert a double into a string in C++?

If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

Usage:

string s = to_string(42.5);

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%}

Should I use <i> tag for icons instead of <span>?

Quentin's answer clearly states that i tag should not be used to define icons.

But, Holly suggested that span has no meaning in itself and voted in favor of i instead of span tag.

Few suggested to use img as it's semantic and contains alt tag. But, we should not also use img because even empty src sends a request to server. Read here

I think, the correct way would be,

<span class="icon-fb" role="img" aria-label="facebook"></span>

This solves the issue of no alt tag in span and makes it accessible to vision-impaired users. It's semantic and not misusing ( hacking ) any tag.

boolean in an if statement

I think that your reasoning is sound. But in practice I have found that it is far more common to omit the === comparison. I think that there are three reasons for that:

  1. It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
  2. Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefined or null value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
  3. JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.

Consider this example:

var someString = getInput();
var normalized = someString && trim(someString);  
// trim() removes leading and trailing whitespace

if (normalized) {
    submitInput(normalized);
}

I think that this kind of code is not uncommon. It handles cases where getInput() returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput() is only called if the given input is a string that contains non-whitespace characters.

In JavaScript && returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized will be undefined if someString was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.

I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null or undefined values, which would clutter up the code. In JavaScript that is not needed.

Get the key corresponding to the minimum value within a dictionary

For the case where you have multiple minimal keys and want to keep it simple

def minimums(some_dict):
    positions = [] # output variable
    min_value = float("inf")
    for k, v in some_dict.items():
        if v == min_value:
            positions.append(k)
        if v < min_value:
            min_value = v
            positions = [] # output variable
            positions.append(k)

    return positions

minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})

['e', 'c']

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Adding Lombok plugin to IntelliJ project

I just found how.

I delete the first occurrence of lombok @Slf4j or log where the compiler complains, and wait for the warning(the red bubble) of IDEA, suggesting "add the lombok.extern.Slf4j.jar to classpath". Since then all goes well. It seems IDEA likes to complain about lombok.

clearing a char array c

An array in C is just a memory location, so indeed, your my_custom_data[0] = '\0'; assignment simply sets the first element to zero and leaves the other elements intact.

If you want to clear all the elements of the array, you'll have to visit each element. That is what memset is for:

memset(&arr[0], 0, sizeof(arr));

This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:

char *begin = &arr;
char *end = begin + sizeof(arr);
std::fill(begin, end, 0);

Retrieve WordPress root directory path?

Note: This answer is really old and things may have changed in WordPress land since.

I am guessing that you need to detect the WordPress root from your plugin or theme. I use the following code in FireStats to detect the root WordPress directory where FireStats is installed a a WordPress plugin.

function fs_get_wp_config_path()
{
    $base = dirname(__FILE__);
    $path = false;

    if (@file_exists(dirname(dirname($base))."/wp-config.php"))
    {
        $path = dirname(dirname($base))."/wp-config.php";
    }
    else
    if (@file_exists(dirname(dirname(dirname($base)))."/wp-config.php"))
    {
        $path = dirname(dirname(dirname($base)))."/wp-config.php";
    }
    else
        $path = false;

    if ($path != false)
    {
        $path = str_replace("\\", "/", $path);
    }
    return $path;
}

How to fetch the dropdown values from database and display in jsp

You can learn some tutorials for JSP page direct access database (mysql) here

Notes:

  • import sql tag library in jsp page

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • then set datasource on page

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • Now query what you want on page

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • Finally you can populate dropdowns on page using c:forEach tag to iterate result rows in select element

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

Process escape sequences in a string in Python

Below code should work for \n is required to be displayed on the string.

import string

our_str = 'The String is \\n, \\n and \\n!'
new_str = string.replace(our_str, '/\\n', '/\n', 1)
print(new_str)

onchange event for html.dropdownlist

You can do this

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
  { 

       Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
       {
           onchange = @"form.submit();"
       }
})

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

Append column to pandas dataframe

You can also use:

dat1 = pd.concat([dat1, dat2], axis=1)

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

Git error: "Please make sure you have the correct access rights and the repository exists"

I experienced this issue when I had an invalid RSA SSH key, and a valid ED25519 SSH key on my machine. I believe Gitlab was checking the RSA key, failing and stopping there before checking the ED25519 key.

I fixed this by deleting both of the keys I had on my device and generating a new RSA SSH, and providing that too gitlab.

Java File - Open A File And Write To It

Suggestions:

  • Create a File object that refers to the already existing file on disk.
  • Use a FileWriter object, and use the constructor that takes the File object and a boolean, the latter if true would allow appending text into the File if it exists.
  • Then initialize a PrintWriter passing in the FileWriter into its constructor.
  • Then call println(...) on your PrintWriter, writing your new text into the file.
  • As always, close your resources (the PrintWriter) when you are done with it.
  • As always, don't ignore exceptions but rather catch and handle them.
  • The close() of the PrintWriter should be in the try's finally block.

e.g.,

  PrintWriter pw = null;

  try {
     File file = new File("fubars.txt");
     FileWriter fw = new FileWriter(file, true);
     pw = new PrintWriter(fw);
     pw.println("Fubars rule!");
  } catch (IOException e) {
     e.printStackTrace();
  } finally {
     if (pw != null) {
        pw.close();
     }
  }

Easy, no?

Casting a variable using a Type variable

When it comes to casting to Enum type:

private static Enum GetEnum(Type type, int value)
    {
        if (type.IsEnum)
            if (Enum.IsDefined(type, value))
            {
                return (Enum)Enum.ToObject(type, value);
            }

        return null;
    }

And you will call it like that:

var enumValue = GetEnum(typeof(YourEnum), foo);

This was essential for me in case of getting Description attribute value of several enum types by int value:

public enum YourEnum
{
    [Description("Desc1")]
    Val1,
    [Description("Desc2")]
    Val2,
    Val3,
}

public static string GetDescriptionFromEnum(Enum value, bool inherit)
    {
        Type type = value.GetType();

        System.Reflection.MemberInfo[] memInfo = type.GetMember(value.ToString());

        if (memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), inherit);
            if (attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }

        return value.ToString();
    }

and then:

string description = GetDescriptionFromEnum(GetEnum(typeof(YourEnum), foo));
string description2 = GetDescriptionFromEnum(GetEnum(typeof(YourEnum2), foo2));
string description3 = GetDescriptionFromEnum(GetEnum(typeof(YourEnum3), foo3));

Alternatively (better approach), such casting could look like that:

 private static T GetEnum<T>(int v) where T : struct, IConvertible
    {
        if (typeof(T).IsEnum)
            if (Enum.IsDefined(typeof(T), v))
            {
                return (T)Enum.ToObject(typeof(T), v);
            }

        throw new ArgumentException(string.Format("{0} is not a valid value of {1}", v, typeof(T).Name));
    }

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Datatables on-the-fly resizing

might be late also like the other answer but I did this early this year and the solution I came up with is using css.

    $(window).bind('resize', function () {
        /*the line below was causing the page to keep loading.
        $('#tableData').dataTable().fnAdjustColumnSizing();
        Below is a workaround. The above should automatically work.*/
        $('#tableData').css('width', '100%');
    } );

How to add class active on specific li on user click with jQuery

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

Parsing JSON from URL

Here is a easy method.

First parse the JSON from url -

public String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);

    try {

        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            inputStream.close();

        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

Then place a task and then read the desired value from JSON -

private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result) {

        JSONObject json;
        try {
            json = new JSONObject(result);

        ////CREATE A JSON OBJECT////

        JSONObject data = json.getJSONObject("JSON OBJECT NAME");

        ////GET A STRING////

        String title = data.getString("");

        //Similarly you can get other types of data
        //Replace String to the desired data type like int or boolean etc.

        } catch (JSONException e1) {
            e1.printStackTrace();

        }

        //GETTINGS DATA FROM JSON ARRAY//

        try {

            JSONObject jsonObject = new JSONObject(result);
            JSONArray postalCodesItems = new JSONArray(
                    jsonObject.getString("postalCodes"));

                JSONObject postalCodesItem = postalCodesItems
                        .getJSONObject(1);

        } catch (Exception e) {
            Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
        }
    }
}

You can then place a task like this -

new ReadPlacesFeedTask()
    .execute("JSON URL");

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

To execute more Maven builds from one script you shall use the Windows call function in the following way:

call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true

initializing a Guava ImmutableMap

Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

You want an ImmutableMap.Builder:

ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
    .put("key1", "value1") 
    .put("key2", "value2") 
    .put("key3", "value3") 
    .put("key4", "value4") 
    .put("key5", "value5") 
    .put("key6", "value6") 
    .put("key7", "value7") 
    .put("key8", "value8") 
    .put("key9", "value9")
    .build();

Wait some seconds without blocking UI execution

I think what you are after is Task.Delay. This doesn't block the thread like Sleep does and it means you can do this using a single thread using the async programming model.

async Task PutTaskDelay()
{
    await Task.Delay(5000);
} 

private async void btnTaskDelay_Click(object sender, EventArgs e)
{
    await PutTaskDelay();
    MessageBox.Show("I am back");
}

How do I format date in jQuery datetimepicker?

this worked for me.

$(document).ready(function () {
    $("#datePicker").datetimepicker({
        format: 'DD/MM/YYYY HH:mm:ss',
        defaultDate: new Date(),
    });
}

here are the CDN links

<!-- datetime picker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.min.css"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Postman: sending nested JSON object

For a nested Json(example below), you can form a query using postman as shown below.

{
    "Items": {
        "sku": "10 Units",
        "Price": "20 Rs"
    },
    "Characteristics": {
        "color": "blue",
        "weight": "2 lb"
    }
}

enter image description here

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

In Windows 10, Windows Defender has a feature of core isolation which uses virtualisation technology that will also interupt in working of HAXM. Disable it and try again. In my case disabling it solved my issue.

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

If you are using maven then you can add the tomcat7-maven-plugin to your pom.xml and it shall run fine. This plugin will run the project on Tomcat servlet container version 7.0.47 which supports JDK 1.8.

    <plugins>
    <plugin>
     <groupId>org.apache.tomcat.maven</groupId>
     <artifactId>tomcat7-maven-plugin</artifactId>
     <version>2.2</version>
     <configuration>
<!-- Include context file for Datasource configuration -->
     <contextFile>./src/main/webapp/META-INF/context.xml</contextFile>
    <port>8080</port>
     </configuration>
     <dependencies>
<!-- Include jdbc driver dependency if using datasource (in my case oracle) -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.4.0</version>
    </dependency>
  </dependencies>
    </plugin>
    </plugins>

Hope this is useful! Thanks

Auto-loading lib files in Rails 4

This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module whose name matched my filename appropriately, rather than just defining a class:

In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))

module DevelopmentMailInterceptor
  class DevelopmentMailInterceptor
    def self.delivering_email(message)
      message.subject = "intercepted for: #{message.to} #{message.subject}"
      message.to = "[email protected]"
    end
  end
end

works, but it doesn't load if I hadn't put the class inside a module.

jQuery UI Sortable Position

I wasn't quite sure where I would store the start position, so I want to elaborate on David Boikes comment. I found that I could store that variable in the ui.item object itself and retrieve it in the stop function as so:

$( "#sortable" ).sortable({
    start: function(event, ui) {
        ui.item.startPos = ui.item.index();
    },
    stop: function(event, ui) {
        console.log("Start position: " + ui.item.startPos);
        console.log("New position: " + ui.item.index());
    }
});

How are ssl certificates verified?

It's worth noting that in addition to purchasing a certificate (as mentioned above), you can also create your own for free; this is referred to as a "self-signed certificate". The difference between a self-signed certificate and one that's purchased is simple: the purchased one has been signed by a Certificate Authority that your browser already knows about. In other words, your browser can easily validate the authenticity of a purchased certificate.

Unfortunately this has led to a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect.

If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.).

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Adding a leading zero to some values in column in MySQL

Possibly:

select lpad(column, 8, 0) from table;

Edited in response to question from mylesg, in comments below:

ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT

I'm assuming that you used a query similar to:

UPDATE table SET columnName=lpad(nums,8,0);

If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:

First:

ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);

Second, run the update:

UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');

This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.

References:

What is the difference between compare() and compareTo()?

compareTo(T object)

comes from the java.lang.Comparable interface, implemented to compare this object with another to give a negative int value for this object being less than, 0 for equals, or positive value for greater than the other. This is the more convenient compare method, but must be implemented in every class you want to compare.

compare(T obj1, T obj2)

comes from the java.util.Comparator interface, implemented in a separate class that compares another class's objects to give a negative int value for the first object being less than, 0 for equals, or positive value for greater than the second object. It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age).

Test if object implements interface

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Convert a String to int?

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

How can I change the color of my prompt in zsh (different from normal text)?

To complement all of the above answers another convenient trick is to place the coloured prompt settings into a zsh function. There you may define local variables to alias longer commands, e.g. rc=$reset_color or define your own colour variables. Don't forget to place it into your .zshrc file and call the function you have defined:

# Coloured prompt
autoload -U colors && colors
function myprompt {
  local rc=$reset_color
  export PS1="%F{cyan}%n%{$rc%}@%F{green}%m%{$rc%}:%F{magenta}%~%{$rc%}%# "
}
myprompt

General guidelines to avoid memory leaks in C++

valgrind is a good tool to check your programs memory leakages at runtime, too.

It is available on most flavors of Linux (including Android) and on Darwin.

If you use to write unit tests for your programs, you should get in the habit of systematicaly running valgrind on tests. It will potentially avoid many memory leaks at an early stage. It is also usually easier to pinpoint them in simple tests that in a full software.

Of course this advice stay valid for any other memory check tool.

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

Twitter bootstrap 3 two columns full height

try

<div class="container">
    <div class="row">
        <div class="col-md-12">header section</div>

    </div>
     <div class="row fill">
        <div class="col-md-4">Navigation</div>
        <div class="col-md-8">Content</div>

    </div>
</div>

css for .fill class is below

 .fill{
    width:100%;
    height:100%;
    min-height:100%;
    padding:10px;
    color:#efefef;
    background: blue;
}
.col-md-12
{
    background: red;

}

.col-md-4
{
    background: yellow;
    height:100%;
    min-height:100%;

}
.col-md-8
{
    background: green;
    height:100%;
    min-height:100%;

}

For your reference just look into the fiddle.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

If you don't have the fortune of the log4j-1.2.jar on your classpath as Renko points out in his comment, you will only see the message no log4j2 configuration file found.

This is a problem if there is an error in your configuration file, as you will not be told where the problem lies upon start-up.

For instance if you have a log4j2.yaml file which log4j2 fails to process, because for example, you have not configured a YAML parser for your project, or your config is simply incorrect. You will encounter the no log4j2 configuration file found message, with no further information. This is the case even if you have a valid log4j2.xml file, as log4j2 will only attempt to process the first configuration file it finds.

I've found the best way to debug the problem is to explicitly state the configuration file you wish to use as per the command line argument mentioned above.

-Dlog4j.configurationFile=

Hopefully this will help you pinpoint if the issue is actually caused by your classloader not finding the log4j2 configuration file or something else in your configuration.

Update

You can also use the below property to change the default level of the status logger to get further information:

-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=<level>

How to use moment.js library in angular 2 typescript app?

To use it in a Typescript project you will need to install moment:

npm install moment --save

After installing moment, you can use it in any .ts file after importing it:

import * as moment from "moment";

How to update an "array of objects" with Firestore?

We can use arrayUnion({}) method to achive this.

Try this:

collectionRef.doc(ID).update({
    sharedWith: admin.firestore.FieldValue.arrayUnion({
       who: "[email protected]",
       when: new Date()
    })
});

Documentation can find here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

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

FLOAT stores floating point numbers with accuracy up to eight places and has four bytes while DOUBLE stores floating point numbers with accuracy upto 18 places and has eight bytes.

Postgres: clear entire database before re-creating / re-populating from bash script

I've used:

pg_restore -c -d database_name filename.dump

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

Close popup window

You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :

window.open

then

window.close

will work. Or else not.

What is a Python egg?

The .egg file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe. But note that for pure Python, the .egg file is completely cross-platform.

The .egg file itself is essentially a .zip file. If you change the extension to “zip”, you can see that it will have folders inside the archive.

Also, if you have an .egg file, you can install it as a package using easy_install

Example: To create an .egg file for a directory say mymath which itself may have several python scripts, do the following step:

# setup.py
from setuptools import setup, find_packages
setup(
    name = "mymath",
    version = "0.1",
    packages = find_packages()
    )

Then, from the terminal do:

 $ python setup.py bdist_egg

This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg file, mymath-0.1-py3.5.egg with your default python (installation) version number(mine here: 3.5)

Source: Python library blog

MySQL limit from descending order

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.

How to insert a picture into Excel at a specified cell position with VBA

I have been working on a system that ran on a PC and Mac and was battling to find code that worked for inserting pictures on both PC and Mac. This worked for me so hopefully someone else can make use of it!

Note: the strPictureFilePath and strPictureFileName variables need to be set to valid PC and Mac paths Eg

For PC: strPictureFilePath = "E:\Dropbox\" and strPictureFileName = "TestImage.jpg" and with Mac: strPictureFilePath = "Macintosh HD:Dropbox:" and strPictureFileName = "TestImage.jpg"

Code as Follows:

    On Error GoTo ErrorOccured

    shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Select

    ActiveSheet.Pictures.Insert(Trim(strPictureFilePath & strPictureFileName)).Select

    Selection.ShapeRange.Left = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Left
    Selection.ShapeRange.Top = shtRecipeBrowser.Cells(intDestinationRecipeRowCount, 1).Top + 10
    Selection.ShapeRange.LockAspectRatio = msoTrue
    Selection.ShapeRange.Height = 130

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

How to sort by dates excel?

If you dont want to format a separate column with you normal dates pasted to it -- do the following -- add a column to the extreme left of your data and reverve your date ie if the date you had already entered was for example 11.5.16 enter int he new lefthand column 160511 ( notice that there are numbers only and no full stops . When you now sort there will be no mix ups as you have encountered.i have used this method for over 30 years and it never lets me down. And as you have placed the date by year, month and day you neednt include that column if you want or need tu print out your complete list.

Retain precision with double in Java

As others have noted, not all decimal values can be represented as binary since decimal is based on powers of 10 and binary is based on powers of two.

If precision matters, use BigDecimal, but if you just want friendly output:

System.out.printf("%.2f\n", total);

Will give you:

11.40

How to Copy Text to Clip Board in Android?

Kotlin helper method to attach click to copy Texts on a TextView

Put this method somewhere in Util class. This method attach click listener on textview to Copy Content of textView to a clipText on click of that textView

/**
 * Param:  cliplabel, textview, context
 */
fun attachClickToCopyText(textView: TextView?, clipLabel: String, context: Context?) {
    if (textView != null && null != context) {
        textView.setOnClickListener {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clip = ClipData.newPlainText(clipLabel, textView!!.text)
            clipboard.primaryClip = clip
            Snackbar.make(textView,
                    "Copied $clipLabel", Snackbar.LENGTH_LONG).show()
        }
    }

}

RecyclerView inside ScrollView is not working

**Solution which worked for me
Use NestedScrollView with height as wrap_content

<br> RecyclerView 
                android:layout_width="match_parent"<br>
                android:layout_height="wrap_content"<br>
                android:nestedScrollingEnabled="false"<br>
                  app:layoutManager="android.support.v7.widget.LinearLayoutManager"
                tools:targetApi="lollipop"<br><br> and view holder layout 
 <br> android:layout_width="match_parent"<br>
        android:layout_height="wrap_content"

//Your row content goes here

Python [Errno 98] Address already in use

run the command

fuser -k (port_number_you_are _trying_to_access)/TCP

example for flask: fuser -k 5000/tcp

Also, remember this error arises when you interput by ctrl+z. so to terminate use ctrl+c

How do you do exponentiation in C?

or you could just write the power function, with recursion as a added bonus

int power(int x, int y){
      if(y == 0)
        return 1;
     return (x * power(x,y-1) );
    }

yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

One way is to associating unique properties with your file while creation.

properties = "{ \
    key='somekey' and \
    value='somevalue'
}"

then create a query.

query = "title = " + "\'" + title + "\'" + \
        AND + "mimeType = " + "\'" + mimeType + "\'" + \
        AND + "trashed = false" + \
        AND + "properties has " + properties

All the file properties(title, etc) already known to you can go here + properties.

Fast Linux file count for a large number of files

You could try if using opendir() and readdir() in Perl is faster. For an example of those function, look here.

Convert UTC dates to local time in PHP

Date arithmetic is not needed if you just want to display the same timestamp in different timezones:

$format = "M d, Y h:ia";
$timestamp = gmdate($format);

date_default_timezone_set("UTC");
$utc_datetime = date($format, $timestamp);

date_default_timezone_set("America/Guayaquil");
$local_datetime = date($format, $timestamp);

Can anyone explain python's relative imports?

You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

With start.py:

import pkg.sub.relative

Now pkg is the top level package and your relative import should work.


If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

How do implement a breadth first traversal?

//traverse
public void traverse()
{
    if(node == null)
        System.out.println("Empty tree");
    else
    {
        Queue<Node> q= new LinkedList<Node>();
        q.add(node);
        while(q.peek() != null)
        {
            Node temp = q.remove();
            System.out.println(temp.getData());
            if(temp.left != null)
                q.add(temp.left);
            if(temp.right != null)
                q.add(temp.right);
        }
    }
}

}

How can I echo the whole content of a .html file in PHP?

Just use:

<?php
    include("/path/to/file.html");
?>

That will echo it as well. This also has the benefit of executing any PHP in the file.

If you need to do anything with the contents, use file_get_contents(),

For example,

<?php
    $pagecontents = file_get_contents("/path/to/file.html");

    echo str_replace("Banana", "Pineapple", $pagecontents);

?>

This doesn't execute code in that file, so be careful if you expect that to work.

I usually use:

include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");

as then I can move files without breaking the includes.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I ran into this problem because I had OpenVPN running. As soon as I killed OpenVPN, docker-compose up fired right up, and the error disappeared.

Unsetting array values in a foreach loop

Sorry for the late response, I recently had the same problem with PHP and found out that when working with arrays that do not use $key => $value structure, when using the foreach loop you actual copy the value of the position on the loop variable, in this case $image. Try using this code and it will fix your problem.

for ($i=0; $i < count($images[1]); $i++)
{

    if($images[1][$i] == 'http://i27.tinypic.com/29yk345.gif' ||

    $images[1][$i] == 'http://img3.abload.de/img/10nx2340fhco.gif' ||

    $images[1][$i] == 'http://i42.tinypic.com/9pp2456x.gif')

    {

        unset($images[1][$i]);

    }

}

var_dump($images);die();

iptables LOG and DROP in one rule

At work, I needed to log and block SSLv3 connections on ports 993 (IMAPS) and 995 (POP3S) using iptables. So, I combined Gert van Dijk's How to take down SSLv3 in your network using iptables firewall? (POODLE) with Prevok's answer and came up with this:

iptables -N SSLv3
iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
iptables -A SSLv3 -j DROP
iptables -A INPUT \
  -p tcp \! -f -m multiport --dports 993,995 \
  -m state --state ESTABLISHED -m u32 --u32 \
  "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
   0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
   0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
  -j SSLv3

Explanation

  1. To LOG and DROP, create a custom chain (e.g. SSLv3):

    iptables -N SSLv3
    iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
    iptables -A SSLv3 -j DROP
    
  2. Then, redirect what you want to LOG and DROP to that chain (see -j SSLv3):

    iptables -A INPUT \
      -p tcp \! -f -m multiport --dports 993,995 \
      -m state --state ESTABLISHED -m u32 --u32 \
      "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
       0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
       0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
      -j SSLv3
    

Note: mind the order of the rules. Those rules did not work for me until I put them above this one I had on my firewall script:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

CSS: Creating textured backgrounds

Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.

In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.

How do you get the logical xor of two variables in Python?

Rewarding thread:

Anoder idea... Just you try the (may be) pythonic expression «is not» in order to get behavior of logical «xor»

The truth table would be:

>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> False is not False
False
>>>

And for your example string:

>>> "abc" is not  ""
True
>>> 'abc' is not 'abc' 
False
>>> 'abc' is not '' 
True
>>> '' is not 'abc' 
True
>>> '' is not '' 
False
>>> 

However; as they indicated above, it depends of the actual behavior you want to pull out about any couple strings, because strings aren't boleans... and even more: if you «Dive Into Python» you will find «The Peculiar Nature of "and" and "or"» http://www.diveintopython.net/power_of_introspection/and_or.html

Sorry my writed English, it's not my born language.

Regards.

ArrayList initialization equivalent to array initialization

This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-

List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();

It's a very cool library that saves you a tonne of time.

How can I quantify difference between two images?

What about calculating the Manhattan Distance of the two images. That gives you n*n values. Then you could do something like an row average to reduce to n values and a function over that to get one single value.

How to generate an MD5 file hash in JavaScript?

If you don't want to use libraries or other things, you can use this native javascript approach:

_x000D_
_x000D_
var MD5 = function(d){var r = M(V(Y(X(d),8*d.length)));return r.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}_x000D_
_x000D_
/** NORMAL words**/_x000D_
var value = 'test';_x000D_
_x000D_
var result = MD5(value);_x000D_
 _x000D_
document.body.innerHTML = 'hash -  normal words: ' + result;_x000D_
_x000D_
/** NON ENGLISH words**/_x000D_
value = '????'_x000D_
_x000D_
//unescape() can be deprecated for the new browser versions_x000D_
result = MD5(unescape(encodeURIComponent(value)));_x000D_
_x000D_
document.body.innerHTML += '<br><br>hash - non english words: ' + result;_x000D_
 
_x000D_
_x000D_
_x000D_

For non english words you may need to use unescape() and the encodeURIComponent() methods.

How can I revert multiple Git commits (already pushed) to a published repository?

If you've already pushed things to a remote server (and you have other developers working off the same remote branch) the important thing to bear in mind is that you don't want to rewrite history

Don't use git reset --hard

You need to revert changes, otherwise any checkout that has the removed commits in its history will add them back to the remote repository the next time they push; and any other checkout will pull them in on the next pull thereafter.

If you have not pushed changes to a remote, you can use

git reset --hard <hash>

If you have pushed changes, but are sure nobody has pulled them you can use

git reset --hard
git push -f

If you have pushed changes, and someone has pulled them into their checkout you can still do it but the other team-member/checkout would need to collaborate:

(you) git reset --hard <hash>
(you) git push -f

(them) git fetch
(them) git reset --hard origin/branch

But generally speaking that's turning into a mess. So, reverting:

The commits to remove are the lastest

This is possibly the most common case, you've done something - you've pushed them out and then realized they shouldn't exist.

First you need to identify the commit to which you want to go back to, you can do that with:

git log

just look for the commit before your changes, and note the commit hash. you can limit the log to the most resent commits using the -n flag: git log -n 5

Then reset your branch to the state you want your other developers to see:

git revert  <hash of first borked commit>..HEAD

The final step is to create your own local branch reapplying your reverted changes:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Continue working in my-new-branch until you're done, then merge it in to your main development branch.

The commits to remove are intermingled with other commits

If the commits you want to revert are not all together, it's probably easiest to revert them individually. Again using git log find the commits you want to remove and then:

git revert <hash>
git revert <another hash>
..

Then, again, create your branch for continuing your work:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Then again, hack away and merge in when you're done.

You should end up with a commit history which looks like this on my-new-branch

2012-05-28 10:11 AD7six             o [my-new-branch] Revert "Revert "another mistake""
2012-05-28 10:11 AD7six             o Revert "Revert "committing a mistake""
2012-05-28 10:09 AD7six             o [master] Revert "committing a mistake"
2012-05-28 10:09 AD7six             o Revert "another mistake"
2012-05-28 10:08 AD7six             o another mistake
2012-05-28 10:08 AD7six             o committing a mistake
2012-05-28 10:05 Bob                I XYZ nearly works

Better way®

Especially that now that you're aware of the dangers of several developers working in the same branch, consider using feature branches always for your work. All that means is working in a branch until something is finished, and only then merge it to your main branch. Also consider using tools such as git-flow to automate branch creation in a consistent way.

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

How to sum a list of integers with java streams?

From the docs

Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().

Of course, such operations can be readily implemented as simple sequential loops, as in:

int sum = 0;
for (int x : numbers) {
   sum += x;
}

However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:

int sum = numbers.stream().reduce(0, (x,y) -> x+y);

or:

int sum = numbers.stream().reduce(0, Integer::sum);

These reduction operations can run safely in parallel with almost no modification:

int sum = numbers.parallelStream().reduce(0, Integer::sum);

So, for a map you would use:

integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);

Or:

integers.values().stream().reduce(0, Integer::sum);

Specify sudo password for Ansible

This worked for me... Created file /etc/sudoers.d/90-init-users file with NOPASSWD

echo "user ALL=(ALL)       NOPASSWD:ALL" > 90-init-users

where "user" is your userid.

How to use NULL or empty string in SQL

You could use isnull function to get both null and empty values of a text field:

SELECT * FROM myTable
WHERE isnull(my_nullable_text_field,'') = ''

What's the right way to decode a string that has special HTML entities in it?

This is so good answer. You can use this with angular like this:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);

How do you count the number of occurrences of a certain substring in a SQL varchar?

If we know there is a limitation on LEN and space, why cant we replace the space first? Then we know there is no space to confuse LEN.

len(replace(@string, ' ', '-')) - len(replace(replace(@string, ' ', '-'), ',', ''))

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

Using @property versus getters and setters

The short answer is: properties wins hands down. Always.

There is sometimes a need for getters and setters, but even then, I would "hide" them to the outside world. There are plenty of ways to do this in Python (getattr, setattr, __getattribute__, etc..., but a very concise and clean one is:

def set_email(self, value):
    if '@' not in value:
        raise Exception("This doesn't look like an email address.")
    self._email = value

def get_email(self):
    return self._email

email = property(get_email, set_email)

Here's a brief article that introduces the topic of getters and setters in Python.

Unable to import path from django.urls

Python 2 doesn't support Django 2. On a Mac once you've installed Python 3 and Django 2 run the following command from shell to run your app while keeping path:

python3 manage.py runserver

Even if you have upgraded and are on a mac you will, by default, run Python 2 if you're entering the following command:

python manage.py runserver

The version of Django will then be wrong and you will see import errors for path

Detecting Enter keypress on VB.NET

Make sure the form KeyPreview property is set to true.

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If

End Sub

See whether an item appears more than once in a database column

It should be:

SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1

Regarding your initial query:

  1. You cannot do a SELECT * since this operation requires a GROUP BY and columns need to either be in the GROUP BY or in an aggregate function (i.e. COUNT, SUM, MIN, MAX, AVG, etc.)
  2. As this is a GROUP BY operation, a HAVING clause will filter it instead of a WHERE

Edit:

And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):

;WITH cte AS (
    SELECT  *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
    FROM    AXDelNotesNoTracking
)
SELECT  *
FROM    cte
WHERE   cte.Num > 1

Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.

Edit2:

The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.

SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
    (     SELECT SalesID
          FROM AXDelNotesNoTracking
          GROUP BY SalesID
          HAVING COUNT(*) > 1
    )
ORDER BY SalesID

The 'packages' element is not declared

Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.

See this similar question also.